patch
stringlengths 17
31.2k
| y
int64 1
1
| oldf
stringlengths 0
2.21M
| idx
int64 1
1
| id
int64 4.29k
68.4k
| msg
stringlengths 8
843
| proj
stringclasses 212
values | lang
stringclasses 9
values |
---|---|---|---|---|---|---|---|
@@ -21,6 +21,7 @@ public enum NetworkName {
SEPOLIA,
GOERLI,
DEV,
+ PREMERGE,
CLASSIC,
KOTTI,
MORDOR, | 1 | /*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.cli.config;
public enum NetworkName {
MAINNET,
RINKEBY,
ROPSTEN,
SEPOLIA,
GOERLI,
DEV,
CLASSIC,
KOTTI,
MORDOR,
ECIP1049_DEV,
ASTOR
}
| 1 | 26,900 | I don't think this is the type of network we should be putting in our named networks. | hyperledger-besu | java |
@@ -60,7 +60,15 @@ void generic_data_reader::setup() {
shuffle_indices();
}
+std::ofstream debug;
+
int lbann::generic_data_reader::fetch_data(CPUMat& X) {
+if (! debug.is_open()) {
+ char b[1024];
+ sprintf(b, "debug.%d", m_comm->get_rank_in_world());
+ debug.open(b);
+}
+if (get_role() == "train") debug << "\nstarting fetch_data ";
int nthreads = omp_get_max_threads();
if(!position_valid()) {
throw lbann_exception( | 1 | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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.
//
// lbann_data_reader .hpp .cpp - Input data base class for training, testing
////////////////////////////////////////////////////////////////////////////////
#include "lbann/data_readers/data_reader.hpp"
#include "lbann/data_store/generic_data_store.hpp"
#include <omp.h>
namespace lbann {
void generic_data_reader::shuffle_indices() {
// Shuffle the data
if (m_shuffle) {
std::shuffle(m_shuffled_indices.begin(), m_shuffled_indices.end(),
get_data_seq_generator());
}
}
void generic_data_reader::setup() {
m_base_offset = 0;
m_sample_stride = 1;
m_stride_to_next_mini_batch = 0;
m_stride_to_last_mini_batch = 0;
m_current_mini_batch_idx = 0;
m_num_iterations_per_epoch = 0;
m_global_mini_batch_size = 0;
m_global_last_mini_batch_size = 0;
m_world_master_mini_batch_adjustment = 0;
/// The amount of space needed will vary based on input layer type,
/// but the batch size is the maximum space necessary
El::Zeros(m_indices_fetched_per_mb, m_mini_batch_size, 1);
set_initial_position();
shuffle_indices();
}
int lbann::generic_data_reader::fetch_data(CPUMat& X) {
int nthreads = omp_get_max_threads();
if(!position_valid()) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__)
+ " :: generic data reader load error: !position_valid"
+ " -- current pos = " + std::to_string(m_current_pos)
+ " and there are " + std::to_string(m_shuffled_indices.size()) + " indices");
}
if (!m_save_minibatch_indices) {
/// Allow each thread to perform any preprocessing necessary on the
/// data source prior to fetching data
#pragma omp parallel for schedule(static, 1)
for (int t = 0; t < nthreads; t++) {
preprocess_data_source(omp_get_thread_num());
}
}
int loaded_batch_size = get_loaded_mini_batch_size();
const int end_pos = std::min(static_cast<size_t>(m_current_pos+loaded_batch_size),
m_shuffled_indices.size());
const int mb_size = std::min(
El::Int{((end_pos - m_current_pos) + m_sample_stride - 1) / m_sample_stride},
X.Width());
if (!m_save_minibatch_indices) {
El::Zeros(X, X.Height(), X.Width());
El::Zeros(m_indices_fetched_per_mb, mb_size, 1);
}
if (m_save_minibatch_indices) {
m_my_minibatch_indices.resize(m_my_minibatch_indices.size() + 1);
for (int s = 0; s < mb_size; s++) {
int n = m_current_pos + (s * m_sample_stride);
m_my_minibatch_indices.back().push_back(n);
}
}
else {
#pragma omp parallel for
for (int s = 0; s < mb_size; s++) {
// Catch exceptions within the OpenMP thread.
try {
int n = m_current_pos + (s * m_sample_stride);
int index = m_shuffled_indices[n];
bool valid = fetch_datum(X, index, s, omp_get_thread_num());
if (!valid) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic data reader load error: datum not valid");
}
m_indices_fetched_per_mb.Set(s, 0, index);
} catch (lbann_exception& e) {
lbann_report_exception(e);
} catch (std::exception& e) {
El::ReportException(e);
}
}
/// Allow each thread to perform any postprocessing necessary on the
/// data source prior to fetching data
#pragma omp parallel for schedule(static, 1)
for (int t = 0; t < nthreads; t++) {
postprocess_data_source(omp_get_thread_num());
}
}
return mb_size;
}
int lbann::generic_data_reader::fetch_labels(CPUMat& Y) {
if(!position_valid()) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic data reader load error: !position_valid");
}
int loaded_batch_size = get_loaded_mini_batch_size();
const int end_pos = std::min(static_cast<size_t>(m_current_pos+loaded_batch_size),
m_shuffled_indices.size());
const int mb_size = std::min(
El::Int{((end_pos - m_current_pos) + m_sample_stride - 1) / m_sample_stride},
Y.Width());
El::Zeros(Y, Y.Height(), Y.Width());
// if (m_data_store != nullptr) {
//@todo: get it to work, then add omp support
//m_data_store->fetch_labels(...);
// }
// else {
#pragma omp parallel for
for (int s = 0; s < mb_size; s++) {
// Catch exceptions within the OpenMP thread.
try {
int n = m_current_pos + (s * m_sample_stride);
int index = m_shuffled_indices[n];
bool valid = fetch_label(Y, index, s, omp_get_thread_num());
if (!valid) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic data reader load error: label not valid");
}
} catch (lbann_exception& e) {
lbann_report_exception(e);
} catch (std::exception& e) {
El::ReportException(e);
}
}
//}
return mb_size;
}
int lbann::generic_data_reader::fetch_responses(CPUMat& Y) {
if(!position_valid()) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic data reader load error: !position_valid");
}
int loaded_batch_size = get_loaded_mini_batch_size();
const int end_pos = std::min(static_cast<size_t>(m_current_pos+loaded_batch_size),
m_shuffled_indices.size());
const int mb_size = std::min(
El::Int{((end_pos - m_current_pos) + m_sample_stride - 1) / m_sample_stride},
Y.Width());
El::Zeros(Y, Y.Height(), Y.Width());
#pragma omp parallel for
for (int s = 0; s < mb_size; s++) {
// Catch exceptions within the OpenMP thread.
try {
int n = m_current_pos + (s * m_sample_stride);
int index = m_shuffled_indices[n];
bool valid = fetch_response(Y, index, s, omp_get_thread_num());
if (!valid) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic data reader load error: response not valid");
}
} catch (lbann_exception& e) {
lbann_report_exception(e);
} catch (std::exception& e) {
El::ReportException(e);
}
}
return mb_size;
}
bool generic_data_reader::is_data_reader_done(bool is_active_reader) {
bool reader_not_done = true;
if(is_active_reader) {
reader_not_done = !((m_loaded_mini_batch_idx + m_iteration_stride) >= m_num_iterations_per_epoch);
}else {
reader_not_done = !(m_loaded_mini_batch_idx >= m_num_iterations_per_epoch);
}
return reader_not_done;
}
bool generic_data_reader::update(bool is_active_reader) {
bool reader_not_done = true; // BVE The sense of this should be fixed
m_current_mini_batch_idx++;
if(is_active_reader) {
m_current_pos = get_next_position();
/// Maintain the current height of the matrix
if (!m_save_minibatch_indices) {
El::Zeros(m_indices_fetched_per_mb, m_indices_fetched_per_mb.Height(), 1);
}
m_loaded_mini_batch_idx += m_iteration_stride;
}
if (m_loaded_mini_batch_idx >= m_num_iterations_per_epoch) {
reader_not_done = false;
}
if ((size_t)m_current_pos >= m_shuffled_indices.size()) {
reader_not_done = false;
}
if (m_current_mini_batch_idx == m_num_iterations_per_epoch) {
if ((get_rank() < m_num_parallel_readers) && (m_current_pos < (int)m_shuffled_indices.size())) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__)
+ " :: generic data reader update error: the epoch is complete,"
+ " but not all of the data has been used -- current pos = " + std::to_string(m_current_pos)
+ " and there are " + std::to_string(m_shuffled_indices.size()) + " indices"
+ " : iteration="
+ std::to_string(m_current_mini_batch_idx) + "C ["
+ std::to_string(m_loaded_mini_batch_idx) +"L] of "
+ std::to_string(m_num_iterations_per_epoch) + "+"
+ std::to_string(m_iteration_stride) + " : "
+ " index stride="
+ std::to_string(m_stride_to_next_mini_batch) + "/"
+ std::to_string(m_stride_to_last_mini_batch));
}
if (!m_save_minibatch_indices) {
shuffle_indices();
}
set_initial_position();
if (!m_save_minibatch_indices) {
if (m_data_store) {
m_data_store->set_shuffled_indices(&m_shuffled_indices);
}
}
}
return reader_not_done;
}
int generic_data_reader::get_loaded_mini_batch_size() const {
if (m_loaded_mini_batch_idx >= (m_num_iterations_per_epoch-1)) {
return m_last_mini_batch_size;
} else {
return m_mini_batch_size;
}
}
int generic_data_reader::get_current_mini_batch_size() const {
if (m_current_mini_batch_idx == (m_num_iterations_per_epoch-1)) {
return m_last_mini_batch_size + m_world_master_mini_batch_adjustment;
} else {
return m_mini_batch_size;
}
}
int generic_data_reader::get_current_global_mini_batch_size() const {
if (m_current_mini_batch_idx == (m_num_iterations_per_epoch-1)) {
return m_global_last_mini_batch_size;
} else {
return m_global_mini_batch_size;
}
}
/// Returns the current adjustment to the mini-batch size based on if
/// the world master (model 0) has any extra samples
/// Note that any rank in model 0 does not need to add in this offset
/// since the model will already be aware of the extra samples
int generic_data_reader::get_current_world_master_mini_batch_adjustment(int model_rank) const {
if (model_rank != 0 && m_current_mini_batch_idx == (m_num_iterations_per_epoch-1)) {
return m_world_master_mini_batch_adjustment;
} else {
return 0;
}
}
int generic_data_reader::get_next_position() const {
/// If the next mini-batch for this rank is going to be the last
/// mini-batch, take the proper (possibly reduced) step to
/// setup for the last mini-batch
if ((m_current_mini_batch_idx + m_iteration_stride - 1) == (m_num_iterations_per_epoch-1)) {
return m_current_pos + m_stride_to_last_mini_batch;
} else {
return m_current_pos + m_stride_to_next_mini_batch;
}
}
void generic_data_reader::select_subset_of_data() {
m_num_global_indices = m_shuffled_indices.size();
shuffle_indices();
size_t count = get_absolute_sample_count();
double use_percent = get_use_percent();
if (count == 0 and use_percent == 0.0) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic_data_reader::select_subset_of_data() get_use_percent() "
+ "and get_absolute_sample_count() are both zero; exactly one "
+ "must be zero");
}
if (!(count == 0 or use_percent == 0.0)) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic_data_reader::select_subset_of_data() get_use_percent() "
"and get_absolute_sample_count() are both non-zero; exactly one "
"must be zero");
}
if (count != 0) {
if(count > static_cast<size_t>(get_num_data())) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: generic_data_reader::select_subset_of_data() - absolute_sample_count=" +
std::to_string(count) + " is > get_num_data=" +
std::to_string(get_num_data()));
}
m_shuffled_indices.resize(get_absolute_sample_count());
}
if (use_percent) {
m_shuffled_indices.resize(get_use_percent()*get_num_data());
}
long unused = get_validation_percent()*get_num_data(); //get_num_data() = m_shuffled_indices.size()
long use_me = get_num_data() - unused;
if (unused > 0) {
m_unused_indices=std::vector<int>(m_shuffled_indices.begin() + use_me, m_shuffled_indices.end());
m_shuffled_indices.resize(use_me);
}
if(!m_shuffle) {
std::sort(m_shuffled_indices.begin(), m_shuffled_indices.end());
std::sort(m_unused_indices.begin(), m_unused_indices.end());
}
}
void generic_data_reader::use_unused_index_set() {
m_shuffled_indices.swap(m_unused_indices);
m_unused_indices.clear();
std::vector<int>().swap(m_unused_indices); // Trick to force memory reallocation
}
/** \brief Given directory to store checkpoint files, write state to file and add to number of bytes written */
bool generic_data_reader::save_to_checkpoint_shared(persist& p, const char *name) {
// rank 0 writes the training state file
if (m_comm->am_model_master()) {
pack_scalars(p,name);
}
return true;
}
/** \brief Given directory to store checkpoint files, read state from file and add to number of bytes read */
bool lbann::generic_data_reader::load_from_checkpoint_shared(persist& p, const char *name) {
// rank 0 reads the training state file
struct packing_header header;
if (m_comm->am_model_master()) {
unpack_scalars(p,&header,name);
}
m_comm->model_broadcast(0, header);
unpack_header(header);
m_comm->model_broadcast(0, m_shuffled_indices);
// Adjust current position to deal with fact that it was just loaded to all ranks from rank 0 (differs by rank #)
m_current_pos += m_comm->get_rank_in_model();
return true;
}
bool generic_data_reader::save_to_checkpoint_distributed(persist& p, const char *name) {
pack_scalars(p,name);
return true;
}
bool lbann::generic_data_reader::load_from_checkpoint_distributed(persist& p, const char *name) {
struct packing_header header;
unpack_scalars(p,&header,name);
return true;
}
void generic_data_reader::set_file_dir(std::string s) {
if(endsWith(s, "/")) {
m_file_dir = s;
}else {
m_file_dir = s + "/";
}
}
void generic_data_reader::set_local_file_dir(std::string s) {
if(endsWith(s, "/")) {
m_local_file_dir = s;
}else {
m_local_file_dir = s + "/";
}
}
std::string generic_data_reader::get_file_dir() const {
return m_file_dir;
}
std::string generic_data_reader::get_local_file_dir() const {
return m_local_file_dir;
}
void generic_data_reader::set_data_filename(std::string s) {
m_data_fn = s;
}
std::string generic_data_reader::get_data_filename() const {
if (m_data_fn == "") {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: you apparently did not call set_data_filename; error!");
}
return m_data_fn;
}
void generic_data_reader::set_label_filename(std::string s) {
m_label_fn = s;
}
std::string generic_data_reader::get_label_filename() const {
if (m_label_fn == "") {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: you apparently did not call set_label_filename; error!");
}
return m_label_fn;
}
void generic_data_reader::set_first_n(int n) {
m_first_n = n;
}
void generic_data_reader::set_absolute_sample_count(size_t s) {
m_absolute_sample_count = s;
}
size_t generic_data_reader::get_absolute_sample_count() const {
return m_absolute_sample_count;
}
void generic_data_reader::set_validation_percent(double s) {
if (s < 0 or s > 1.0) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: set_validation_percent() - must be: s >= 0, s <= 1.0; you passed: " +
std::to_string(s));
}
m_validation_percent = s;
}
double generic_data_reader::get_validation_percent() const {
return m_validation_percent;
}
void generic_data_reader::set_use_percent(double s) {
if (s < 0 or s > 1.0) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: set_use_percent() - must be: s >= 0, s <= 1.0; you passed: " +
std::to_string(s));
}
m_use_percent = s;
}
double generic_data_reader::get_use_percent() const {
return m_use_percent;
}
void generic_data_reader::setup_data_store(model *m) {
m_data_store = nullptr;
}
void generic_data_reader::set_save_minibatch_entries(bool b) {
m_save_minibatch_indices = b;
if (b) {
m_my_minibatch_indices.reserve(get_num_iterations_per_epoch());
}
}
void generic_data_reader::set_data_store(generic_data_store *g) {
if (m_data_store != nullptr) {
delete m_data_store;
}
m_data_store = g;
}
void generic_data_reader::init_minibatch() {
if (m_data_store != nullptr) {
m_data_store->init_minibatch();
}
}
} // namespace lbann
| 1 | 13,027 | debug? I suspect this will be removed before merge? | LLNL-lbann | cpp |
@@ -42,7 +42,12 @@ describe('Operation (Generators)', function() {
// LINE test = require('assert');
// LINE
// LINE co(function*() {
- // LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
+ // LINE const client = new MongoClient('mongodb://localhost:27017/test');
+ // LINE yield client.connect();
+ // LINE
+ // LINE const client = new MongoClient('mongodb://localhost:27017/test');
+ // LINE yield client.connect();
+ // LINE
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN | 1 | 'use strict';
var test = require('./shared').assert;
var setupDatabase = require('./shared').setupDatabase;
var Buffer = require('safe-buffer').Buffer;
/**************************************************************************
*
* COLLECTION TESTS
*
*************************************************************************/
describe('Operation (Generators)', function() {
before(function() {
return setupDatabase(this.configuration);
});
/**
* Call toArray on an aggregation cursor using ES6 generators and the co module
*
* @example-class Collection
* @example-method aggregate
* @ignore
*/
it('aggregationExample2WithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, mongodb: '>2.1.0', topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Some docs for insertion
var docs = [
{
title: 'this is my title',
author: 'bob',
posted: new Date(),
pageViews: 5,
tags: ['fun', 'good', 'fun'],
other: { foo: 5 },
comments: [
{ author: 'joe', text: 'this is cool' },
{ author: 'sam', text: 'this is bad' }
]
}
];
// Create a collection
var collection = db.collection('aggregationExample2_with_generatorsGenerator');
// Insert the docs
yield collection.insertMany(docs, { w: 1 });
// Execute aggregate, notice the pipeline is expressed as an Array
var cursor = collection.aggregate(
[
{
$project: {
author: 1,
tags: 1
}
},
{ $unwind: '$tags' },
{
$group: {
_id: { tags: '$tags' },
authors: { $addToSet: '$author' }
}
}
],
{ cursor: { batchSize: 1 } }
);
// Get all the aggregation results
docs = yield cursor.toArray();
test.equal(2, docs.length);
client.close();
});
// END
}
});
/**
* Call next on an aggregation cursor using a Generator and the co module
*
* @example-class AggregationCursor
* @example-method next
* @ignore
*/
it('Aggregation Cursor next Test with Generators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, mongodb: '>2.1.0', topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Some docs for insertion
var docs = [
{
title: 'this is my title',
author: 'bob',
posted: new Date(),
pageViews: 5,
tags: ['fun', 'good', 'fun'],
other: { foo: 5 },
comments: [
{ author: 'joe', text: 'this is cool' },
{ author: 'sam', text: 'this is bad' }
]
}
];
// Create a collection
var collection = db.collection('aggregation_next_example_with_generatorsGenerator');
// Insert the docs
yield collection.insertMany(docs, { w: 1 });
// Execute aggregate, notice the pipeline is expressed as an Array
var cursor = collection.aggregate(
[
{
$project: {
author: 1,
tags: 1
}
},
{ $unwind: '$tags' },
{
$group: {
_id: { tags: '$tags' },
authors: { $addToSet: '$author' }
}
}
],
{ cursor: { batchSize: 1 } }
);
// Get all the aggregation results
yield cursor.next();
// Closing cursor to close implicit session,
// since the cursor is not exhausted
cursor.close();
client.close();
});
// END
}
});
/**
* Example of running simple count commands against a collection using a Generator and the co module.
*
* @example-class Collection
* @example-method count
* @ignore
*/
it('shouldCorrectlyDoSimpleCountExamplesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Crete the collection for the distinct example
var collection = db.collection('countExample1_with_generators');
// Insert documents to perform distinct against
yield collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4, b: 1 }], {
w: 1
});
// Perform a total count command
var count = yield collection.count();
test.equal(4, count);
// Perform a partial account where b=1
count = yield collection.count({ b: 1 });
test.equal(1, count);
// Close database
client.close();
});
// END
}
});
/**
* A more complex createIndex using a Generator and the co module and a compound unique index in the background and dropping duplicated documents
*
* @example-class Collection
* @example-method createIndex
* @ignore
*/
it('shouldCreateComplexIndexOnTwoFieldsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('createIndexExample1_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
configuration.writeConcernMax()
);
// Create an index on the a field
yield collection.createIndex({ a: 1, b: 1 }, { unique: true, background: true, w: 1 });
// Show that duplicate records got dropped
var items = yield collection.find({}).toArray();
test.equal(4, items.length);
// Perform a query, with explain to show we hit the query
var explanation = yield collection.find({ a: 2 }).explain();
test.ok(explanation != null);
client.close();
});
// END
}
});
/**
* Example of running the distinct command using a Generator and the co module against a collection
*
* @example-class Collection
* @example-method distinct
* @ignore
*/
it('shouldCorrectlyHandleDistinctIndexesWithSubQueryFilterWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Crete the collection for the distinct example
var collection = db.collection('distinctExample1_with_generators');
// Insert documents to perform distinct against
yield collection.insertMany(
[
{ a: 0, b: { c: 'a' } },
{ a: 1, b: { c: 'b' } },
{ a: 1, b: { c: 'c' } },
{ a: 2, b: { c: 'a' } },
{ a: 3 },
{ a: 3 }
],
configuration.writeConcernMax()
);
// Perform a distinct query against the a field
var docs = yield collection.distinct('a');
test.deepEqual([0, 1, 2, 3], docs.sort());
// Perform a distinct query against the sub-field b.c
docs = yield collection.distinct('b.c');
test.deepEqual(['a', 'b', 'c'], docs.sort());
client.close();
});
// END
}
});
/**
* Example of running the distinct command against a collection using a Generator and the co module with a filter query
*
* @ignore
*/
it('shouldCorrectlyHandleDistinctIndexesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Crete the collection for the distinct example
var collection = db.collection('distinctExample2_with_generators');
// Insert documents to perform distinct against
yield collection.insertMany(
[
{ a: 0, b: { c: 'a' } },
{ a: 1, b: { c: 'b' } },
{ a: 1, b: { c: 'c' } },
{ a: 2, b: { c: 'a' } },
{ a: 3 },
{ a: 3 },
{ a: 5, c: 1 }
],
configuration.writeConcernMax()
);
// Perform a distinct query with a filter against the documents
var docs = yield collection.distinct('a', { c: 1 });
test.deepEqual([5], docs.sort());
client.close();
});
// END
}
});
/**
* Example of Collection.prototype.drop using a Generator and the co module
*
* @example-class Collection
* @example-method drop
* @ignore
*/
it('shouldCorrectlyDropCollectionWithDropFunctionWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = yield db.createCollection('test_other_drop_with_generators');
// Drop the collection
yield collection.drop();
// Ensure we don't have the collection in the set of names
var replies = yield db.listCollections().toArray();
// Did we find the collection
var found = false;
// For each collection in the list of collection names in this db look for the
// dropped collection
replies.forEach(function(document) {
if (document.name === 'test_other_drop_with_generators') {
found = true;
return;
}
});
// Ensure the collection is not found
test.equal(false, found);
// Let's close the db
client.close();
});
// END
}
});
/**
* Example of a how to drop all the indexes on a collection using dropAllIndexes with a Generator and the co module
*
* @example-class Collection
* @example-method dropAllIndexes
* @ignore
*/
it('dropAllIndexesExample1WithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
yield db.createCollection('dropExample1_with_generators');
// Drop the collection
yield db.collection('dropExample1_with_generators').dropAllIndexes();
// Let's close the db
client.close();
});
// END
}
});
/**
* An examples showing the creation and dropping of an index using a Generator and the co module
*
* @example-class Collection
* @example-method dropIndex
* @ignore
*/
it('shouldCorrectlyCreateAndDropIndexWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
var collection = db.collection('dropIndexExample1_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
{ w: 1 }
);
// Create an index on the a field
yield collection.ensureIndex({ a: 1, b: 1 }, { unique: true, background: true, w: 1 });
// Drop the index
yield collection.dropIndex('a_1_b_1');
// Verify that the index is gone
var indexInformation = yield collection.indexInformation();
test.deepEqual([['_id', 1]], indexInformation._id_);
test.equal(undefined, indexInformation.a_1_b_1);
// Close db
client.close();
});
// END
}
});
/**
* A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents using a Generator and the co module.
*
* @example-class Collection
* @example-method ensureIndex
* @ignore
*/
it('shouldCreateComplexEnsureIndexWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
var collection = db.collection('ensureIndexExample1_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
configuration.writeConcernMax()
);
// Create an index on the a field
yield db.ensureIndex(
'ensureIndexExample1_with_generators',
{ a: 1, b: 1 },
{ unique: true, background: true, w: 1 }
);
// Show that duplicate records got dropped
var items = yield collection.find({}).toArray();
test.equal(4, items.length);
// Perform a query, with explain to show we hit the query
var explanation = yield collection.find({ a: 2 }).explain();
test.ok(explanation != null);
client.close();
});
// END
}
});
/**
* A more complex ensureIndex using a compound unique index in the background using a Generator and the co module.
*
* @example-class Collection
* @example-method ensureIndex
* @ignore
*/
it('ensureIndexExampleWithCompountIndexWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
var collection = db.collection('ensureIndexExample2_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
{ w: 1 }
);
// Create an index on the a field
yield collection.ensureIndex({ a: 1, b: 1 }, { unique: true, background: true, w: 1 });
// Show that duplicate records got dropped
var items = yield collection.find({}).toArray();
test.equal(4, items.length);
// Perform a query, with explain to show we hit the query
var explanation = yield collection.find({ a: 2 }).explain();
test.ok(explanation != null);
// Close db
client.close();
});
// END
}
});
/**
* A simple query using the find method and toArray method with a Generator and the co module.
*
* @example-class Collection
* @example-method find
* @ignore
*/
it('shouldPerformASimpleQueryWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('simple_query_with_generators');
// Insert a bunch of documents for the testing
yield collection.insertMany(
[{ a: 1 }, { a: 2 }, { a: 3 }],
configuration.writeConcernMax()
);
// Perform a simple find and return all the documents
var docs = yield collection.find().toArray();
test.equal(3, docs.length);
// Close the db
client.close();
});
// END
}
});
/**
* A simple query showing the explain for a query using a Generator and the co module.
*
* @example-class Collection
* @example-method find
* @ignore
*/
it('shouldPerformASimpleExplainQueryWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('simple_explain_query_with_generators');
// Insert a bunch of documents for the testing
yield collection.insertMany(
[{ a: 1 }, { a: 2 }, { a: 3 }],
configuration.writeConcernMax()
);
// Perform a simple find and return all the documents
var explain = yield collection.find({}).explain();
test.ok(explain != null);
client.close();
});
// END
}
});
/**
* A simple query showing skip and limit using a Generator and the co module.
*
* @example-class Collection
* @example-method find
* @ignore
*/
it('shouldPerformASimpleLimitSkipQueryWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('simple_limit_skip_query_with_generators');
// Insert a bunch of documents for the testing
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }],
configuration.writeConcernMax()
);
// Perform a simple find and return all the documents
var docs = yield collection
.find({})
.skip(1)
.limit(1)
.project({ b: 1 })
.toArray();
test.equal(1, docs.length);
test.equal(undefined, docs[0].a);
test.equal(2, docs[0].b);
// Close db
client.close();
});
// END
}
});
/**
* A whole set of different ways to use the findAndModify command with a Generator and the co module..
*
* The first findAndModify command modifies a document and returns the modified document back.
* The second findAndModify command removes the document.
* The second findAndModify command upserts a document and returns the new document.
*
* @example-class Collection
* @example-method findAndModify
* @ignore
*/
it('shouldPerformSimpleFindAndModifyOperationsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('simple_find_and_modify_operations_with_generators');
// Insert some test documentations
yield collection.insertMany(
[{ a: 1 }, { b: 1 }, { c: 1 }],
configuration.writeConcernMax()
);
// Simple findAndModify command returning the new document
var doc = yield collection.findAndModify(
{ a: 1 },
[['a', 1]],
{ $set: { b1: 1 } },
{ new: true }
);
test.equal(1, doc.value.a);
test.equal(1, doc.value.b1);
// Simple findAndModify command returning the new document and
// removing it at the same time
doc = yield collection.findAndModify(
{ b: 1 },
[['b', 1]],
{ $set: { b: 2 } },
{ remove: true }
);
// Verify that the document is gone
var item = yield collection.findOne({ b: 1 });
test.equal(null, item);
// Simple findAndModify command performing an upsert and returning the new document
// executing the command safely
doc = yield collection.findAndModify(
{ d: 1 },
[['b', 1]],
{ d: 1, f: 1 },
{ new: true, upsert: true, w: 1 }
);
test.equal(1, doc.value.d);
test.equal(1, doc.value.f);
// Close the db
client.close();
});
// END
}
});
/**
* An example of using findAndRemove using a Generator and the co module.
*
* @example-class Collection
* @example-method findAndRemove
* @ignore
*/
it('shouldPerformSimpleFindAndRemoveWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('simple_find_and_modify_operations_2_with_generators');
// Insert some test documentations
yield collection.insertMany(
[{ a: 1 }, { b: 1, d: 1 }, { c: 1 }],
configuration.writeConcernMax()
);
// Simple findAndModify command returning the old document and
// removing it at the same time
var doc = yield collection.findAndRemove({ b: 1 }, [['b', 1]]);
test.equal(1, doc.value.b);
test.equal(1, doc.value.d);
// Verify that the document is gone
var item = yield collection.findOne({ b: 1 });
test.equal(null, item);
// Db close
client.close();
});
// END
}
});
/**
* A simple query using findOne with a Generator and the co module.
*
* @example-class Collection
* @example-method findOne
* @ignore
*/
it('shouldPerformASimpleLimitSkipFindOneQueryWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('simple_limit_skip_find_one_query_with_generators');
// Insert a bunch of documents for the testing
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }],
configuration.writeConcernMax()
);
// Perform a simple find and return all the documents
var doc = yield collection.findOne({ a: 2 }, { fields: { b: 1 } });
test.equal(undefined, doc.a);
test.equal(2, doc.b);
// Db close
client.close();
});
// END
}
});
/**
* Example of a simple geoHaystackSearch query across some documents using a Generator and the co module.
*
* @example-class Collection
* @example-method geoHaystackSearch
* @ignore
*/
it('shouldCorrectlyPerformSimpleGeoHaystackSearchCommandWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch the collection
var collection = db.collection('simple_geo_haystack_command_with_generators');
// Add a location based index
yield collection.ensureIndex({ loc: 'geoHaystack', type: 1 }, { bucketSize: 1 });
// Save a new location tagged document
yield collection.insertMany(
[{ a: 1, loc: [50, 30] }, { a: 1, loc: [30, 50] }],
configuration.writeConcernMax()
);
// Use geoHaystackSearch command to find document
var docs = yield collection.geoHaystackSearch(50, 50, {
search: { a: 1 },
limit: 1,
maxDistance: 100
});
test.equal(1, docs.results.length);
client.close();
});
// END
}
});
/**
* A whole lot of different ways to execute the group command using a Generator and the co module.
*
* @example-class Collection
* @example-method group
* @ignore
*/
it('shouldCorrectlyExecuteGroupFunctionWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
Code = configuration.require.Code;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection
var collection = db.collection('test_group_with_generators');
// Perform a simple group by on an empty collection
var results = yield collection.group(
[],
{},
{ count: 0 },
'function (obj, prev) { prev.count++; }'
);
test.deepEqual([], results);
// Trigger some inserts on the collection
yield collection.insertMany([{ a: 2 }, { b: 5 }, { a: 1 }], { w: 1 });
// Perform a group count
results = yield collection.group(
[],
{},
{ count: 0 },
'function (obj, prev) { prev.count++; }'
);
test.equal(3, results[0].count);
// Perform a group count using the eval method
results = yield collection.group(
[],
{},
{ count: 0 },
'function (obj, prev) { prev.count++; }',
false
);
test.equal(3, results[0].count);
// Group with a conditional
results = yield collection.group(
[],
{ a: { $gt: 1 } },
{ count: 0 },
'function (obj, prev) { prev.count++; }'
);
// Results
test.equal(1, results[0].count);
// Group with a conditional using the EVAL method
results = yield collection.group(
[],
{ a: { $gt: 1 } },
{ count: 0 },
'function (obj, prev) { prev.count++; }',
false
);
// Results
test.equal(1, results[0].count);
// Insert some more test data
yield collection.insertMany([{ a: 2 }, { b: 3 }], { w: 1 });
// Do a Group by field a
results = yield collection.group(
['a'],
{},
{ count: 0 },
'function (obj, prev) { prev.count++; }'
);
// Results
test.equal(2, results[0].a);
test.equal(2, results[0].count);
test.equal(null, results[1].a);
test.equal(2, results[1].count);
test.equal(1, results[2].a);
test.equal(1, results[2].count);
// Do a Group by field a
results = yield collection.group(
{ a: true },
{},
{ count: 0 },
function(obj, prev) {
prev.count++;
},
true
);
// Results
test.equal(2, results[0].a);
test.equal(2, results[0].count);
test.equal(null, results[1].a);
test.equal(2, results[1].count);
test.equal(1, results[2].a);
test.equal(1, results[2].count);
try {
// Correctly handle illegal function
results = yield collection.group([], {}, {}, '5 ++ 5');
} catch (err) {
test.ok(err.message != null);
// Use a function to select the keys used to group by
var keyf = function(doc) {
return { a: doc.a };
};
results = yield collection.group(
keyf,
{ a: { $gt: 0 } },
{ count: 0, value: 0 },
function(obj, prev) {
prev.count++;
prev.value += obj.a;
},
true
);
// Results
results.sort(function(a, b) {
return b.count - a.count;
});
test.equal(2, results[0].count);
test.equal(2, results[0].a);
test.equal(4, results[0].value);
test.equal(1, results[1].count);
test.equal(1, results[1].a);
test.equal(1, results[1].value);
// Use a Code object to select the keys used to group by
keyf = new Code(function(doc) {
return { a: doc.a };
});
results = yield collection.group(
keyf,
{ a: { $gt: 0 } },
{ count: 0, value: 0 },
function(obj, prev) {
prev.count++;
prev.value += obj.a;
},
true
);
// Results
results.sort(function(a, b) {
return b.count - a.count;
});
test.equal(2, results[0].count);
test.equal(2, results[0].a);
test.equal(4, results[0].value);
test.equal(1, results[1].count);
test.equal(1, results[1].a);
test.equal(1, results[1].value);
try {
yield collection.group([], {}, {}, '5 ++ 5', false);
} catch (err) {
test.ok(err.message != null);
client.close();
}
}
});
// END
}
});
/**
* A simple map reduce example using a Generator and the co module.
*
* @example-class Collection
* @example-method mapReduce
* @ignore
*/
it('shouldPerformSimpleMapReduceFunctionsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection
var collection = db.collection('test_map_reduce_functions_with_generators');
// Insert some documents to perform map reduce over
yield collection.insertMany([{ user_id: 1 }, { user_id: 2 }], { w: 1 });
// Map function
var map = function() {
emit(this.user_id, 1); // eslint-disable-line
};
// Reduce function
// eslint-disable-next-line
var reduce = function(k, vals) {
return 1;
};
// Perform the map reduce
collection = yield collection.mapReduce(map, reduce, {
out: { replace: 'tempCollection' }
});
// Mapreduce returns the temporary collection with the results
var result = yield collection.findOne({ _id: 1 });
test.equal(1, result.value);
result = yield collection.findOne({ _id: 2 });
test.equal(1, result.value);
// Db close
client.close();
});
// END
}
});
/**
* A simple map reduce example using the inline output type on MongoDB > 1.7.6 returning the statistics using a Generator and the co module.
*
* @example-class Collection
* @example-method mapReduce
* @ignore
*/
it('shouldPerformMapReduceFunctionInlineWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, mongodb: '>1.7.6', topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection
var collection = db.collection('test_map_reduce_functions_inline_with_generators');
// Insert some test documents
yield collection.insertMany([{ user_id: 1 }, { user_id: 2 }], { w: 1 });
// Map function
var map = function() {
emit(this.user_id, 1); // eslint-disable-line
};
// Reduce function
// eslint-disable-next-line
var reduce = function(k, vals) {
return 1;
};
// Execute map reduce and return results inline
var result = yield collection.mapReduce(map, reduce, { out: { inline: 1 }, verbose: true });
test.equal(2, result.results.length);
test.ok(result.stats != null);
result = yield collection.mapReduce(map, reduce, {
out: { replace: 'mapreduce_integration_test' },
verbose: true
});
test.ok(result.stats != null);
client.close();
});
// END
}
});
/**
* Mapreduce using a provided scope containing a javascript function executed using a Generator and the co module.
*
* @example-class Collection
* @example-method mapReduce
* @ignore
*/
it('shouldPerformMapReduceWithContextWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
Code = configuration.require.Code;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection
var collection = db.collection('test_map_reduce_functions_scope_with_generators');
// Insert some test documents
yield collection.insertMany(
[{ user_id: 1, timestamp: new Date() }, { user_id: 2, timestamp: new Date() }],
{ w: 1 }
);
// Map function
var map = function() {
emit(fn(this.timestamp.getYear()), 1); // eslint-disable-line
};
// Reduce function
var reduce = function(k, v) {
var count = 0;
for (var i = 0; i < v.length; i++) {
count += v[i];
}
return count;
};
// Javascript function available in the map reduce scope
var t = function(val) {
return val + 1;
};
// Execute the map reduce with the custom scope
var o = {};
o.scope = { fn: new Code(t.toString()) };
o.out = { replace: 'replacethiscollection' };
// Execute with output collection
var outCollection = yield collection.mapReduce(map, reduce, o);
// Find all entries in the map-reduce collection
var results = yield outCollection.find().toArray();
test.equal(2, results[0].value);
// mapReduce with scope containing plain function
o = {};
o.scope = { fn: t };
o.out = { replace: 'replacethiscollection' };
// Execute with outCollection
outCollection = yield collection.mapReduce(map, reduce, o);
// Find all entries in the map-reduce collection
results = yield outCollection.find().toArray();
test.equal(2, results[0].value);
client.close();
});
// END
}
});
/**
* Mapreduce using a scope containing javascript objects with functions using a Generator and the co module.
*
* @example-class Collection
* @example-method mapReduce
* @ignore
*/
it.skip('shouldPerformMapReduceInContextObjectsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
Code = configuration.require.Code;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection
var collection = db.collection('test_map_reduce_functions_scope_objects_with_generators');
// Insert some test documents
yield collection.insertMany(
[{ user_id: 1, timestamp: new Date() }, { user_id: 2, timestamp: new Date() }],
{ w: 1 }
);
// Map function
var map = function() {
emit(obj.fn(this.timestamp.getYear()), 1); // eslint-disable-line
};
// Reduce function
var reduce = function(k, v) {
var count = 0;
for (var i = 0; i < v.length; i++) {
count += v[i];
}
return count;
};
// Javascript function available in the map reduce scope
var t = function(val) {
return val + 1;
};
// Execute the map reduce with the custom scope containing objects
var o = {};
o.scope = { obj: { fn: new Code(t.toString()) } };
o.out = { replace: 'replacethiscollection' };
// Execute returning outCollection
var outCollection = yield collection.mapReduce(map, reduce, o);
// Find all entries in the map-reduce collection
var results = yield outCollection.find().toArray();
test.equal(2, results[0].value);
// mapReduce with scope containing plain function
o = {};
o.scope = { obj: { fn: t } };
o.out = { replace: 'replacethiscollection' };
// Execute returning outCollection
outCollection = yield collection.mapReduce(map, reduce, o);
// Find all entries in the map-reduce collection
results = yield outCollection.find().toArray();
test.equal(2, results[0].value);
client.close();
});
// END
}
});
/**
* Example of retrieving a collections indexes using a Generator and the co module.
*
* @example-class Collection
* @example-method indexes
* @ignore
*/
it('shouldCorrectlyRetriveACollectionsIndexesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Crete the collection for the distinct example
var collection = db.collection('simple_key_based_distinct_with_generators');
// Create a geo 2d index
yield collection.ensureIndex({ loc: '2d' }, configuration.writeConcernMax());
// Create a simple single field index
yield collection.ensureIndex({ a: 1 }, configuration.writeConcernMax());
// List all of the indexes on the collection
var indexes = yield collection.indexes();
test.equal(3, indexes.length);
client.close();
});
// END
}
});
/**
* An example showing the use of the indexExists function using a Generator and the co module for a single index name and a list of index names.
*
* @example-class Collection
* @example-method indexExists
* @ignore
*/
it('shouldCorrectlyExecuteIndexExistsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection that we are getting the options back from
var collection = db.collection(
'test_collection_index_exists_with_generators',
configuration.writeConcernMax()
);
// Create an index on the collection
yield collection.createIndex('a', configuration.writeConcernMax());
// Let's test to check if a single index exists
var result = yield collection.indexExists('a_1');
test.equal(true, result);
// Let's test to check if multiple indexes are available
result = yield collection.indexExists(['a_1', '_id_']);
test.equal(true, result);
// Check if a non existing index exists
result = yield collection.indexExists('c_1');
test.equal(false, result);
client.close();
});
// END
}
});
/**
* An example showing the information returned by indexInformation using a Generator and the co module.
*
* @example-class Collection
* @example-method indexInformation
* @ignore
*/
it('shouldCorrectlyShowTheResultsFromIndexInformationWithGenerators', {
metadata: {
requires: { generators: true, topology: ['single'] }
},
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('more_index_information_test_2_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
configuration.writeConcernMax()
);
// Create an index on the a field
yield collection.ensureIndex({ a: 1, b: 1 }, { unique: true, background: true, w: 1 });
// Fetch basic indexInformation for collection
var indexInformation = yield db.indexInformation(
'more_index_information_test_2_with_generators'
);
test.deepEqual([['_id', 1]], indexInformation._id_);
test.deepEqual([['a', 1], ['b', 1]], indexInformation.a_1_b_1);
// Fetch full index information
indexInformation = yield collection.indexInformation({ full: true });
test.deepEqual({ _id: 1 }, indexInformation[0].key);
test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
// Close db
client.close();
});
// END
}
});
/**
* An examples showing the information returned by indexInformation using a Generator and the co module.
*
* @example-class Collection
* @example-method indexInformation
* @ignore
*/
it('shouldCorrectlyShowAllTheResultsFromIndexInformationWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('more_index_information_test_3_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
{ w: 1 }
);
// Create an index on the a field
yield collection.ensureIndex({ a: 1, b: 1 }, { unique: true, background: true, w: 1 });
// Fetch basic indexInformation for collection
var indexInformation = yield collection.indexInformation();
test.deepEqual([['_id', 1]], indexInformation._id_);
test.deepEqual([['a', 1], ['b', 1]], indexInformation.a_1_b_1);
// Fetch full index information
indexInformation = yield collection.indexInformation({ full: true });
test.deepEqual({ _id: 1 }, indexInformation[0].key);
test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key);
client.close();
});
// END
}
});
/**
* A simple document insert using a Generator and the co module example, not using safe mode to ensure document persistance on MongoDB
*
* @example-class Collection
* @example-method insert
* @ignore
*/
it('shouldCorrectlyPerformASimpleSingleDocumentInsertNoCallbackNoSafeWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
var collection = db.collection('simple_document_insert_collection_no_safe_with_generators');
// Insert a single document
yield collection.insertOne({ hello: 'world_no_safe' });
var item = yield collection.findOne({ hello: 'world_no_safe' });
test.equal('world_no_safe', item.hello);
client.close();
});
// END
}
});
/**
* A batch document insert using a Generator and the co module example, using safe mode to ensure document persistance on MongoDB
*
* @example-class Collection
* @example-method insert
* @ignore
*/
it('shouldCorrectlyPerformABatchDocumentInsertSafeWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch a collection to insert document into
var collection = db.collection('batch_document_insert_collection_safe_with_generators');
// Insert a single document
yield collection.insertMany(
[{ hello: 'world_safe1' }, { hello: 'world_safe2' }],
configuration.writeConcernMax()
);
// Fetch the document
var item = yield collection.findOne({ hello: 'world_safe2' });
test.equal('world_safe2', item.hello);
client.close();
});
// END
}
});
/**
* Example of inserting a document containing functions using a Generator and the co module.
*
* @example-class Collection
* @example-method insert
* @ignore
*/
it('shouldCorrectlyPerformASimpleDocumentInsertWithFunctionSafeWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch a collection to insert document into
var collection = db.collection('simple_document_insert_with_function_safe_with_generators');
// Get the option
var o = configuration.writeConcernMax();
o.serializeFunctions = true;
// Insert a single document
yield collection.insertOne({ hello: 'world', func: function() {} }, o);
// Fetch the document
var item = yield collection.findOne({ hello: 'world' });
test.ok('function() {}', item.code);
client.close();
});
// END
}
});
/**
* Example of using keepGoing to allow batch insert using a Generator and the co module to complete even when there are illegal documents in the batch
*
* @example-class Collection
* @example-method insert
* @ignore
*/
it('Should correctly execute insert with keepGoing option on mongod >= 1.9.1 with Generators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, mongodb: '>1.9.1', topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection
var collection = db.collection('keepGoingExample_with_generators');
// Add an unique index to title to force errors in the batch insert
yield collection.ensureIndex({ title: 1 }, { unique: true });
// Insert some intial data into the collection
yield collection.insertMany(
[{ name: 'Jim' }, { name: 'Sarah', title: 'Princess' }],
configuration.writeConcernMax()
);
try {
// Force keep going flag, ignoring unique index issue
yield collection.insert(
[
{ name: 'Jim' },
{ name: 'Sarah', title: 'Princess' },
{ name: 'Gump', title: 'Gump' }
],
{ w: 1, keepGoing: true }
);
} catch (err) {} // eslint-disable-line
// Count the number of documents left (should not include the duplicates)
var count = yield collection.count();
test.equal(3, count);
client.close();
});
// END
}
});
/**
* An example showing how to establish if it's a capped collection using a Generator and the co module.
*
* @example-class Collection
* @example-method isCapped
* @ignore
*/
it('shouldCorrectlyExecuteIsCappedWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection that we are getting the options back from
var collection = yield db.createCollection('test_collection_is_capped_with_generators', {
capped: true,
size: 1024
});
test.equal('test_collection_is_capped_with_generators', collection.collectionName);
// Let's fetch the collection options
var capped = yield collection.isCapped();
test.equal(true, capped);
client.close();
});
// END
}
});
/**
* An example returning the options for a collection using a Generator and the co module.
*
* @example-class Collection
* @example-method options
* @ignore
*/
it('shouldCorrectlyRetriveCollectionOptionsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a test collection that we are getting the options back from
var collection = yield db.createCollection('test_collection_options_with_generators', {
capped: true,
size: 1024
});
test.equal('test_collection_options_with_generators', collection.collectionName);
// Let's fetch the collection options
var options = yield collection.options();
test.equal(true, options.capped);
test.ok(options.size >= 1024);
client.close();
});
// END
}
});
/**
* A parallelCollectionScan example using a Generator and the co module.
*
* @example-class Collection
* @example-method parallelCollectionScan
* @ignore
*/
it('Should correctly execute parallelCollectionScan with multiple cursors with Generators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, mongodb: '>2.5.5', topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
var docs = [];
// Insert some documents
for (var i = 0; i < 1000; i++) {
docs.push({ a: i });
}
// Get the collection
var collection = db.collection('parallelCollectionScan_with_generators');
// Insert 1000 documents in a batch
yield collection.insertMany(docs);
var results = [];
var numCursors = 3;
// Execute parallelCollectionScan command
var cursors = yield collection.parallelCollectionScan({ numCursors: numCursors });
test.ok(cursors != null);
test.ok(cursors.length >= 0);
for (i = 0; i < cursors.length; i++) {
var items = yield cursors[i].toArray();
// Add docs to results array
results = results.concat(items);
}
test.equal(docs.length, results.length);
client.close();
});
// END
}
});
/**
* An example showing how to force a reindex of a collection using a Generator and the co module.
*
* @example-class Collection
* @example-method reIndex
* @ignore
*/
it('shouldCorrectlyIndexAndForceReindexOnCollectionWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('shouldCorrectlyForceReindexOnCollection_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4, c: 4 }],
{ w: 1 }
);
// Create an index on the a field
yield collection.ensureIndex({ a: 1, b: 1 }, { unique: true, background: true, w: 1 });
// Force a reindex of the collection
var result = yield collection.reIndex();
test.equal(true, result);
// Verify that the index is gone
var indexInformation = yield collection.indexInformation();
test.deepEqual([['_id', 1]], indexInformation._id_);
test.deepEqual([['a', 1], ['b', 1]], indexInformation.a_1_b_1);
client.close();
});
// END
}
});
/**
* An example removing all documents in a collection not using safe mode using a Generator and the co module.
*
* @example-class Collection
* @example-method remove
* @ignore
*/
it('shouldRemoveAllDocumentsNoSafeWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch a collection to insert document into
var collection = db.collection('remove_all_documents_no_safe_with_generators');
// Insert a bunch of documents
yield collection.insertMany([{ a: 1 }, { b: 2 }], { w: 1 });
// Remove all the document
collection.removeMany();
// Fetch all results
var items = yield collection.find().toArray();
test.equal(0, items.length);
client.close();
});
// END
}
});
/**
* An example removing a subset of documents using safe mode to ensure removal of documents using a Generator and the co module.
*
* @example-class Collection
* @example-method remove
* @ignore
*/
it('shouldRemoveSubsetOfDocumentsSafeModeWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch a collection to insert document into
var collection = db.collection('remove_subset_of_documents_safe_with_generators');
// Insert a bunch of documents
yield collection.insertMany([{ a: 1 }, { b: 2 }], { w: 1 });
// Remove all the document
var r = yield collection.removeOne({ a: 1 }, { w: 1 });
test.equal(1, r.result.n);
client.close();
});
// END
}
});
/**
* An example of illegal and legal renaming of a collection using a Generator and the co module.
*
* @example-class Collection
* @example-method rename
* @ignore
*/
it('shouldCorrectlyRenameCollectionWithGenerators', {
metadata: {
requires: { generators: true, topology: ['single'] }
},
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Open a couple of collections
var collection1 = yield db.createCollection('test_rename_collection_with_generators');
var collection2 = yield db.createCollection('test_rename_collection2_with_generators');
// Attemp to rename a collection to a number
try {
collection1.rename(5, function(err, collection) {}); // eslint-disable-line
} catch (err) {
test.ok(err instanceof Error);
test.equal('collection name must be a String', err.message);
}
// Attemp to rename a collection to an empty string
try {
collection1.rename('', function(err, collection) {}); // eslint-disable-line
} catch (err) {
test.ok(err instanceof Error);
test.equal('collection names cannot be empty', err.message);
}
// Attemp to rename a collection to an illegal name including the character $
try {
collection1.rename('te$t', function(err, collection) {}); // eslint-disable-line
} catch (err) {
test.ok(err instanceof Error);
test.equal("collection names must not contain '$'", err.message);
}
// Attemp to rename a collection to an illegal name starting with the character .
try {
collection1.rename('.test', function(err, collection) {}); // eslint-disable-line
} catch (err) {
test.ok(err instanceof Error);
test.equal("collection names must not start or end with '.'", err.message);
}
// Attemp to rename a collection to an illegal name ending with the character .
try {
collection1.rename('test.', function(err, collection) {}); // eslint-disable-line
} catch (err) {
test.ok(err instanceof Error);
test.equal("collection names must not start or end with '.'", err.message);
}
// Attemp to rename a collection to an illegal name with an empty middle name
try {
collection1.rename('tes..t', function(err, collection) {}); // eslint-disable-line
} catch (err) {
test.equal('collection names cannot be empty', err.message);
}
// Insert a couple of documents
yield collection1.insertMany([{ x: 1 }, { x: 2 }], configuration.writeConcernMax());
try {
// Attemp to rename the first collection to the second one, this will fail
yield collection1.rename('test_rename_collection2_with_generators');
} catch (err) {
test.ok(err instanceof Error);
test.ok(err.message.length > 0);
// Attemp to rename the first collection to a name that does not exist
// this will be succesful
collection2 = yield collection1.rename('test_rename_collection3_with_generators');
test.equal('test_rename_collection3_with_generators', collection2.collectionName);
// Ensure that the collection is pointing to the new one
var count = yield collection2.count();
test.equal(2, count);
client.close();
}
});
// END
}
});
/**
* Example of a simple document save with safe set to false using a Generator and the co module.
*
* @example-class Collection
* @example-method save
* @ignore
*/
it('shouldCorrectlySaveASimpleDocumentWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch the collection
var collection = db.collection('save_a_simple_document_with_generators');
// Save a document with no safe option
yield collection.save({ hello: 'world' });
// Find the saved document
var item = yield collection.findOne({ hello: 'world' });
test.equal('world', item && item.hello);
client.close();
});
// END
}
});
/**
* Example of a simple document save and then resave with safe set to true using a Generator and the co module.
*
* @example-class Collection
* @example-method save
* @ignore
*/
it('shouldCorrectlySaveASimpleDocumentModifyItAndResaveItWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch the collection
var collection = db.collection(
'save_a_simple_document_modify_it_and_resave_it_with_generators'
);
// Save a document with no safe option
yield collection.save({ hello: 'world' }, configuration.writeConcernMax());
// Find the saved document
var item = yield collection.findOne({ hello: 'world' });
test.equal('world', item.hello);
// Update the document
item['hello2'] = 'world2';
// Save the item with the additional field
yield collection.save(item, configuration.writeConcernMax());
// Find the changed document
item = yield collection.findOne({ hello: 'world' });
test.equal('world', item.hello);
test.equal('world2', item.hello2);
client.close();
});
// END
}
});
/**
* Example of a simple document update with safe set to false on an existing document using a Generator and the co module.
*
* @example-class Collection
* @example-method update
* @ignore
*/
it('shouldCorrectlyUpdateASimpleDocumentWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get a collection
var collection = db.collection('update_a_simple_document_with_generators');
// Insert a document, then update it
yield collection.insertOne({ a: 1 }, configuration.writeConcernMax());
// Update the document with an atomic operator
yield collection.updateOne({ a: 1 }, { $set: { b: 2 } });
var item = yield collection.findOne({ a: 1 });
test.equal(1, item.a);
test.equal(2, item.b);
client.close();
});
// END
}
});
/**
* Example of a simple document update using upsert (the document will be inserted if it does not exist) using a Generator and the co module.
*
* @example-class Collection
* @example-method update
* @ignore
*/
it('shouldCorrectlyUpsertASimpleDocumentWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get a collection
var collection = db.collection('update_a_simple_document_upsert_with_generators');
// Update the document using an upsert operation, ensuring creation if it does not exist
var result = yield collection.updateOne(
{ a: 1 },
{ $set: { b: 2, a: 1 } },
{ upsert: true, w: 1 }
);
test.equal(1, result.result.n);
// Fetch the document that we modified and check if it got inserted correctly
var item = yield collection.findOne({ a: 1 });
test.equal(1, item.a);
test.equal(2, item.b);
client.close();
});
// END
}
});
/**
* Example of an update across multiple documents using the multi option and using a Generator and the co module.
*
* @example-class Collection
* @example-method update
* @ignore
*/
it('shouldCorrectlyUpdateMultipleDocumentsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get a collection
var collection = db.collection('update_a_simple_document_multi_with_generators');
// Insert a couple of documentations
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 1, b: 2 }],
configuration.writeConcernMax()
);
var o = configuration.writeConcernMax();
var r = yield collection.updateMany({ a: 1 }, { $set: { b: 0 } }, o);
test.equal(2, r.result.n);
// Fetch all the documents and verify that we have changed the b value
var items = yield collection.find().toArray();
test.equal(1, items[0].a);
test.equal(0, items[0].b);
test.equal(1, items[1].a);
test.equal(0, items[1].b);
client.close();
});
// END
}
});
/**
* Example of retrieving a collections stats using a Generator and the co module.
*
* @example-class Collection
* @example-method stats
* @ignore
*/
it('shouldCorrectlyReturnACollectionsStatsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Crete the collection for the distinct example
var collection = db.collection('collection_stats_test_with_generators');
// Insert some documents
yield collection.insertMany(
[{ a: 1 }, { hello: 'world' }],
configuration.writeConcernMax()
);
// Retrieve the statistics for the collection
var stats = yield collection.stats();
test.equal(2, stats.count);
client.close();
});
// END
}
});
/**
* An examples showing the creation and dropping of an index using Generators.
*
* @example-class Collection
* @example-method dropIndexes
* @ignore
*/
it('shouldCorrectlyCreateAndDropAllIndexWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('shouldCorrectlyCreateAndDropAllIndex_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4, c: 4 }],
{ w: 1 }
);
// Create an index on the a field
yield collection.ensureIndex({ a: 1, b: 1 }, { unique: true, background: true, w: 1 });
// Create an additional index
yield collection.ensureIndex(
{ c: 1 },
{ unique: true, background: true, sparse: true, w: 1 }
);
// Drop the index
yield collection.dropAllIndexes();
// Verify that the index is gone
var indexInformation = yield collection.indexInformation();
test.deepEqual([['_id', 1]], indexInformation._id_);
test.equal(undefined, indexInformation.a_1_b_1);
test.equal(undefined, indexInformation.c_1);
client.close();
});
// END
}
});
/**************************************************************************
*
* DB TESTS
*
*************************************************************************/
/**
* An example that shows how to force close a db connection so it cannot be reused using a Generator and the co module..
*
* @example-class Db
* @example-method close
* @ignore
*/
it('shouldCorrectlyFailOnRetryDueToAppCloseOfDbWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Fetch a collection
var collection = db.collection(
'shouldCorrectlyFailOnRetryDueToAppCloseOfDb_with_generators'
);
// Insert a document
yield collection.insertOne({ a: 1 }, configuration.writeConcernMax());
// Force close the connection
yield client.close(true);
try {
// Attemp to insert should fail now with correct message 'db closed by application'
yield collection.insertOne({ a: 2 }, configuration.writeConcernMax());
} catch (err) {
client.close();
}
});
// END
}
});
/**
* A whole bunch of examples on how to use eval on the server with a Generator and the co module.
*
* @example-class Db
* @example-method eval
* @ignore
*/
it('shouldCorrectlyExecuteEvalFunctionsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
Code = configuration.require.Code,
ReadPreference = configuration.require.ReadPreference;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
var numberOfTests = 10;
var tests_done = function() {
numberOfTests = numberOfTests - 1;
if (numberOfTests === 0) {
client.close();
}
};
// Evaluate a function on the server with the parameter 3 passed in
var result = yield db.eval('function (x) {return x;}', [3]);
test.equal(3, result);
tests_done();
// Evaluate a function on the server with the parameter 3 passed in no lock aquired for eval
// on server
result = yield db.eval('function (x) {return x;}', [3], { nolock: true });
test.equal(3, result);
tests_done();
// Evaluate a function on the server that writes to a server collection
result = yield db.eval('function (x) {db.test_eval_with_generators.save({y:x});}', [5], {
readPreference: ReadPreference.PRIMARY
});
yield new Promise(resolve => setTimeout(resolve, 1000));
// Locate the entry
var collection = db.collection('test_eval_with_generators');
var item = yield collection.findOne();
test.equal(5, item.y);
tests_done();
// Evaluate a function with 2 parameters passed in
result = yield db.eval('function (x, y) {return x + y;}', [2, 3]);
test.equal(5, result);
tests_done();
// Evaluate a function with no parameters passed in
result = yield db.eval('function () {return 5;}');
test.equal(5, result);
tests_done();
// Evaluate a statement
result = yield db.eval('2 + 3;');
test.equal(5, result);
tests_done();
// Evaluate a statement using the code object
result = yield db.eval(new Code('2 + 3;'));
test.equal(5, result);
tests_done();
// Evaluate a statement using the code object including a scope
result = yield db.eval(new Code('return i;', { i: 2 }));
test.equal(2, result);
tests_done();
// Evaluate a statement using the code object including a scope
result = yield db.eval(new Code('i + 3;', { i: 2 }));
test.equal(5, result);
tests_done();
try {
// Evaluate an illegal statement
yield db.eval('5 ++ 5;');
} catch (err) {
test.ok(err instanceof Error);
test.ok(err.message != null);
tests_done();
}
});
// END
}
});
/**
* Defining and calling a system level javascript function (NOT recommended, http://www.mongodb.org/display/DOCS/Server-side+Code+Execution) using a Generator and the co module.
*
* @example-class Db
* @example-method eval
* @ignore
*/
it('shouldCorrectlyDefineSystemLevelFunctionAndExecuteFunctionWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
Code = configuration.require.Code;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Clean out the collection
yield db.collection('system.js').deleteMany({}, configuration.writeConcernMax());
// Define a system level function
yield db
.collection('system.js')
.insertOne(
{ _id: 'echo', value: new Code('function(x) { return x; }') },
configuration.writeConcernMax()
);
var result = yield db.eval('echo(5)');
test.equal(5, result);
client.close();
});
// END
}
});
/**
* An example of retrieving the collections list for a database using a Generator and the co module.
*
* @example-class Db
* @example-method listCollections
* @ignore
*/
it('shouldCorrectlyRetrievelistCollectionsWithGenerators', {
metadata: {
requires: { generators: true, topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap'] }
},
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get an empty db
var db1 = client.db('listCollectionTestDb2Generator');
// Create a collection
var collection = db1.collection('shouldCorrectlyRetrievelistCollections_with_generators');
// Ensure the collection was created
yield collection.insertOne({ a: 1 });
// Return the information of a single collection name
var items = yield db1
.listCollections({ name: 'shouldCorrectlyRetrievelistCollections_with_generators' })
.toArray();
test.equal(1, items.length);
// Return the information of a all collections, using the callback format
items = yield db1.listCollections().toArray();
test.ok(items.length >= 1);
client.close();
});
// END
}
});
/**
* An example of retrieving all collections for a db as Collection objects using a Generator and the co module.
*
* @example-class Db
* @example-method collections
* @ignore
*/
it('shouldCorrectlyRetrieveAllCollectionsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Retry to get the collection, should work as it's now created
var collections = yield db.collections();
test.ok(collections.length > 0);
client.close();
});
// END
}
});
/**
* An example of adding a user to the database using a Generator and the co module.
*
* @example-class Db
* @example-method addUser
* @ignore
*/
it('shouldCorrectlyAddUserToDbWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Add a user to the database
yield db.addUser('user', 'name');
// Remove the user from the db
yield db.removeUser('user');
client.close();
});
// END
}
});
/**
* An example of removing a user using a Generator and the co module.
*
* @example-class Db
* @example-method removeUser
* @ignore
*/
it('shouldCorrectlyAddAndRemoveUserWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
MongoClient = configuration.require.MongoClient;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Add a user to the database
yield db.addUser('user', 'name');
// Authenticate
var client2 = yield MongoClient.connect(
'mongodb://user:name@localhost:27017/' + configuration.db
);
client2.close();
// Remove the user from the db
yield db.removeUser('user');
try {
// Authenticate
yield MongoClient.connect('mongodb://user:name@localhost:27017/admin');
test.ok(false);
} catch (err) {} // eslint-disable-line
client.close();
});
// END
}
});
/**
* A simple example showing the creation of a collection using a Generator and the co module.
*
* @example-class Db
* @example-method createCollection
* @ignore
*/
it('shouldCorrectlyCreateACollectionWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a capped collection with a maximum of 1000 documents
var collection = yield db.createCollection('a_simple_collection_with_generators', {
capped: true,
size: 10000,
max: 1000,
w: 1
});
// Insert a document in the capped collection
yield collection.insertOne({ a: 1 }, configuration.writeConcernMax());
client.close();
});
// END
}
});
/**
* A simple example creating, dropping a collection and then verifying that the collection is gone using a Generator and the co module.
*
* @example-class Db
* @example-method dropCollection
* @ignore
*/
it('shouldCorrectlyExecuteACommandAgainstTheServerWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Execute ping against the server
yield db.command({ ping: 1 });
// Create a capped collection with a maximum of 1000 documents
var collection = yield db.createCollection(
'a_simple_create_drop_collection_with_generators',
{ capped: true, size: 10000, max: 1000, w: 1 }
);
// Insert a document in the capped collection
yield collection.insertOne({ a: 1 }, configuration.writeConcernMax());
// Drop the collection from this world
yield db.dropCollection('a_simple_create_drop_collection_with_generators');
// Verify that the collection is gone
var names = yield db
.listCollections({ name: 'a_simple_create_drop_collection_with_generators' })
.toArray();
test.equal(0, names.length);
client.close();
});
// END
}
});
/**
* A simple example executing a command against the server using a Generator and the co module.
*
* @example-class Db
* @example-method command
* @ignore
*/
it('shouldCorrectlyCreateDropAndVerifyThatCollectionIsGoneWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Execute ping against the server
yield db.command({ ping: 1 });
client.close();
});
// END
}
});
/**
* A simple example creating, dropping a collection and then verifying that the collection is gone.
*
* @example-class Db
* @example-method renameCollection
* @ignore
*/
it('shouldCorrectlyRenameACollectionWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection
var collection = yield db.createCollection(
'simple_rename_collection_with_generators',
configuration.writeConcernMax()
);
// Insert a document in the collection
yield collection.insertOne({ a: 1 }, configuration.writeConcernMax());
// Retrieve the number of documents from the collection
var count = yield collection.count();
test.equal(1, count);
// Rename the collection
var collection2 = yield db.renameCollection(
'simple_rename_collection_with_generators',
'simple_rename_collection_2_with_generators'
);
// Retrieve the number of documents from the collection
count = yield collection2.count();
test.equal(1, count);
// Verify that the collection is gone
var names = yield db
.listCollections({ name: 'simple_rename_collection_with_generators' })
.toArray();
test.equal(0, names.length);
// Verify that the new collection exists
names = yield db
.listCollections({ name: 'simple_rename_collection_2_with_generators' })
.toArray();
test.equal(1, names.length);
client.close();
});
// END
}
});
/**
* A more complex createIndex using a compound unique index in the background and dropping duplicated documents using a Generator and the co module.
*
* @example-class Db
* @example-method createIndex
* @ignore
*/
it('shouldCreateOnDbComplexIndexOnTwoFieldsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('more_complex_index_test_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
configuration.writeConcernMax()
);
// Create an index on the a field
yield db.createIndex(
'more_complex_index_test_with_generators',
{ a: 1, b: 1 },
{ unique: true, background: true, w: 1 }
);
// Show that duplicate records got dropped
var items = yield collection.find({}).toArray();
test.equal(4, items.length);
// Perform a query, with explain to show we hit the query
var explanation = yield collection.find({ a: 2 }).explain();
test.ok(explanation != null);
client.close();
});
// END
}
});
/**
* A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents using a Generator and the co module.
*
* @example-class Db
* @example-method ensureIndex
* @ignore
*/
it('shouldCreateComplexEnsureIndexDbWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection we want to drop later
var collection = db.collection('more_complex_ensure_index_db_test_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
configuration.writeConcernMax()
);
// Create an index on the a field
yield db.ensureIndex(
'more_complex_ensure_index_db_test_with_generators',
{ a: 1, b: 1 },
{ unique: true, background: true, w: 1 }
);
// Show that duplicate records got dropped
var items = yield collection.find({}).toArray();
test.equal(4, items.length);
// Perform a query, with explain to show we hit the query
var explanation = yield collection.find({ a: 2 }).explain();
test.ok(explanation != null);
client.close();
});
// END
}
});
/**
* An examples showing the dropping of a database using a Generator and the co module.
*
* @example-class Db
* @example-method dropDatabase
* @ignore
*/
it('shouldCorrectlyDropTheDatabaseWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection
var collection = db.collection('more_index_information_test_1_with_generators');
// Insert a bunch of documents for the index
yield collection.insertMany(
[{ a: 1, b: 1 }, { a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }],
configuration.writeConcernMax()
);
// Let's drop the database
yield db.dropDatabase();
// Wait two seconds to let it replicate across
yield new Promise(resolve => setTimeout(resolve, 2000));
// Get the admin database
var dbs = yield db.admin().listDatabases();
// Grab the databases
dbs = dbs.databases;
// Did we find the db
var found = false;
// Check if we have the db in the list
for (var i = 0; i < dbs.length; i++) {
if (dbs[i].name === 'integration_tests_to_drop') found = true;
}
// We should not find the databases
if (process.env['JENKINS'] == null) test.equal(false, found);
client.close();
});
// END
}
});
/**
* An example showing how to retrieve the db statistics using a Generator and the co module.
*
* @example-class Db
* @example-method stats
* @ignore
*/
it('shouldCorrectlyRetrieveDbStatsWithGeneratorsWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
var stats = yield db.stats();
test.ok(stats != null);
client.close();
});
// END
}
});
/**
* Simple example connecting to two different databases sharing the socket connections below using a Generator and the co module.
*
* @example-class Db
* @example-method db
* @ignore
*/
it('shouldCorrectlyShareConnectionPoolsAcrossMultipleDbInstancesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Reference a different database sharing the same connections
// for the data transfer
var secondDb = client.db('integration_tests_2');
// Fetch the collections
var multipleColl1 = db.collection('multiple_db_instances_with_generators');
var multipleColl2 = secondDb.collection('multiple_db_instances_with_generators');
// Write a record into each and then count the records stored
yield multipleColl1.insertOne({ a: 1 }, { w: 1 });
yield multipleColl2.insertOne({ a: 1 }, { w: 1 });
// Count over the results ensuring only on record in each collection
var count = yield multipleColl1.count();
test.equal(1, count);
count = yield multipleColl2.count();
test.equal(1, count);
client.close();
});
// END
}
});
/**************************************************************************
*
* ADMIN TESTS
*
*************************************************************************/
/**
* Retrieve the buildInfo for the current MongoDB instance using a Generator and the co module.
*
* @example-class Admin
* @example-method buildInfo
* @ignore
*/
it('shouldCorrectlyRetrieveBuildInfoWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Use the admin database for the operation
var adminDb = db.admin();
// Retrive the build information for the MongoDB instance
yield adminDb.buildInfo();
client.close();
});
// END
}
});
/**
* Retrieve the buildInfo using the command function using a Generator and the co module.
*
* @example-class Admin
* @example-method command
* @ignore
*/
it('shouldCorrectlyRetrieveBuildInfoUsingCommandWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Use the admin database for the operation
var adminDb = db.admin();
// Retrive the build information using the admin command
yield adminDb.command({ buildInfo: 1 });
client.close();
});
// END
}
});
/**
* An example of how to use the setProfilingInfo using a Generator and the co module.
* Use this command to set the Profiling level on the MongoDB server
*
* @example-class Db
* @example-method setProfilingLevel
* @ignore
*/
it('shouldCorrectlyChangeProfilingLevelWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Grab a collection object
var collection = db.collection('test_with_generators');
// Force the creation of the collection by inserting a document
// Collections are not created until the first document is inserted
yield collection.insertOne({ a: 1 }, { w: 1 });
// Set the profiling level to only profile slow queries
yield db.setProfilingLevel('slow_only');
// Retrive the profiling level and verify that it's set to slow_only
var level = yield db.profilingLevel();
test.equal('slow_only', level);
// Turn profiling off
yield db.setProfilingLevel('off');
// Retrive the profiling level and verify that it's set to off
level = yield db.profilingLevel();
test.equal('off', level);
// Set the profiling level to log all queries
yield db.setProfilingLevel('all');
// Retrive the profiling level and verify that it's set to all
level = yield db.profilingLevel();
test.equal('all', level);
try {
// Attempt to set an illegal profiling level
yield db.setProfilingLevel('medium');
} catch (err) {
test.ok(err instanceof Error);
test.equal('Error: illegal profiling level value medium', err.message);
client.close();
}
});
// END
}
});
/**
* An example of how to use the profilingInfo using a Generator and the co module.
* Use this command to pull back the profiling information currently set for Mongodb
*
* @example-class Db
* @example-method profilingInfo
* @ignore
*/
it('shouldCorrectlySetAndExtractProfilingInfoWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Grab a collection object
var collection = db.collection('test_with_generators');
// Force the creation of the collection by inserting a document
// Collections are not created until the first document is inserted
yield collection.insertOne({ a: 1 }, { w: 1 });
// Set the profiling level to all
yield db.setProfilingLevel('all');
// Execute a query command
yield collection.find().toArray();
// Turn off profiling
yield db.setProfilingLevel('off');
// Retrive the profiling information
var infos = yield db.profilingInfo();
test.ok(infos.constructor === Array);
test.ok(infos.length >= 1);
test.ok(infos[0].ts.constructor === Date);
test.ok(infos[0].millis.constructor === Number);
client.close();
});
// END
}
});
/**
* An example of how to use the validateCollection command using a Generator and the co module.
* Use this command to check that a collection is valid (not corrupt) and to get various statistics.
*
* @example-class Admin
* @example-method validateCollection
* @ignore
*/
it('shouldCorrectlyCallValidateCollectionWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Grab a collection object
var collection = db.collection('test_with_generators');
// Force the creation of the collection by inserting a document
// Collections are not created until the first document is inserted
yield collection.insertOne({ a: 1 }, { w: 1 });
// Use the admin database for the operation
var adminDb = db.admin();
// Validate the 'test' collection
var doc = yield adminDb.validateCollection('test_with_generators');
test.ok(doc != null);
client.close();
});
}
});
/**
* An example of how to add a user to the admin database using a Generator and the co module.
*
* @example-class Admin
* @example-method ping
* @ignore
*/
it('shouldCorrectlyPingTheMongoDbInstanceWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Use the admin database for the operation
var adminDb = db.admin();
// Ping the server
yield adminDb.ping();
client.close();
});
// END
}
});
/**
* An example of how to add a user to the admin database using a Generator and the co module.
*
* @example-class Admin
* @example-method addUser
* @ignore
*/
it('shouldCorrectlyAddAUserToAdminDbWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Use the admin database for the operation
var adminDb = db.admin();
// Add the new user to the admin database
yield adminDb.addUser('admin11', 'admin11');
var result = yield adminDb.removeUser('admin11');
test.ok(result);
client.close();
});
}
});
/**
* An example of how to remove a user from the admin database using a Generator and the co module.
*
* @example-class Admin
* @example-method removeUser
* @ignore
*/
it('shouldCorrectlyAddAUserAndRemoveItFromAdminDbWithGenerators', {
metadata: { requires: { generators: true, topology: 'single' } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Use the admin database for the operation
var adminDb = db.admin();
// Add the new user to the admin database
yield adminDb.addUser('admin12', 'admin12');
// Remove the user
var result = yield adminDb.removeUser('admin12');
test.equal(true, result);
client.close();
});
// END
}
});
/**
* An example of listing all available databases. using a Generator and the co module.
*
* @example-class Admin
* @example-method listDatabases
* @ignore
*/
it('shouldCorrectlyListAllAvailableDatabasesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Use the admin database for the operation
var adminDb = db.admin();
// List all the available databases
var dbs = yield adminDb.listDatabases();
test.ok(dbs.databases.length > 0);
client.close();
});
// END
}
});
/**
* Retrieve the current server Info using a Generator and the co module.
*
* @example-class Admin
* @example-method serverStatus
* @ignore
*/
it('shouldCorrectlyRetrieveServerInfoWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Grab a collection object
var collection = db.collection('test_with_generators');
// Force the creation of the collection by inserting a document
// Collections are not created until the first document is inserted
yield collection.insertOne({ a: 1 }, { w: 1 });
// Use the admin database for the operation
var adminDb = db.admin();
// Retrive the server Info
var info = yield adminDb.serverStatus();
test.ok(info != null);
client.close();
});
// END
}
});
/**
* Retrieve the current replicaset status if the server is running as part of a replicaset using a Generator and the co module.
*
* @example-class Admin
* @example-method replSetGetStatus
* @ignore
*/
it('shouldCorrectlyRetrieveReplSetGetStatusWithGenerators', {
metadata: { requires: { generators: true, topology: ['replicaset'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Grab a collection object
var collection = db.collection('test_with_generators');
// Force the creation of the collection by inserting a document
// Collections are not created until the first document is inserted
yield collection.insertOne({ a: 1 }, { w: 1 });
// Use the admin database for the operation
var adminDb = db.admin();
// Retrive the server Info, returns error if we are not
// running a replicaset
yield adminDb.replSetGetStatus();
client.close();
});
// END
}
});
/**************************************************************************
*
* CURSOR TESTS
*
*************************************************************************/
var fs = require('fs');
/**
* An example showing the information returned by indexInformation using a Generator and the co module.
*
* @example-class Cursor
* @example-method toArray
* @ignore
*/
it('shouldCorrectlyExecuteToArrayWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection to hold our documents
var collection = db.collection('test_array_with_generators');
// Insert a test document
yield collection.insertOne({ b: [1, 2, 3] }, configuration.writeConcernMax());
// Retrieve all the documents in the collection
var documents = yield collection.find().toArray();
test.equal(1, documents.length);
test.deepEqual([1, 2, 3], documents[0].b);
client.close();
});
// END
}
});
/**
* A simple example showing the count function of the cursor using a Generator and the co module.
*
* @example-class Cursor
* @example-method count
* @ignore
*/
it('shouldCorrectlyUseCursorCountFunctionWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Creat collection
var collection = db.collection('cursor_count_collection_with_generators');
// Insert some docs
yield collection.insertMany([{ a: 1 }, { a: 2 }], configuration.writeConcernMax());
// Do a find and get the cursor count
var count = yield collection.find().count();
test.equal(2, count);
client.close();
});
// END
}
});
/**
* A simple example showing the use of next and co module to iterate over cursor
*
* @example-class Cursor
* @example-method next
* @ignore
*/
it('shouldCorrectlyPerformNextOnCursorWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection
var collection = db.collection('simple_next_object_collection_next_with_generators');
// Insert some documents we can sort on
yield collection.insertMany(
[{ a: 1 }, { a: 2 }, { a: 3 }],
configuration.writeConcernMax()
);
// Get a cursor
var cursor = collection.find({});
// Get the document
var docs = [];
// Iterate over the cursor
while (yield cursor.hasNext()) {
docs.push(yield cursor.next());
}
// Validate the correct number of elements
test.equal(3, docs.length);
client.close();
});
// END
}
});
/**
* A simple example showing the use of the cursor explain function using a Generator and the co module.
*
* @example-class Cursor
* @example-method explain
* @ignore
*/
it('shouldCorrectlyPerformSimpleExplainCursorWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a collection
var collection = db.collection('simple_explain_collection_with_generators');
// Insert some documents we can sort on
yield collection.insertMany(
[{ a: 1 }, { a: 2 }, { a: 3 }],
configuration.writeConcernMax()
);
// Do normal ascending sort
yield collection.find().explain();
client.close();
});
// END
}
});
/**
* A simple example showing the use of the cursor close function using a Generator and the co module.
*
* @example-class Cursor
* @example-method close
* @ignore
*/
it('shouldStreamDocumentsUsingTheCloseFunctionWithGenerators', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a lot of documents to insert
var docs = [];
for (var i = 0; i < 100; i++) {
docs.push({ a: i });
}
// Create a collection
var collection = db.collection('test_close_function_on_cursor_with_generators');
// Insert documents into collection
yield collection.insertMany(docs, configuration.writeConcernMax());
// Perform a find to get a cursor
var cursor = collection.find();
// Fetch the first object
yield cursor.next();
// Close the cursor, this is the same as reseting the query
yield cursor.close();
client.close();
});
// END
}
});
/**************************************************************************
*
* GRIDSTORE TESTS
*
*************************************************************************/
/**
* A simple example showing the usage of the Gridstore.exist method using a Generator and the co module.
*
* @example-class GridStore
* @example-method GridStore.exist
* @ignore
*/
it('shouldCorrectlyExecuteGridStoreExistsByObjectIdWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Open a file for writing
var gridStore = new GridStore(db, null, 'w');
yield gridStore.open();
// Writing some content to the file
yield gridStore.write('hello world!');
// Flush the file to GridFS
var file = yield gridStore.close();
// Check if the file exists using the id returned from the close function
var result = yield GridStore.exist(db, file._id);
test.equal(true, result);
// Show that the file does not exist for a random ObjectID
result = yield GridStore.exist(db, new ObjectID());
test.equal(false, result);
// Show that the file does not exist for a different file root
result = yield GridStore.exist(db, file._id, 'another_root');
test.equal(false, result);
client.close();
});
// END
}
});
/**
* A simple example showing the usage of the eof method using a Generator and the co module.
*
* @example-class GridStore
* @example-method GridStore.list
* @ignore
*/
it('shouldCorrectlyExecuteGridStoreListWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file id
var fileId = new ObjectID();
// Open a file for writing
var gridStore = new GridStore(db, fileId, 'foobar2', 'w');
yield gridStore.open();
// Write some content to the file
yield gridStore.write('hello world!');
// Flush to GridFS
yield gridStore.close();
// List the existing files
var items = yield GridStore.list(db);
var found = false;
items.forEach(function(filename) {
if (filename === 'foobar2') found = true;
});
test.ok(items.length >= 1);
test.ok(found);
// List the existing files but return only the file ids
items = yield GridStore.list(db, { id: true });
found = false;
items.forEach(function(id) {
test.ok(typeof id === 'object');
});
test.ok(items.length >= 1);
// List the existing files in a specific root collection
items = yield GridStore.list(db, 'fs');
found = false;
items.forEach(function(filename) {
if (filename === 'foobar2') found = true;
});
test.ok(items.length >= 1);
test.ok(found);
// List the existing files in a different root collection where the file is not located
items = yield GridStore.list(db, 'my_fs');
found = false;
items.forEach(function(filename) {
if (filename === 'foobar2') found = true;
});
test.ok(items.length >= 0);
test.ok(!found);
// Specify seperate id
var fileId2 = new ObjectID();
// Write another file to GridFS
var gridStore2 = new GridStore(db, fileId2, 'foobar3', 'w');
yield gridStore2.open();
// Write the content
yield gridStore2.write('my file');
// Flush to GridFS
yield gridStore2.close();
// List all the available files and verify that our files are there
items = yield GridStore.list(db);
found = false;
var found2 = false;
items.forEach(function(filename) {
if (filename === 'foobar2') found = true;
if (filename === 'foobar3') found2 = true;
});
test.ok(items.length >= 2);
test.ok(found);
test.ok(found2);
client.close();
});
// END
}
});
/**
* A simple example showing the usage of the puts method using a Generator and the co module.
*
* @example-class GridStore
* @example-method puts
* @ignore
*/
it('shouldCorrectlyReadlinesAndPutLinesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Open a file for writing
var gridStore = new GridStore(db, 'test_gs_puts_and_readlines', 'w');
yield gridStore.open();
// Write a line to the file using the puts method
yield gridStore.puts('line one');
// Flush the file to GridFS
yield gridStore.close();
// Read in the entire contents
var data = yield GridStore.read(db, 'test_gs_puts_and_readlines');
test.equal('line one\n', data.toString());
client.close();
});
// END
}
});
/**
* A simple example showing the usage of the GridStore.unlink method using a Generator and the co module.
*
* @example-class GridStore
* @example-method GridStore.unlink
* @ignore
*/
it('shouldCorrectlyUnlinkWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Open a new file for writing
var gridStore = new GridStore(db, 'test_gs_unlink', 'w');
yield db.dropDatabase();
yield gridStore.open();
// Write some content
yield gridStore.write('hello, world!');
// Flush file to GridFS
yield gridStore.close();
// Verify the existance of the fs.files document
var collection = db.collection('fs.files');
var count = yield collection.count();
test.equal(1, count);
// Verify the existance of the fs.chunks chunk document
collection = db.collection('fs.chunks');
count = yield collection.count();
test.equal(1, count);
// Unlink the file (removing it)
yield GridStore.unlink(db, 'test_gs_unlink');
// Verify that fs.files document is gone
collection = db.collection('fs.files');
count = yield collection.count();
test.equal(0, count);
// Verify that fs.chunks chunk documents are gone
collection = db.collection('fs.chunks');
count = yield collection.count();
test.equal(0, count);
client.close();
});
// END
}
});
/**
* A simple example showing the usage of the read method using a Generator and the co module.
*
* @example-class GridStore
* @example-method read
* @ignore
*/
it('shouldCorrectlyWriteAndReadJpgImageWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Read in the content of a file
var data = fs.readFileSync('./test/functional/data/iya_logo_final_bw.jpg');
// Create a new file
var gs = new GridStore(db, 'test', 'w');
// Open the file
yield gs.open();
// Write the file to GridFS
yield gs.write(data);
// Flush to the GridFS
yield gs.close();
// Define the file we wish to read
var gs2 = new GridStore(db, 'test', 'r');
// Open the file
yield gs2.open();
// Set the pointer of the read head to the start of the gridstored file
yield gs2.seek(0);
// Read the entire file
var data2 = yield gs2.read();
// Compare the file content against the orgiinal
test.equal(data.toString('base64'), data2.toString('base64'));
client.close();
});
// END
}
});
/**
* A simple example showing opening a file using a filename, writing to it and saving it using a Generator and the co module.
*
* @example-class GridStore
* @example-method open
* @ignore
*/
it('shouldCorrectlySaveSimpleFileToGridStoreUsingFilenameWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a new instance of the gridstore
var gridStore = new GridStore(db, 'ourexamplefiletowrite.txt', 'w');
// Open the file
yield gridStore.open();
// Write some data to the file
yield gridStore.write('bar');
// Close (Flushes the data to MongoDB)
yield gridStore.close();
// Verify that the file exists
var result = yield GridStore.exist(db, 'ourexamplefiletowrite.txt');
test.equal(true, result);
client.close();
});
// END
}
});
/**
* A simple example showing opening a file using an ObjectID, writing to it and saving it using a Generator and the co module.
*
* @example-class GridStore
* @example-method open
* @ignore
*/
it('shouldCorrectlySaveSimpleFileToGridStoreUsingObjectIDWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Create a new instance of the gridstore
var gridStore = new GridStore(db, fileId, 'w');
// Open the file
yield gridStore.open();
// Write some data to the file
yield gridStore.write('bar');
// Close (Flushes the data to MongoDB)
yield gridStore.close();
// Verify that the file exists
var result = yield GridStore.exist(db, fileId);
test.equal(true, result);
client.close();
});
// END
}
});
/**
* A simple example showing how to write a file to Gridstore using file location path using a Generator and the co module.
*
* @example-class GridStore
* @example-method writeFile
* @ignore
*/
it('shouldCorrectlySaveSimpleFileToGridStoreUsingWriteFileWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore = new GridStore(db, fileId, 'w');
// Read the filesize of file on disk (provide your own)
var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
// Read the buffered data for comparision reasons
var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');
// Open the new file
yield gridStore.open();
// Write the file to gridFS
yield gridStore.writeFile('./test/functional/data/test_gs_weird_bug.png');
// Read back all the written content and verify the correctness
var fileData = yield GridStore.read(db, fileId);
test.equal(data.toString('base64'), fileData.toString('base64'));
test.equal(fileSize, fileData.length);
client.close();
});
// END
}
});
/**
* A simple example showing how to write a file to Gridstore using a file handle using a Generator and the co module.
*
* @example-class GridStore
* @example-method writeFile
* @ignore
*/
it('shouldCorrectlySaveSimpleFileToGridStoreUsingWriteFileWithHandleWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore = new GridStore(db, fileId, 'w');
// Read the filesize of file on disk (provide your own)
var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
// Read the buffered data for comparision reasons
var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');
// Open a file handle for reading the file
var fd = fs.openSync(
'./test/functional/data/test_gs_weird_bug.png',
'r',
parseInt('0666', 8)
);
// Open the new file
yield gridStore.open();
// Write the file to gridFS using the file handle
yield gridStore.writeFile(fd);
// Read back all the written content and verify the correctness
var fileData = yield GridStore.read(db, fileId);
test.equal(data.toString('base64'), fileData.toString('base64'));
test.equal(fileSize, fileData.length);
client.close();
});
// END
}
});
/**
* A simple example showing how to use the write command with strings and Buffers using a Generator and the co module.
*
* @example-class GridStore
* @example-method write
* @ignore
*/
it('shouldCorrectlySaveSimpleFileToGridStoreUsingWriteWithStringsAndBuffersWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore = new GridStore(db, fileId, 'w');
// Open the new file
yield gridStore.open();
// Write a text string
yield gridStore.write('Hello world');
// Write a buffer
yield gridStore.write(Buffer.from('Buffer Hello world'));
// Close the
yield gridStore.close();
// Read back all the written content and verify the correctness
var fileData = yield GridStore.read(db, fileId);
test.equal('Hello worldBuffer Hello world', fileData.toString());
client.close();
});
// END
}
});
/**
* A simple example showing how to use the write command with strings and Buffers using a Generator and the co module.
*
* @example-class GridStore
* @example-method close
* @ignore
*/
it('shouldCorrectlySaveSimpleFileToGridStoreUsingCloseWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore = new GridStore(db, fileId, 'w');
// Open the new file
yield gridStore.open();
// Write a text string
yield gridStore.write('Hello world');
// Close the
yield gridStore.close();
client.close();
});
// END
}
});
/**
* A simple example showing how to use the instance level unlink command to delete a gridstore item using a Generator and the co module.
*
* @example-class GridStore
* @example-method unlink
* @ignore
*/
it('shouldCorrectlySaveSimpleFileToGridStoreUsingCloseAndThenUnlinkItWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore = new GridStore(db, fileId, 'w');
// Open the new file
yield gridStore.open();
// Write a text string
yield gridStore.write('Hello world');
// Close the
yield gridStore.close();
// Open the file again and unlin it
gridStore = yield new GridStore(db, fileId, 'r').open();
// Unlink the file
yield gridStore.unlink();
// Verify that the file no longer exists
var result = yield GridStore.exist(db, fileId);
test.equal(false, result);
client.close();
});
// END
}
});
/**
* A simple example showing reading back using readlines to split the text into lines by the separator provided using a Generator and the co module.
*
* @example-class GridStore
* @example-method GridStore.readlines
* @ignore
*/
it('shouldCorrectlyPutACoupleOfLinesInGridStoreAndUseReadlinesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore = new GridStore(db, fileId, 'w');
// Open the new file
yield gridStore.open();
// Write one line to gridStore
yield gridStore.puts('line one');
// Write second line to gridStore
yield gridStore.puts('line two');
// Write third line to gridStore
yield gridStore.puts('line three');
// Flush file to disk
yield gridStore.close();
// Read back all the lines
var lines = yield GridStore.readlines(db, fileId);
test.deepEqual(['line one\n', 'line two\n', 'line three\n'], lines);
client.close();
});
// END
}
});
/**
* A simple example showing reading back using readlines to split the text into lines by the separator provided using a Generator and the co module.
*
* @example-class GridStore
* @example-method readlines
* @ignore
*/
it('shouldCorrectlyPutACoupleOfLinesInGridStoreAndUseInstanceReadlinesWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore = new GridStore(db, fileId, 'w');
// Open the new file
yield gridStore.open();
// Write one line to gridStore
yield gridStore.puts('line one');
// Write second line to gridStore
yield gridStore.puts('line two');
// Write third line to gridStore
yield gridStore.puts('line three');
// Flush file to disk
yield gridStore.close();
// Open file for reading
gridStore = new GridStore(db, fileId, 'r');
yield gridStore.open();
// Read all the lines and verify correctness
var lines = yield gridStore.readlines();
test.deepEqual(['line one\n', 'line two\n', 'line three\n'], lines);
client.close();
});
// END
}
});
/**
* A simple example showing the usage of the read method using a Generator and the co module.
*
* @example-class GridStore
* @example-method GridStore.read
* @ignore
*/
it('shouldCorrectlyPutACoupleOfLinesInGridStoreReadWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a new file
var gridStore = new GridStore(db, null, 'w');
// Read in the content from a file, replace with your own
var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');
// Open the file
yield gridStore.open();
// Write the binary file data to GridFS
yield gridStore.write(data);
// Flush the remaining data to GridFS
var result = yield gridStore.close();
// Read in the whole file and check that it's the same content
var fileData = yield GridStore.read(db, result._id);
test.equal(data.length, fileData.length);
client.close();
});
// END
}
});
/*
* A simple example showing the usage of the seek method using a Generator and the co module.
*
* @example-class GridStore
* @example-method seek
* @ignore
*/
it('shouldCorrectlySeekWithBufferWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a file and open it
var gridStore = new GridStore(db, 'test_gs_seek_with_buffer', 'w');
yield gridStore.open();
// Write some content to the file
yield gridStore.write(Buffer.from('hello, world!', 'utf8'));
// Flush the file to GridFS
yield gridStore.close();
// Open the file in read mode
gridStore = new GridStore(db, 'test_gs_seek_with_buffer', 'r');
yield gridStore.open();
// Seek to start
yield gridStore.seek(0);
// Read first character and verify
var chr = yield gridStore.getc();
test.equal('h', chr.toString());
// Open the file in read mode
gridStore = new GridStore(db, 'test_gs_seek_with_buffer', 'r');
yield gridStore.open();
// Seek to 7 characters from the beginning off the file and verify
yield gridStore.seek(7);
chr = yield gridStore.getc();
test.equal('w', chr.toString());
// Open the file in read mode
gridStore = new GridStore(db, 'test_gs_seek_with_buffer', 'r');
yield gridStore.open();
// Seek to -1 characters from the end off the file and verify
yield gridStore.seek(-1, GridStore.IO_SEEK_END);
chr = yield gridStore.getc();
test.equal('!', chr.toString());
// Open the file in read mode
gridStore = new GridStore(db, 'test_gs_seek_with_buffer', 'r');
yield gridStore.open();
// Seek to -6 characters from the end off the file and verify
yield gridStore.seek(-6, GridStore.IO_SEEK_END);
chr = yield gridStore.getc();
test.equal('w', chr.toString());
// Open the file in read mode
gridStore = new GridStore(db, 'test_gs_seek_with_buffer', 'r');
yield gridStore.open();
// Seek forward 7 characters from the current read position and verify
yield gridStore.seek(7, GridStore.IO_SEEK_CUR);
chr = yield gridStore.getc();
test.equal('w', chr.toString());
// Seek forward -1 characters from the current read position and verify
yield gridStore.seek(-1, GridStore.IO_SEEK_CUR);
chr = yield gridStore.getc();
test.equal('w', chr.toString());
// Seek forward -4 characters from the current read position and verify
yield gridStore.seek(-4, GridStore.IO_SEEK_CUR);
chr = yield gridStore.getc();
test.equal('o', chr.toString());
// Seek forward 3 characters from the current read position and verify
yield gridStore.seek(3, GridStore.IO_SEEK_CUR);
chr = yield gridStore.getc();
test.equal('o', chr.toString());
client.close();
});
// END
}
});
/**
* A simple example showing how to rewind and overwrite the file using a Generator and the co module.
*
* @example-class GridStore
* @example-method rewind
* @ignore
*/
it('shouldCorrectlyRewingAndTruncateOnWriteWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Our file ID
var fileId = new ObjectID();
// Create a new file
var gridStore = new GridStore(db, fileId, 'w');
// Open the file
yield gridStore.open();
// Write to the file
yield gridStore.write('hello, world!');
// Flush the file to disk
yield gridStore.close();
// Reopen the file
gridStore = new GridStore(db, fileId, 'w');
yield gridStore.open();
// Write some more text to the file
yield gridStore.write('some text is inserted here');
// Let's rewind to truncate the file
yield gridStore.rewind();
// Write something from the start
yield gridStore.write('abc');
// Flush the data to mongodb
yield gridStore.close();
// Verify that the new data was written
var data = yield GridStore.read(db, fileId);
test.equal('abc', data.toString());
client.close();
});
// END
}
});
/**
* A simple example showing the usage of the tell method using a Generator and the co module.
*
* @example-class GridStore
* @example-method tell
* @ignore
*/
it('shouldCorrectlyExecuteGridstoreTellWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a new file
var gridStore = new GridStore(db, 'test_gs_tell', 'w');
// Open the file
yield gridStore.open();
// Write a string to the file
yield gridStore.write('hello, world!');
// Flush the file to GridFS
yield gridStore.close();
// Open the file in read only mode
gridStore = new GridStore(db, 'test_gs_tell', 'r');
yield gridStore.open();
// Read the first 5 characters
var data = yield gridStore.read(5);
test.equal('hello', data.toString());
// Get the current position of the read head
var position = yield gridStore.tell();
test.equal(5, position);
client.close();
});
// END
}
});
/**
* A simple example showing the usage of the seek method using a Generator and the co module.
*
* @example-class GridStore
* @example-method getc
* @ignore
*/
it('shouldCorrectlyRetrieveSingleCharacterUsingGetCWithGenerators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a file and open it
var gridStore = new GridStore(db, 'test_gs_getc_file', 'w');
yield gridStore.open();
// Write some content to the file
yield gridStore.write(Buffer.from('hello, world!', 'utf8'));
// Flush the file to GridFS
yield gridStore.close();
// Open the file in read mode
gridStore = new GridStore(db, 'test_gs_getc_file', 'r');
yield gridStore.open();
// Read first character and verify
var chr = yield gridStore.getc();
test.equal('h', chr.toString());
client.close();
});
// END
}
});
/**
* A simple example showing how to save a file with a filename allowing for multiple files with the same name using a Generator and the co module.
*
* @example-class GridStore
* @example-method open
* @ignore
*/
it('shouldCorrectlyRetrieveSingleCharacterUsingGetCWithGenerators2', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co'),
GridStore = configuration.require.GridStore,
ObjectID = configuration.require.ObjectID;
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a file and open it
var gridStore = new GridStore(db, new ObjectID(), 'test_gs_getc_file', 'w');
yield gridStore.open();
// Write some content to the file
yield gridStore.write(Buffer.from('hello, world!', 'utf8'));
// Flush the file to GridFS
yield gridStore.close();
// Create another file with same name and and save content to it
gridStore = new GridStore(db, new ObjectID(), 'test_gs_getc_file', 'w');
yield gridStore.open();
// Write some content to the file
yield gridStore.write(Buffer.from('hello, world!', 'utf8'));
// Flush the file to GridFS
var fileData = yield gridStore.close();
// Open the file in read mode using the filename
gridStore = new GridStore(db, 'test_gs_getc_file', 'r');
yield gridStore.open();
// Read first character and verify
var chr = yield gridStore.getc();
test.equal('h', chr.toString());
// Open the file using an object id
gridStore = new GridStore(db, fileData._id, 'r');
yield gridStore.open();
// Read first character and verify
chr = yield gridStore.getc();
test.equal('h', chr.toString());
client.close();
});
// END
}
});
/**************************************************************************
*
* BULK TESTS
*
*************************************************************************/
/**
* Example of a simple ordered insert/update/upsert/remove ordered collection using a Generator and the co module.
*
* @example-class Collection
* @example-method initializeOrderedBulkOp
* @ignore
*/
it('Should correctly execute ordered batch with no errors using write commands with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('batch_write_ordered_ops_0_with_generators');
// Initialize the Ordered Batch
var batch = col.initializeOrderedBulkOp();
// Add some operations to be executed in order
batch.insert({ a: 1 });
batch.find({ a: 1 }).updateOne({ $set: { b: 1 } });
batch
.find({ a: 2 })
.upsert()
.updateOne({ $set: { b: 2 } });
batch.insert({ a: 3 });
batch.find({ a: 3 }).remove({ a: 3 });
// Execute the operations
var result = yield batch.execute();
// Check state of result
test.equal(2, result.nInserted);
test.equal(1, result.nUpserted);
test.equal(1, result.nMatched);
test.ok(1 === result.nModified || result.nModified == null);
test.equal(1, result.nRemoved);
var upserts = result.getUpsertedIds();
test.equal(1, upserts.length);
test.equal(2, upserts[0].index);
test.ok(upserts[0]._id != null);
var upsert = result.getUpsertedIdAt(0);
test.equal(2, upsert.index);
test.ok(upsert._id != null);
// Finish up test
client.close();
});
// END
}
});
/**
* Example of a simple ordered insert/update/upsert/remove ordered collection using a Generator and the co module.
*
*
* @example-class Collection
* @example-method initializeUnorderedBulkOp
* @ignore
*/
it('Should correctly execute unordered batch with no errors with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('batch_write_unordered_ops_legacy_0_with_generators');
// Initialize the unordered Batch
var batch = col.initializeUnorderedBulkOp({ useLegacyOps: true });
// Add some operations to be executed in order
batch.insert({ a: 1 });
batch.find({ a: 1 }).updateOne({ $set: { b: 1 } });
batch
.find({ a: 2 })
.upsert()
.updateOne({ $set: { b: 2 } });
batch.insert({ a: 3 });
batch.find({ a: 3 }).remove({ a: 3 });
// Execute the operations
var result = yield batch.execute();
// Check state of result
test.equal(2, result.nInserted);
test.equal(1, result.nUpserted);
test.equal(1, result.nMatched);
test.ok(1 === result.nModified || result.nModified == null);
test.equal(1, result.nRemoved);
var upserts = result.getUpsertedIds();
test.equal(1, upserts.length);
test.equal(2, upserts[0].index);
test.ok(upserts[0]._id != null);
var upsert = result.getUpsertedIdAt(0);
test.equal(2, upsert.index);
test.ok(upsert._id != null);
// Finish up test
client.close();
});
// END
}
});
/**************************************************************************
*
* CRUD TESTS
*
*************************************************************************/
/**
* Example of a simple insertOne operation using a Generator and the co module.
*
* @example-class Collection
* @example-method insertOne
* @ignore
*/
it('Should correctly execute insertOne operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('insert_one_with_generators');
var r = yield col.insertOne({ a: 1 });
test.equal(1, r.insertedCount);
// Finish up test
client.close();
});
// END
}
});
/**
* Example of a simple insertMany operation using a Generator and the co module.
*
* @example-class Collection
* @example-method insertMany
* @ignore
*/
it('Should correctly execute insertMany operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('insert_many_with_generators');
var r = yield col.insertMany([{ a: 1 }, { a: 2 }]);
test.equal(2, r.insertedCount);
// Finish up test
client.close();
});
// END
}
});
/**
* Example of a simple updateOne operation using a Generator and the co module.
*
* @example-class Collection
* @example-method updateOne
* @ignore
*/
it('Should correctly execute updateOne operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('update_one_with_generators');
var r = yield col.updateOne({ a: 1 }, { $set: { a: 2 } }, { upsert: true });
test.equal(0, r.matchedCount);
test.equal(1, r.upsertedCount);
// Finish up test
client.close();
});
// END
}
});
/**
* Example of a simple updateMany operation using a Generator and the co module.
*
* @example-class Collection
* @example-method updateMany
* @ignore
*/
it('Should correctly execute updateMany operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('update_many_with_generators');
var r = yield col.insertMany([{ a: 1 }, { a: 1 }]);
test.equal(2, r.insertedCount);
// Update all documents
r = yield col.updateMany({ a: 1 }, { $set: { b: 1 } });
test.equal(2, r.matchedCount);
test.equal(2, r.modifiedCount);
// Finish up test
client.close();
});
// END
}
});
/**
* Example of a simple removeOne operation using a Generator and the co module.
*
* @example-class Collection
* @example-method removeOne
* @ignore
*/
it('Should correctly execute removeOne operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('remove_one_with_generators');
var r = yield col.insertMany([{ a: 1 }, { a: 1 }]);
test.equal(2, r.insertedCount);
r = yield col.removeOne({ a: 1 });
test.equal(1, r.deletedCount);
// Finish up test
client.close();
});
// END
}
});
/**
* Example of a simple removeMany operation using a Generator and the co module.
*
* @example-class Collection
* @example-method removeMany
* @ignore
*/
it('Should correctly execute removeMany operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('remove_many_with_generators');
var r = yield col.insertMany([{ a: 1 }, { a: 1 }]);
test.equal(2, r.insertedCount);
// Update all documents
r = yield col.removeMany({ a: 1 });
test.equal(2, r.deletedCount);
// Finish up test
client.close();
});
// END
}
});
/**
* Example of a simple bulkWrite operation using a Generator and the co module.
*
* @example-class Collection
* @example-method bulkWrite
* @ignore
*/
it('Should correctly execute bulkWrite operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('bulk_write_with_generators');
var r = yield col.bulkWrite(
[
{ insertOne: { document: { a: 1 } } },
{ updateOne: { filter: { a: 2 }, update: { $set: { a: 2 } }, upsert: true } },
{ updateMany: { filter: { a: 2 }, update: { $set: { a: 2 } }, upsert: true } },
{ deleteOne: { filter: { c: 1 } } },
{ deleteMany: { filter: { c: 1 } } },
{ replaceOne: { filter: { c: 3 }, replacement: { c: 4 }, upsert: true } }
],
{ ordered: true, w: 1 }
);
test.equal(1, r.nInserted);
test.equal(2, r.nUpserted);
test.equal(0, r.nRemoved);
// Crud fields
test.equal(1, r.insertedCount);
test.equal(1, Object.keys(r.insertedIds).length);
test.equal(1, r.matchedCount);
test.ok(r.modifiedCount === 0 || r.modifiedCount === 1);
test.equal(0, r.deletedCount);
test.equal(2, r.upsertedCount);
test.equal(2, Object.keys(r.upsertedIds).length);
// Ordered bulk operation
client.close();
});
// END
}
});
/**
* Example of a simple findOneAndDelete operation using a Generator and the co module.
*
* @example-class Collection
* @example-method findOneAndDelete
* @ignore
*/
it('Should correctly execute findOneAndDelete operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('find_one_and_delete_with_generators');
var r = yield col.insertMany([{ a: 1, b: 1 }], { w: 1 });
test.equal(1, r.result.n);
r = yield col.findOneAndDelete({ a: 1 }, { projection: { b: 1 }, sort: { a: 1 } });
test.equal(1, r.lastErrorObject.n);
test.equal(1, r.value.b);
client.close();
});
// END
}
});
/**
* Example of a simple findOneAndReplace operation using a Generator and the co module.
*
* @example-class Collection
* @example-method findOneAndReplace
* @ignore
*/
it('Should correctly execute findOneAndReplace operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('find_one_and_replace_with_generators');
var r = yield col.insertMany([{ a: 1, b: 1 }], { w: 1 });
test.equal(1, r.result.n);
r = yield col.findOneAndReplace(
{ a: 1 },
{ c: 1, b: 1 },
{
projection: { b: 1, c: 1 },
sort: { a: 1 },
returnOriginal: false,
upsert: true
}
);
test.equal(1, r.lastErrorObject.n);
test.equal(1, r.value.b);
test.equal(1, r.value.c);
client.close();
});
// END
}
});
/**
* Example of a simple findOneAndUpdate operation using a Generator and the co module.
*
* @example-class Collection
* @example-method findOneAndUpdate
* @ignore
*/
it('Should correctly execute findOneAndUpdate operation with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Get the collection
var col = db.collection('find_one_and_update_with_generators');
var r = yield col.insertMany([{ a: 1, b: 1 }], { w: 1 });
test.equal(1, r.result.n);
r = yield col.findOneAndUpdate(
{ a: 1 },
{ $set: { d: 1 } },
{
projection: { b: 1, d: 1 },
sort: { a: 1 },
returnOriginal: false,
upsert: true
}
);
test.equal(1, r.lastErrorObject.n);
test.equal(1, r.value.b);
test.equal(1, r.value.d);
client.close();
});
// END
}
});
/**
* A simple example showing the listening to a capped collection using a Generator and the co module.
*
* @example-class Db
* @example-method createCollection
* @ignore
*/
it('Should correctly add capped collection options to cursor with Generators', {
metadata: { requires: { generators: true, topology: ['single'] } },
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
// Connect
var client = yield configuration
.newClient(configuration.writeConcernMax(), { poolSize: 1 })
.connect();
var db = client.db(configuration.db);
// LINE var MongoClient = require('mongodb').MongoClient,
// LINE co = require('co');
// LINE test = require('assert');
// LINE
// LINE co(function*() {
// LINE var client = yield MongoClient.connect('mongodb://localhost:27017/test');
// LINE var db = client.db('test');
// REPLACE configuration.writeConcernMax() WITH {w:1}
// BEGIN
// Create a capped collection with a maximum of 1000 documents
var collection = yield db.createCollection('a_simple_collection_2_with_generators', {
capped: true,
size: 100000,
max: 10000,
w: 1
});
var docs = [];
for (var i = 0; i < 1000; i++) docs.push({ a: i });
// Insert a document in the capped collection
yield collection.insertMany(docs, configuration.writeConcernMax());
yield new Promise(resolve => {
var total = 0;
// Get the cursor
var cursor = collection
.find({})
.addCursorFlag('tailable', true)
.addCursorFlag('awaitData', true);
cursor.on('data', function() {
total = total + 1;
if (total === 1000) {
cursor.kill();
}
});
cursor.on('end', function() {
client.close();
resolve();
});
});
});
// END
}
});
/**
* Correctly call the aggregation framework to return a cursor with batchSize 1 and get the first result using next
*
* @ignore
*/
it('Correctly handle sample aggregation', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: {
requires: {
generators: true,
mongodb: '>=3.2.0',
topology: 'single'
},
ignore: { travis: true }
},
// The actual test we wish to run
test: function() {
var configuration = this.configuration;
var co = require('co');
return co(function*() {
var client = configuration.newClient({ w: 1 }, { poolSize: 1 });
client = yield client.connect();
var db = client.db(configuration.db);
var string = new Array(6000000).join('x');
// Get the collection
var collection = db.collection('bigdocs_aggregate_sample_issue');
// Go over the number of
for (var i = 0; i < 100; i++) {
yield collection.insertOne({
s: string
});
}
yield collection.count();
var options = {
maxTimeMS: 10000,
allowDiskUse: true
};
var index = 0;
collection
.aggregate(
[
{
$sample: {
size: 100
}
}
],
options
)
.batchSize(10)
.on('error', function() {
client.close();
})
.on('data', function() {
index = index + 1;
})
// `end` sometimes emits before any `data` events have been emitted,
// depending on document size.
.on('end', function() {
test.equal(100, index);
client.close();
});
});
}
});
});
| 1 | 14,771 | should this be here twice? | mongodb-node-mongodb-native | js |
@@ -46,8 +46,13 @@ public:
width_ = GENERATE(16, 128, 1024);
stride_ = GENERATE(16, 128, 1024);
height_ = GENERATE(16, 128, 1024, 16384, 32768);
- SKIP_IF(width_ > stride_);
- REQUIRE(width_ <= stride_);
+ CAPTURE(width_, stride_, height_);
+ }
+
+ void generate_special() {
+ width_ = GENERATE(28, 960, 2000, 3072);
+ height_ = GENERATE(1024, 4096);
+ stride_ = height_;
CAPTURE(width_, stride_, height_);
}
| 1 | /*******************************************************************************
* Copyright 2021 Intel Corporation
*
* 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 <array>
#include <cmath>
#include <type_traits>
#include "oneapi/dal/test/engine/common.hpp"
#include "oneapi/dal/test/engine/fixtures.hpp"
#include "oneapi/dal/test/engine/dataframe.hpp"
#include "oneapi/dal/table/row_accessor.hpp"
#include "oneapi/dal/backend/primitives/reduction/reduction_rm_cw_dpc.hpp"
namespace oneapi::dal::backend::primitives::test {
namespace te = dal::test::engine;
namespace pr = oneapi::dal::backend::primitives;
constexpr auto rm_order = ndorder::c;
using reduction_types = std::tuple<std::tuple<float, sum<float>, square<float>>>;
template <typename Param>
class reduction_rm_test_uniform : public te::float_algo_fixture<std::tuple_element_t<0, Param>> {
public:
using float_t = std::tuple_element_t<0, Param>;
using binary_t = std::tuple_element_t<1, Param>;
using unary_t = std::tuple_element_t<2, Param>;
void generate() {
width_ = GENERATE(16, 128, 1024);
stride_ = GENERATE(16, 128, 1024);
height_ = GENERATE(16, 128, 1024, 16384, 32768);
SKIP_IF(width_ > stride_);
REQUIRE(width_ <= stride_);
CAPTURE(width_, stride_, height_);
}
bool is_initialized() const {
return width_ > 0 && stride_ > 0 && height_ > 0;
}
void check_if_initialized() {
if (!is_initialized()) {
throw std::runtime_error{ "reduce test is not initialized" };
}
}
bool should_be_skipped() {
if (width_ > stride_) {
return true;
}
return false;
}
auto input() {
check_if_initialized();
return ndarray<float_t, 2, rm_order>::zeros(this->get_queue(),
{ stride_, height_ },
sycl::usm::alloc::device);
}
auto output(std::int64_t size) {
check_if_initialized();
return ndarray<float_t, 1, rm_order>::zeros(this->get_queue(),
{ size },
sycl::usm::alloc::device);
}
auto fpt_desc() {
if constexpr (std::is_same_v<float_t, float>) {
return "float";
}
if constexpr (std::is_same_v<float_t, double>) {
return "double";
}
REQUIRE(false);
return "unknown type";
}
auto type_desc() {
return fmt::format("Floating Point Type: {}", fpt_desc());
}
auto matrix_desc() {
check_if_initialized();
return fmt::format("Row-Major Matrix with parameters: "
"width_ = {}, stride_ = {}, height_ = {}",
width_,
stride_,
height_);
}
auto unary_desc() {
if (std::is_same_v<identity<float_t>, unary_t>) {
return "Identity Unary Functor";
}
if (std::is_same_v<abs<float_t>, unary_t>) {
return "Abs Unary Functor";
}
if (std::is_same_v<square<float_t>, unary_t>) {
return "Square Unary Functor";
}
REQUIRE(false);
return "Unknown Unary Functor";
}
auto binary_desc() {
if (std::is_same_v<sum<float_t>, binary_t>) {
return "Sum Binary Functor";
}
if (std::is_same_v<max<float_t>, binary_t>) {
return "Max Binary Functor";
}
if (std::is_same_v<min<float_t>, binary_t>) {
return "Min Binary Functor";
}
REQUIRE(false);
return "Unknown Binary Functor";
}
auto desc() {
return fmt::format("{}; {}; {}; {}",
matrix_desc(),
type_desc(),
unary_desc(),
binary_desc());
}
void test_raw_cw_reduce_naive() {
using reduction_t = reduction_rm_cw_naive<float_t, binary_t, unary_t>;
auto [inp_array, inp_event] = input();
auto [out_array, out_event] = output(width_);
const float_t* inp_ptr = inp_array.get_data();
float_t* out_ptr = out_array.get_mutable_data();
const auto name = fmt::format("Naive CW Reduction: {}", desc());
this->get_queue().wait_and_throw();
BENCHMARK(name.c_str()) {
reduction_t reducer(this->get_queue());
reducer(inp_ptr, out_ptr, width_, height_, stride_, binary_t{}, unary_t{})
.wait_and_throw();
};
}
void test_raw_cw_reduce_naive_local() {
using reduction_t = reduction_rm_cw_naive_local<float_t, binary_t, unary_t>;
auto [inp_array, inp_event] = input();
auto [out_array, out_event] = output(width_);
const float_t* inp_ptr = inp_array.get_data();
float_t* out_ptr = out_array.get_mutable_data();
const auto name = fmt::format("Naive Local CW Reduction: {}", desc());
this->get_queue().wait_and_throw();
BENCHMARK(name.c_str()) {
reduction_t reducer(this->get_queue());
reducer(inp_ptr, out_ptr, width_, height_, stride_, binary_t{}, unary_t{})
.wait_and_throw();
};
}
void test_raw_cw_reduce_wrapper() {
using reduction_t = reduction_rm_cw<float_t, binary_t, unary_t>;
auto [inp_array, inp_event] = input();
auto [out_array, out_event] = output(width_);
const float_t* inp_ptr = inp_array.get_data();
float_t* out_ptr = out_array.get_mutable_data();
const auto name = fmt::format("Naive CW Reduction Wrapper: {}", desc());
this->get_queue().wait_and_throw();
BENCHMARK(name.c_str()) {
reduction_t reducer(this->get_queue());
reducer(inp_ptr, out_ptr, width_, height_, stride_, binary_t{}, unary_t{})
.wait_and_throw();
};
}
private:
std::int64_t width_;
std::int64_t stride_;
std::int64_t height_;
};
TEMPLATE_LIST_TEST_M(reduction_rm_test_uniform,
"Uniformly filled Row-Major Col-Wise reduction",
"[reduction][rm][small]",
reduction_types) {
SKIP_IF(this->not_float64_friendly());
this->generate();
SKIP_IF(this->should_be_skipped());
this->test_raw_cw_reduce_naive();
this->test_raw_cw_reduce_naive_local();
this->test_raw_cw_reduce_wrapper();
}
} // namespace oneapi::dal::backend::primitives::test
| 1 | 29,476 | `generate_special` - a meaningless name for me. Can we provide more detailed naming? | oneapi-src-oneDAL | cpp |
@@ -61,8 +61,8 @@ feature 'Subscriber views subscription invoices' do
@current_user.stripe_customer_id = "cus_NOMATCH"
@current_user.save!
- visit subscriber_invoice_path("in_1s4JSgbcUaElzU")
-
- expect(page).to have_content 'ActiveRecord::RecordNotFound'
+ expect {
+ visit subscriber_invoice_path("in_1s4JSgbcUaElzU")
+ }.to raise_error ActiveRecord::RecordNotFound
end
end | 1 | require 'spec_helper'
feature 'Subscriber views subscription invoices' do
scenario 'Subscriber views a listing of all invoices' do
sign_in_as_user_with_subscription
@current_user.stripe_customer_id = FakeStripe::CUSTOMER_ID
@current_user.save!
visit my_account_path
click_link 'View all invoices'
expect(page).to have_css('.number', text: '130521')
expect(page).to have_css('.date', text: '05/21/13')
expect(page).to have_css('.total', text: '$79.00')
expect(page).to have_css('.balance', text: '$0.00')
click_link '130521'
expect(page).to have_content('Invoice 130521')
end
scenario 'Subscriber can view a subscription invoice' do
create_mentors
sign_in_as_user_with_subscription
plan_purchase = create(:plan_purchase, user: @current_user)
@current_user.stripe_customer_id = FakeStripe::CUSTOMER_ID
@current_user.organization = 'Sprockets, LLC'
@current_user.address1 = '1 Street Way'
@current_user.address2 = 'Suite 3'
@current_user.city = 'Austin'
@current_user.state = 'TX'
@current_user.zip_code = '00000'
@current_user.country = 'USA'
@current_user.save!
visit subscriber_invoice_path("in_1s4JSgbcUaElzU")
expect(page).to have_content('Invoice 130521')
expect(page).to have_content('Date 05/21/13')
expect(page).to have_css('.subscription', text: 'Subscription to Prime')
expect(page).to have_css('.subscription', text: '$99.00 USD')
expect(page).to have_css('.subtotal', text: '$99.00 USD')
expect(page).to have_css('.discount', text: 'Discount: railsconf')
expect(page).to have_css('.discount', text: '- $20.00 USD')
expect(page).to have_css('.total', text: '$79.00 USD')
expect(page).to have_content('Invoice lookup: in_1s4JSgbcUaElzU')
expect(page).to have_content(@current_user.organization)
expect(page).to have_content(@current_user.address1)
expect(page).to have_content(@current_user.address2)
expect(page).to have_content(@current_user.city)
expect(page).to have_content(@current_user.state)
expect(page).to have_content(@current_user.zip_code)
expect(page).to have_content(@current_user.country)
end
scenario "a subscriber can't view another user's invoice" do
create_mentors
sign_in_as_user_with_subscription
plan_purchase = create(:plan_purchase, user: @current_user)
@current_user.stripe_customer_id = "cus_NOMATCH"
@current_user.save!
visit subscriber_invoice_path("in_1s4JSgbcUaElzU")
expect(page).to have_content 'ActiveRecord::RecordNotFound'
end
end
| 1 | 8,913 | This isn't something you introduced in your changes, but the change makes more obvious to me that this test would be better as a unit test of some kind (probably a controller test). Testing a 404 is an edge case that probably doesn't need to be tested with all components in integration. | thoughtbot-upcase | rb |
@@ -102,7 +102,7 @@ class ExternalDriverSupplier implements Supplier<WebDriver> {
Optional<Class<? extends Supplier<WebDriver>>> supplierClass = getDelegateClass();
if (supplierClass.isPresent()) {
Class<? extends Supplier<WebDriver>> clazz = supplierClass.get();
- logger.info("Using delegate supplier: " + clazz.getName());
+ logger.finest("Using delegate supplier: " + clazz.getName());
try {
@SuppressWarnings("unchecked")
Constructor<Supplier<WebDriver>> ctor = | 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
package org.openqa.selenium.testing.drivers;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.base.Suppliers;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.net.UrlChecker;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.logging.Logger;
/**
* Supports providing WebDriver instances from an external source using the following system
* properties:
* <dl>
* <dt>selenium.external.serverUrl</dt>
* <dd>Defines the fully qualified URL of an external WebDriver server to send commands to.
* This server <i>must</i> be compliant with the
* <a href="https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol">JSON wire protocol</a>.
* If only this property is provided, then this supplier will provide a new
* {@link RemoteWebDriver} instance pointed at the designated server. Otherwise, if a
* custom supplier is also defined (see below), this supplier will wait for the server to
* be accepting commands before delegating to the designated class for the actual client
* creation.
* </dd>
* <dt>selenium.external.supplierClass</dt>
* <dd>Specifies the fully qualified name of another class on the classpath. This class must
* implement {@code Supplier<WebDriver>} and have a public constructor that accepts two
* {@link Capabilities} objects as arguments (for the desired and required capabilities,
* respectively).
* </dd>
* </dl>
*/
class ExternalDriverSupplier implements Supplier<WebDriver> {
private static final Logger logger = Logger.getLogger(ExternalDriverSupplier.class.getName());
private static final String DELEGATE_SUPPLIER_CLASS_PROPERTY = "selenium.external.supplierClass";
private static final String EXTERNAL_SERVER_URL_PROPERTY = "selenium.external.serverUrl";
private final Capabilities desiredCapabilities;
ExternalDriverSupplier(Capabilities desiredCapabilities) {
this.desiredCapabilities = new ImmutableCapabilities(desiredCapabilities);
}
@Override
public WebDriver get() {
Optional<Supplier<WebDriver>> delegate = createDelegate(desiredCapabilities);
delegate = createForExternalServer(desiredCapabilities, delegate);
return delegate.orElse(Suppliers.ofInstance(null)).get();
}
private static Optional<Supplier<WebDriver>> createForExternalServer(
Capabilities desiredCapabilities,
Optional<Supplier<WebDriver>> delegate) {
String externalUrl = System.getProperty(EXTERNAL_SERVER_URL_PROPERTY);
if (externalUrl != null) {
logger.info("Using external WebDriver server: " + externalUrl);
URL url;
try {
url = new URL(externalUrl);
} catch (MalformedURLException e) {
throw new RuntimeException("Invalid server URL: " + externalUrl, e);
}
Supplier<WebDriver> defaultSupplier = new DefaultRemoteSupplier(url, desiredCapabilities);
Supplier<WebDriver> supplier = new ExternalServerDriverSupplier(
url, delegate.orElse(defaultSupplier));
return Optional.of(supplier);
}
return delegate;
}
private static Optional<Supplier<WebDriver>> createDelegate(Capabilities desiredCapabilities) {
Optional<Class<? extends Supplier<WebDriver>>> supplierClass = getDelegateClass();
if (supplierClass.isPresent()) {
Class<? extends Supplier<WebDriver>> clazz = supplierClass.get();
logger.info("Using delegate supplier: " + clazz.getName());
try {
@SuppressWarnings("unchecked")
Constructor<Supplier<WebDriver>> ctor =
(Constructor<Supplier<WebDriver>>) clazz.getConstructor(Capabilities.class);
return Optional.of(ctor.newInstance(desiredCapabilities));
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private static Optional<Class<? extends Supplier<WebDriver>>> getDelegateClass() {
String delegateClassName = System.getProperty(DELEGATE_SUPPLIER_CLASS_PROPERTY);
if (delegateClassName != null) {
try {
logger.info("Loading custom supplier: " + delegateClassName);
Class<? extends Supplier<WebDriver>> clazz =
(Class<? extends Supplier<WebDriver>>) Class.forName(delegateClassName);
return Optional.of(clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return Optional.empty();
}
/**
* Waits for an external WebDriver server to be ready before delegating to another supplier
* for driver creation.
*/
private static class ExternalServerDriverSupplier implements Supplier<WebDriver> {
private final URL serverUrl;
private final Supplier<WebDriver> delegateSupplier;
private ExternalServerDriverSupplier(
URL serverUrl, Supplier<WebDriver> delegateSupplier) {
this.serverUrl = serverUrl;
this.delegateSupplier = delegateSupplier;
}
@Override
public WebDriver get() {
try {
logger.info("Waiting for server to be ready at " + serverUrl);
new UrlChecker().waitUntilAvailable(60, SECONDS, new URL(serverUrl + "/status"));
logger.info("Server is ready");
} catch (UrlChecker.TimeoutException e) {
throw new RuntimeException("The external server is not accepting commands", e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
return delegateSupplier.get();
}
}
/**
* Creates basic {@link RemoteWebDriver} instances.
*/
private static class DefaultRemoteSupplier implements Supplier<WebDriver> {
private final URL url;
private final Capabilities desiredCapabilities;
private DefaultRemoteSupplier(URL url, Capabilities desiredCapabilities) {
this.url = url;
this.desiredCapabilities = desiredCapabilities;
}
@Override
public WebDriver get() {
RemoteWebDriver driver = new RemoteWebDriver(url, desiredCapabilities);
driver.setFileDetector(new LocalFileDetector());
return driver;
}
}
}
| 1 | 16,449 | We chose `info` in the test code for obvious reasons. Changing to `finest` makes debugging harder and noisier. | SeleniumHQ-selenium | py |
@@ -139,7 +139,7 @@ public class BaseRemoteProxy implements RemoteProxy {
this.id = id;
} else {
// otherwise assign the remote host as id.
- this.id = remoteHost.toExternalForm();
+ this.id = id = "http://" + remoteHost.getHost() + ":" + remoteHost.getPort();
}
maxConcurrentSession = getConfigInteger(RegistrationRequest.MAX_SESSION); | 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
package org.openqa.grid.internal;
import static org.openqa.grid.common.RegistrationRequest.MAX_INSTANCES;
import static org.openqa.grid.common.RegistrationRequest.PATH;
import static org.openqa.grid.common.RegistrationRequest.REMOTE_HOST;
import static org.openqa.grid.common.RegistrationRequest.SELENIUM_PROTOCOL;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.util.EntityUtils;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.common.SeleniumProtocol;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.listeners.TimeoutListener;
import org.openqa.grid.internal.utils.CapabilityMatcher;
import org.openqa.grid.internal.utils.DefaultHtmlRenderer;
import org.openqa.grid.internal.utils.HtmlRenderer;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.internal.HttpClientFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BaseRemoteProxy implements RemoteProxy {
private final RegistrationRequest request;
// how many ms between 2 cycle checking if there are some session that have
// timed out. -1 means we never run the cleanup cycle. By default there is
// no timeout
private final int cleanUpCycle;
private final int timeOutMs;
private static final Logger log = Logger.getLogger(BaseRemoteProxy.class.getName());
// the host the remote listen on.The final URL will be proxy.host + slot.path
protected volatile URL remoteHost;
private final Map<String, Object> config;
// list of the type of test the remote can run.
private final List<TestSlot> testSlots;
// maximum number of tests that can run at a given time on the remote.
private final int maxConcurrentSession;
private final Registry registry;
private final String id;
private volatile boolean stop = false;
private CleanUpThread cleanUpThread;
// connection and socket timeout for getStatus node alive check
// 0 means default timeouts of grid http client will be used.
private final int statusCheckTimeout;
public List<TestSlot> getTestSlots() {
return testSlots;
}
public Registry getRegistry() {
return registry;
}
public CapabilityMatcher getCapabilityHelper() {
return registry.getCapabilityMatcher();
}
/**
* Create the proxy from the info sent by the remote. <p> If maxSession is not specified, default
* to 1 = max number of tests running at a given time will be 1. <p> For each capability,
* maxInstances is defaulted to 1 if not specified = max number of test of each capability running
* at a time will be 1. maxInstances for firefox can be > 1. IE won't support it.
*
* @param request The request
* @param registry The registry to use
*/
public BaseRemoteProxy(RegistrationRequest request, Registry registry) {
this.request = request;
this.registry = registry;
this.config =
mergeConfig(registry.getConfiguration().getAllParams(), request.getConfiguration());
String url = (String) config.get(REMOTE_HOST);
String id = (String) config.get(RegistrationRequest.ID);
if (url == null && id == null) {
throw new GridException(
"The registration request needs to specify either the remote host, or a valid id.");
}
if (url != null) {
try {
this.remoteHost = new URL(url);
} catch (MalformedURLException e) {
// should only happen when a bad config is sent.
throw new GridException("Not a correct url to register a remote : " + url);
}
}
// if id was provided in the request, use that
if (id != null) {
this.id = id;
} else {
// otherwise assign the remote host as id.
this.id = remoteHost.toExternalForm();
}
maxConcurrentSession = getConfigInteger(RegistrationRequest.MAX_SESSION);
cleanUpCycle = getConfigInteger(RegistrationRequest.CLEAN_UP_CYCLE);
timeOutMs = getConfigInteger(RegistrationRequest.TIME_OUT);
statusCheckTimeout = getConfigInteger(RegistrationRequest.STATUS_CHECK_TIMEOUT);
List<DesiredCapabilities> capabilities = request.getCapabilities();
List<TestSlot> slots = new ArrayList<>();
for (DesiredCapabilities capability : capabilities) {
Object maxInstance = capability.getCapability(MAX_INSTANCES);
SeleniumProtocol protocol = getProtocol(capability);
String path = getPath(capability);
if (maxInstance == null) {
log.warning("Max instance not specified. Using default = 1 instance");
maxInstance = "1";
}
int value = Integer.parseInt(maxInstance.toString());
for (int i = 0; i < value; i++) {
Map<String, Object> c = new HashMap<>();
for (String k : capability.asMap().keySet()) {
c.put(k, capability.getCapability(k));
}
slots.add(new TestSlot(this, protocol, path, c));
}
}
this.testSlots = Collections.unmodifiableList(slots);
}
private Integer getConfigInteger(String key){
Object o = this.config.get(key);
if (o == null) {
return 0;
}
if (o instanceof String){
return Integer.parseInt((String)o);
}
return (Integer) o;
}
private SeleniumProtocol getProtocol(DesiredCapabilities capability) {
String type = (String) capability.getCapability(SELENIUM_PROTOCOL);
SeleniumProtocol protocol;
if (type == null) {
protocol = SeleniumProtocol.WebDriver;
} else {
try {
protocol = SeleniumProtocol.valueOf(type);
} catch (IllegalArgumentException e) {
throw new GridException(
type + " isn't a valid protocol type for grid. See SeleniumProtocol enum.", e);
}
}
return protocol;
}
private String getPath(DesiredCapabilities capability) {
String type = (String) capability.getCapability(PATH);
if (type == null) {
switch (getProtocol(capability)) {
case Selenium:
return "/selenium-server/driver";
case WebDriver:
return "/wd/hub";
default:
throw new GridException("Protocol not supported.");
}
} else {
return type;
}
}
public void setupTimeoutListener() {
cleanUpThread = null;
if (this instanceof TimeoutListener) {
if (cleanUpCycle > 0 && timeOutMs > 0) {
log.fine("starting cleanup thread");
cleanUpThread = new CleanUpThread(this);
new Thread(cleanUpThread, "RemoteProxy CleanUpThread for " + getId())
.start(); // Thread safety reviewed (hopefully ;)
}
}
}
/**
* merge the param from config 1 and 2. If a param is present in both, config2 value is used.
*
* @param configuration1 The first configuration to merge (recessive)
* @param configuration2 The second configuration to merge (dominant)
* @return The merged collection
*/
private Map<String, Object> mergeConfig(Map<String, Object> configuration1,
Map<String, Object> configuration2) {
Map<String, Object> res = new HashMap<>();
res.putAll(configuration1);
for (String key : configuration2.keySet()) {
res.put(key, configuration2.get(key));
}
return res;
}
public String getId() {
if (id == null) {
throw new RuntimeException("Bug. Trying to use the id on a proxy but it hasn't been set.");
}
return id;
}
public void teardown() {
stop = true;
}
/**
* Internal use only
*/
public void forceSlotCleanerRun() {
cleanUpThread.cleanUpAllSlots();
}
class CleanUpThread implements Runnable {
private BaseRemoteProxy proxy;
public CleanUpThread(BaseRemoteProxy proxy) {
this.proxy = proxy;
}
public void run() {
log.fine("cleanup thread starting...");
while (!proxy.stop) {
try {
Thread.sleep(cleanUpCycle);
} catch (InterruptedException e) {
log.severe("clean up thread died. " + e.getMessage());
}
cleanUpAllSlots();
}
}
void cleanUpAllSlots() {
for (TestSlot slot : testSlots) {
try {
cleanUpSlot(slot);
} catch (Throwable t) {
log.warning("Error executing the timeout when cleaning up slot " + slot
+ t.getMessage());
}
}
}
private void cleanUpSlot(TestSlot slot) {
TestSession session = slot.getSession();
if (session != null) {
long inactivity = session.getInactivityTime();
boolean hasTimedOut = inactivity > timeOutMs;
if (hasTimedOut) {
if (!session.isForwardingRequest()) {
log.logp(Level.WARNING, "SessionCleanup", null,
"session " + session
+ " has TIMED OUT due to client inactivity and will be released.");
try {
((TimeoutListener) proxy).beforeRelease(session);
} catch(IllegalStateException ignore){
log.log(Level.WARNING, ignore.getMessage());
}
registry.terminate(session, SessionTerminationReason.TIMEOUT);
}
}
if (session.isOrphaned()) {
log.logp(Level.WARNING, "SessionCleanup", null,
"session " + session + " has been ORPHANED and will be released");
try {
((TimeoutListener) proxy).beforeRelease(session);
} catch(IllegalStateException ignore){
log.log(Level.WARNING, ignore.getMessage());
}
registry.terminate(session, SessionTerminationReason.ORPHAN);
}
}
}
}
public Map<String, Object> getConfig() {
return config;
}
public RegistrationRequest getOriginalRegistrationRequest() {
return request;
}
public int getMaxNumberOfConcurrentTestSessions() {
return maxConcurrentSession;
}
public URL getRemoteHost() {
return remoteHost;
}
public TestSession getNewSession(Map<String, Object> requestedCapability) {
log.info("Trying to create a new session on node " + this);
if (!hasCapability(requestedCapability)) {
log.info("Node " + this + " has no matching capability");
return null;
}
// any slot left at all?
if (getTotalUsed() >= maxConcurrentSession) {
log.info("Node " + this + " has no free slots");
return null;
}
// any slot left for the given app ?
for (TestSlot testslot : testSlots) {
TestSession session = testslot.getNewSession(requestedCapability);
if (session != null) {
return session;
}
}
return null;
}
public int getTotalUsed() {
int totalUsed = 0;
for (TestSlot slot : testSlots) {
if (slot.getSession() != null) {
totalUsed++;
}
}
return totalUsed;
}
public boolean hasCapability(Map<String, Object> requestedCapability) {
for (TestSlot slot : testSlots) {
if (slot.matches(requestedCapability)) {
return true;
}
}
return false;
}
public boolean isBusy() {
return getTotalUsed() != 0;
}
/**
* Takes a registration request and return the RemoteProxy associated to it. It can be any class
* extending RemoteProxy.
*
* @param request The request
* @param registry The registry to use
* @param <T> RemoteProxy subclass
* @return a new instance built from the request.
*/
@SuppressWarnings("unchecked")
public static <T extends RemoteProxy> T getNewInstance(
RegistrationRequest request, Registry registry) {
try {
String proxyClass = request.getRemoteProxyClass();
if (proxyClass == null) {
log.fine("No proxy class. Using default");
proxyClass = BaseRemoteProxy.class.getCanonicalName();
}
Class<?> clazz = Class.forName(proxyClass);
log.fine("Using class " + clazz.getName());
Object[] args = new Object[]{request, registry};
Class<?>[] argsClass = new Class[]{RegistrationRequest.class, Registry.class};
Constructor<?> c = clazz.getConstructor(argsClass);
Object proxy = c.newInstance(args);
if (proxy instanceof RemoteProxy) {
((RemoteProxy) proxy).setupTimeoutListener();
return (T) proxy;
} else {
throw new InvalidParameterException("Error: " + proxy.getClass() + " isn't a remote proxy");
}
} catch (InvocationTargetException e) {
throw new InvalidParameterException("Error: " + e.getTargetException().getMessage());
} catch (Exception e) {
throw new InvalidParameterException("Error: " + e.getMessage());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RemoteProxy other = (RemoteProxy) obj;
if (getId() == null) {
if (other.getId() != null) {
return false;
}
} else if (!getId().equals(other.getId())) {
return false;
}
return true;
}
// less busy to more busy.
public int compareTo(RemoteProxy o) {
if (o == null) {
return -1;
}
return (int)(getResourceUsageInPercent() - o.getResourceUsageInPercent());
}
@Override
public String toString() {
return getRemoteHost() != null ? getRemoteHost().toString() : "<detached>";
}
private final HtmlRenderer renderer = new DefaultHtmlRenderer(this);
public HtmlRenderer getHtmlRender() {
return renderer;
}
public int getTimeOut() {
return timeOutMs;
}
public HttpClientFactory getHttpClientFactory() {
return getRegistry().getHttpClientFactory();
}
/**
* @throws GridException If the node if down or doesn't recognize the /wd/hub/status request.
*/
public JsonObject getStatus() throws GridException {
String url = getRemoteHost().toExternalForm() + "/wd/hub/status";
BasicHttpRequest r = new BasicHttpRequest("GET", url);
HttpClient client = getHttpClientFactory().getGridHttpClient(statusCheckTimeout, statusCheckTimeout);
HttpHost host = new HttpHost(getRemoteHost().getHost(), getRemoteHost().getPort());
HttpResponse response;
String existingName = Thread.currentThread().getName();
HttpEntity entity = null;
try {
Thread.currentThread().setName("Probing status of " + url);
response = client.execute(host, r);
entity = response.getEntity();
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
JsonObject status = new JsonObject();
try {
status = extractObject(response);
} catch (Exception e) {
// ignored due it's not required from node to return anything. Just 200 code is enough.
}
EntityUtils.consume(response.getEntity());
return status;
} else if (code == 404) { // selenium RC case
JsonObject status = new JsonObject();
EntityUtils.consume(response.getEntity());
return status;
} else {
EntityUtils.consume(response.getEntity());
throw new GridException("server response code : " + code);
}
} catch (Exception e) {
throw new GridException(e.getMessage(), e);
} finally {
Thread.currentThread().setName(existingName);
try { //Added by jojo to release connection thoroughly
EntityUtils.consume(entity);
} catch (IOException e) {
log.info("Exception thrown when consume entity");
}
}
}
private JsonObject extractObject(HttpResponse resp) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
StringBuilder s = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
s.append(line);
}
rd.close();
return new JsonParser().parse(s.toString()).getAsJsonObject();
}
public float getResourceUsageInPercent() {
return 100 * (float)getTotalUsed() / (float)getMaxNumberOfConcurrentTestSessions();
}
}
| 1 | 12,733 | any reason you're assigning to the local variable 'id' too? | SeleniumHQ-selenium | py |
@@ -28,6 +28,7 @@ import sys
import termios
from subprocess import CalledProcessError
+import molecule.validators as validators
import prettytable
import sh
import vagrant | 1 | # Copyright (c) 2015 Cisco Systems
#
# 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.
import fcntl
import os
import pexpect
import re
import signal
import struct
import sys
import termios
from subprocess import CalledProcessError
import prettytable
import sh
import vagrant
import yaml
from colorama import Fore
from jinja2 import Environment
from jinja2 import PackageLoader
class Molecule(object):
# locations to look for a config file
CONFIG_PATHS = [os.environ.get('MOLECULE_CONFIG'), os.path.expanduser('~/.config/molecule/config.yml'),
'/etc/molecule/config.yml']
# these defaults will be overwritten if a config file is found in CONFIG_PATHS
CONFIG_DEFAULTS = {
'molecule_file': 'molecule.yml',
'molecule_dir': '.molecule',
'state_file': 'state',
'vagrantfile_file': 'vagrantfile',
'vagrantfile_template': 'vagrantfile.j2',
'ansible_config_template': 'ansible.cfg.j2',
'rakefile_file': 'rakefile',
'rakefile_template': 'rakefile.j2',
'ignore_paths': ['.git', '.vagrant', '.molecule'],
'serverspec_dir': 'spec',
'testinfra_dir': 'tests',
'raw_ssh_args': ['-o StrictHostKeyChecking=no', '-o UserKnownHostsFile=/dev/null'],
'test': {
'sequence': ['destroy', 'create', 'converge', 'idempotence', 'verify', 'destroy']
},
'init': {
'platform': {
'name': 'trusty64',
'box': 'trusty64',
'box_url': 'https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/14.04/providers/virtualbox.box'
},
'templates': {
'molecule': 'molecule.yml.j2',
'playbook': 'playbook.yml.j2',
'spec_helper': 'spec_helper.rb.j2',
'default_spec': 'default_spec.rb.j2'
}
},
'providers': {
'virtualbox': {
'options': {
'memory': 512,
'cpus': 2
}
}
},
'ansible': {
'config_file': 'ansible.cfg',
'user': 'vagrant',
'connection': 'ssh',
'timeout': '30',
'playbook': 'playbook.yml',
'sudo': True,
'sudo_user': False,
'ask_sudo_pass': False,
'ask_vault_pass': False,
'vault_password_file': False,
'limit': 'all',
'verbose': False,
'diff': True,
'tags': False,
'host_key_checking': False,
'inventory_file': 'ansible_inventory',
'raw_ssh_args': [
'-o UserKnownHostsFile=/dev/null', '-o IdentitiesOnly=yes', '-o ControlMaster=auto',
'-o ControlPersist=60s'
]
}
}
def __init__(self, args):
self._created = False
self._provisioned = False
self._env = os.environ.copy()
self._args = args
self._main()
def _main(self):
# init command is handled different than the others
if self._args['init']:
self._config, self._molecule_file = self._load_config(skip_molecule_file=True)
self._init_new_role()
self._config, self._molecule_file = self._load_config()
if not os.path.exists(self._config['molecule_dir']):
os.makedirs(self._config['molecule_dir'])
self._vagrant = vagrant.Vagrant(quiet_stdout=False, quiet_stderr=False)
if self._args['--tags']:
self._env['MOLECULE_TAGS'] = self._args['--tags']
if self._args['--provider']:
if not [item
for item in self._molecule_file['vagrant']['providers']
if item['name'] == self._args['--provider']]:
print("\n{0}Invalid provider '{1}'\n".format(Fore.RED, self._args['--provider'], Fore.RESET))
self._print_valid_providers()
sys.exit(1)
self._set_default_provider(provider=self._args['--provider'])
self._env['VAGRANT_DEFAULT_PROVIDER'] = self._args['--provider']
else:
self._env['VAGRANT_DEFAULT_PROVIDER'] = self._get_default_provider()
if self._args['--platform']:
if not [item
for item in self._molecule_file['vagrant']['platforms']
if item['name'] == self._args['--platform']]:
print("\n{0}Invalid platform '{1}'\n".format(Fore.RED, self._args['--platform'], Fore.RESET))
self._print_valid_platforms()
sys.exit(1)
self._set_default_platform(platform=self._args['--platform'])
self._env['MOLECULE_PLATFORM'] = self._args['--platform']
else:
self._env['MOLECULE_PLATFORM'] = self._get_default_platform()
self._vagrant.env = self._env
def _load_config(self, skip_molecule_file=False):
config = self._get_config()
molecule_file = None
if not skip_molecule_file:
molecule_file = self._load_molecule_file(config)
# if molecule file has a molecule section, merge that into our config as
# an override with the highest precedence
if 'molecule' in molecule_file:
config.update(molecule_file['molecule'])
# merge virtualbox provider options from molecule file with our defaults
for provider in molecule_file['vagrant']['providers']:
if provider['type'] in config['providers']:
if 'options' in provider:
config['providers'][provider['type']]['options'].update(provider['options'])
# append molecule_dir to filenames so they're easier to use later
config['state_file'] = '/'.join([config['molecule_dir'], config['state_file']])
config['vagrantfile_file'] = '/'.join([config['molecule_dir'], config['vagrantfile_file']])
config['rakefile_file'] = '/'.join([config['molecule_dir'], config['rakefile_file']])
config['ansible']['config_file'] = '/'.join([config['molecule_dir'], config['ansible']['config_file']])
config['ansible']['inventory_file'] = '/'.join([config['molecule_dir'], config['ansible']['inventory_file']])
return config, molecule_file
def _get_config(self):
merged_config = Molecule.CONFIG_DEFAULTS.copy()
# merge defaults with a config file if found
for path in Molecule.CONFIG_PATHS:
if path and os.path.isfile(path):
with open(path, 'r') as stream:
merged_config.update(yaml.load(stream))
return merged_config
return Molecule.CONFIG_DEFAULTS
def _print_line(self, line):
print(line),
def _trailing_validators(self):
for dir, _, files in os.walk('.'):
for f in files:
split_dirs = dir.split(os.sep)
if split_dirs < 1:
if split_dirs[1] not in self._config['ignore_paths']:
filename = os.path.join(dir, f)
if os.path.getsize(filename) > 0:
self._trailing_newline(filename)
self._trailing_whitespace(filename)
def _trailing_newline(self, filename):
with open(filename, 'r') as f:
for line in f:
pass
last = line
if re.match(r'^\n$', last):
error = '{0}Trailing newline found in {1}{2}'
print error.format(Fore.RED, filename, Fore.RESET)
print last
sys.exit(1)
def _trailing_whitespace(self, filename):
with open(filename, 'r') as f:
for line in f:
l = line.rstrip('\n\r')
if re.search(r'\s+$', l):
error = '{0}Trailing whitespace found in {1}{2}'
print error.format(Fore.RED, filename, Fore.RESET)
print l
sys.exit(1)
def _rubocop(self):
try:
pattern = self._config['serverspec_dir'] + '/**/*.rb'
output = sh.rubocop(pattern, _env=self._env, _out=self._print_line, _err=self._print_line)
return output.exit_code
except sh.ErrorReturnCode as e:
print("ERROR: {0}".format(e))
sys.exit(e.exit_code)
def _load_state_file(self):
if not os.path.isfile(self._config['state_file']):
return False
with open(self._config['state_file'], 'r') as env:
self._state = yaml.load(env)
return True
def _write_state_file(self):
self._write_file(self._config['state_file'], yaml.dump(self._state, default_flow_style=False))
def _write_ssh_config(self):
try:
out = self._vagrant.ssh_config()
ssh_config = self._get_vagrant_ssh_config()
except CalledProcessError as e:
print("ERROR: {0}".format(e))
print("Does your vagrant VM exist?")
sys.exit(e.returncode)
self._write_file(ssh_config, out)
def _write_file(self, filename, content):
with open(filename, 'w') as f:
f.write(content)
def _get_vagrant_ssh_config(self):
return '.vagrant/ssh-config'
def _get_default_platform(self):
default_platform = self._molecule_file['vagrant']['platforms'][0]['name']
if not (self._load_state_file()):
return default_platform
# default to first entry if no entry for platform exists
if 'default_platform' not in self._state:
return default_platform
# key exists but is falsy
if not self._state['default_platform']:
return default_platform
return self._state['default_platform']
def _set_default_platform(self, platform=False):
if not hasattr(self, '_state'):
if not self._load_state_file():
self._state = {}
self._state['default_platform'] = platform
self._write_state_file()
def _print_valid_platforms(self):
print(Fore.CYAN + "AVAILABLE PLATFORMS" + Fore.RESET)
default_platform = self._get_default_platform()
for platform in self._molecule_file['vagrant']['platforms']:
default = ' (default)' if platform['name'] == default_platform else ''
print(platform['name'] + default)
def _get_default_provider(self):
default_provider = self._molecule_file['vagrant']['providers'][0]['name']
if not (self._load_state_file()):
return default_provider
# default to first entry if no entry for provider exists
if 'default_provider' not in self._state:
return default_provider
# key exists but is falsy
if not self._state['default_provider']:
return default_provider
return self._state['default_provider']
def _set_default_provider(self, provider=False):
if not hasattr(self, '_state'):
if not self._load_state_file():
self._state = {}
self._state['default_provider'] = provider
self._write_state_file()
def _print_valid_providers(self):
print(Fore.CYAN + "AVAILABLE PLATFORMS" + Fore.RESET)
default_provider = self._get_default_provider()
for provider in self._molecule_file['vagrant']['providers']:
default = ' (default)' if provider['name'] == default_provider else ''
print(provider['name'] + default)
def _sigwinch_passthrough(self, sig, data):
TIOCGWINSZ = 1074295912 # assume
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
s = struct.pack('HHHH', 0, 0, 0, 0)
a = struct.unpack('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s))
self._pt.setwinsize(a[0], a[1])
def _destroy(self):
try:
self._vagrant.halt()
self._vagrant.destroy()
self._set_default_platform(platform=False)
except CalledProcessError as e:
print("ERROR: {0}".format(e))
sys.exit(e.returncode)
def _create(self):
if not self._created:
try:
self._vagrant.up(no_provision=True)
self._created = True
except CalledProcessError as e:
print("ERROR: {0}".format(e))
sys.exit(e.returncode)
def _parse_provisioning_output(self, output):
"""
Parses the output of the provisioning method.
:param output:
:return: True if the playbook is idempotent, otherwise False
"""
# remove blank lines to make regex matches easier
output = re.sub("\n\s*\n*", "\n", output)
# look for any non-zero changed lines
changed = re.search(r'(changed=[1-9][0-9]*)', output)
if changed:
return False
return True
def _verify(self):
self._trailing_validators()
# no tests found
if not os.path.isdir(self._config['serverspec_dir']) and not os.path.isdir(self._config['testinfra_dir']):
msg = '{}Skipping tests, could not find {}/ or {}/.{}'
print(msg.format(Fore.YELLOW, self._config['serverspec_dir'], self._config['testinfra_dir'], Fore.RESET))
return
self._write_ssh_config()
kwargs = {'_env': self._env, '_out': self._print_line, '_err': self._print_line}
args = []
# testinfra
if os.path.isdir(self._config['testinfra_dir']):
ssh_config = '--ssh-config={0}'.format(self._get_vagrant_ssh_config())
try:
output = sh.testinfra(ssh_config, '--sudo', self._config['testinfra_dir'], **kwargs)
return output.exit_code
except sh.ErrorReturnCode as e:
print('ERROR: {}'.format(e))
sys.exit(e.exit_code)
# serverspec
if os.path.isdir(self._config['serverspec_dir']):
self._rubocop()
if 'rakefile_file' in self._config:
kwargs['rakefile'] = self._config['rakefile_file']
if self._args['--debug']:
args.append('--trace')
try:
rakecmd = sh.Command("rake")
output = rakecmd(*args, **kwargs)
return output.exit_code
except sh.ErrorReturnCode as e:
print('ERROR: {}'.format(e))
sys.exit(e.exit_code)
def test(self):
for task in self._config['test']['sequence']:
m = getattr(self, task)
m()
def list(self):
print
self._print_valid_platforms()
def status(self):
try:
status = self._vagrant.status()
except CalledProcessError as e:
print("ERROR: {0}".format(e))
return e.returncode
x = prettytable.PrettyTable(['Name', 'State', 'Provider'])
x.align = 'l'
for item in status:
if item.state != 'not_created':
state = Fore.GREEN + item.state + Fore.RESET
else:
state = item.state
x.add_row([item.name, state, item.provider])
print(x)
print
self._print_valid_platforms()
def login(self):
# make sure host argument is specified
host_format = [Fore.RED, self._args['<host>'], Fore.RESET, Fore.YELLOW, Fore.RESET]
host_errmsg = "\nTry molecule {3}molecule status{4} to see available hosts.\n".format(*host_format)
if not self._args['<host>']:
print('You must specify a host when using login')
print(host_errmsg)
sys.exit(1)
# make sure vagrant knows about this host
try:
conf = self._vagrant.conf(vm_name=self._args['<host>'])
ssh_args = [conf['HostName'], conf['User'], conf['Port'], conf['IdentityFile'],
' '.join(self._config['raw_ssh_args'])]
ssh_cmd = 'ssh {0} -l {1} -p {2} -i {3} {4}'
except CalledProcessError:
# gets appended to python-vagrant's error message
conf_format = [Fore.RED, self._args['<host>'], Fore.RESET, Fore.YELLOW, Fore.RESET]
print("\nTry molecule {3}molecule status{4} to see available hosts.\n".format(*conf_format))
sys.exit(1)
lines, columns = os.popen('stty size', 'r').read().split()
dimensions = (int(lines), int(columns))
self._pt = pexpect.spawn('/usr/bin/env ' + ssh_cmd.format(*ssh_args), dimensions=dimensions)
signal.signal(signal.SIGWINCH, self._sigwinch_passthrough)
self._pt.interact()
def _init_new_role(self):
role = self._args['<role>']
role_path = './' + role + '/'
if not role:
msg = '{}The init command requires a role name. Try:\n\n{}{} init <role>{}'
print(msg.format(Fore.RED, Fore.YELLOW, os.path.basename(sys.argv[0]), Fore.RESET))
sys.exit(1)
if os.path.isdir(role):
msg = '{}The directory {} already exists. Cannot create new role.{}'
print(msg.format(Fore.RED, role_path, Fore.RESET))
sys.exit(1)
try:
sh.ansible_galaxy('init', role)
except (CalledProcessError, sh.ErrorReturnCode_1) as e:
print('ERROR: {}'.format(e))
sys.exit(e.returncode)
env = Environment(loader=PackageLoader('molecule', 'templates'), keep_trailing_newline=True)
t_molecule = env.get_template(self._config['init']['templates']['molecule'])
t_playbook = env.get_template(self._config['init']['templates']['playbook'])
t_default_spec = env.get_template(self._config['init']['templates']['default_spec'])
t_spec_helper = env.get_template(self._config['init']['templates']['spec_helper'])
with open(role_path + self._config['molecule_file'], 'w') as f:
f.write(t_molecule.render(config=self._config))
with open(role_path + self._config['ansible']['playbook'], 'w') as f:
f.write(t_playbook.render(role=role))
serverspec_path = role_path + self._config['serverspec_dir'] + '/'
os.makedirs(serverspec_path)
os.makedirs(serverspec_path + 'hosts')
os.makedirs(serverspec_path + 'groups')
with open(serverspec_path + 'default_spec.rb', 'w') as f:
f.write(t_default_spec.render())
with open(serverspec_path + 'spec_helper.rb', 'w') as f:
f.write(t_spec_helper.render())
msg = '{}Successfully initialized new role in {}{}'
print(msg.format(Fore.GREEN, role_path, Fore.RESET))
sys.exit(0)
| 1 | 5,664 | Need to fix this import :) | ansible-community-molecule | py |
@@ -46,12 +46,14 @@ func TestBlockGenerator_GenerateBehavior(t *testing.T) {
Height: uint64(100),
StateRoot: newCid(),
}
+ accountActor := &types.Actor{Code: types.AccountActorCodeCid}
// With no messages.
nextStateRoot := newCid()
mpb, mst := &MockProcessBlock{}, &types.MockStateTree{}
mpb.On("ProcessBlock", context.Background(), mock.AnythingOfType("*types.Block"), mst).Return([]*types.MessageReceipt{}, nil)
mst.On("Flush", context.Background()).Return(nextStateRoot, nil)
+ mst.On("GetActor", context.Background(), mock.AnythingOfType("types.Address")).Return(accountActor, nil)
successfulGetStateTree := func(c context.Context, stateRootCid *cid.Cid) (types.StateTree, error) {
assert.True(stateRootCid.Equals(baseBlock.StateRoot))
return mst, nil | 1 | package mining
import (
"context"
"errors"
"testing"
"github.com/filecoin-project/go-filecoin/core"
"github.com/filecoin-project/go-filecoin/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
)
func TestGenerate(t *testing.T) {
// TODO fritz use core.FakeActor for state/contract tests for generate:
// - test nonces out of order
// - test nonce gap
// - test apply errors are skipped
}
type MockProcessBlock struct {
mock.Mock
}
func (mpb *MockProcessBlock) ProcessBlock(ctx context.Context, b *types.Block, st types.StateTree) (receipts []*types.MessageReceipt, err error) {
args := mpb.Called(ctx, b, st)
if args.Get(0) != nil {
receipts = args.Get(0).([]*types.MessageReceipt)
}
err = args.Error(1)
return
}
// TODO replace with contract-based testing (TestGenerate)
// when we have more nonce pieces in.
func TestBlockGenerator_GenerateBehavior(t *testing.T) {
assert := assert.New(t)
newCid := types.NewCidForTestGetter()
pool := core.NewMessagePool()
addr := types.NewAddressForTestGetter()()
baseBlock := types.Block{
Parent: newCid(),
Height: uint64(100),
StateRoot: newCid(),
}
// With no messages.
nextStateRoot := newCid()
mpb, mst := &MockProcessBlock{}, &types.MockStateTree{}
mpb.On("ProcessBlock", context.Background(), mock.AnythingOfType("*types.Block"), mst).Return([]*types.MessageReceipt{}, nil)
mst.On("Flush", context.Background()).Return(nextStateRoot, nil)
successfulGetStateTree := func(c context.Context, stateRootCid *cid.Cid) (types.StateTree, error) {
assert.True(stateRootCid.Equals(baseBlock.StateRoot))
return mst, nil
}
g := NewBlockGenerator(pool, successfulGetStateTree, mpb.ProcessBlock)
next, err := g.Generate(context.Background(), &baseBlock, addr)
assert.NoError(err)
assert.Equal(baseBlock.Cid(), next.Parent)
assert.Equal(nextStateRoot, next.StateRoot)
assert.Len(next.Messages, 1) // Block reward message is in there.
mpb.AssertExpectations(t)
mst.AssertExpectations(t)
// With messages.
mpb, mst = &MockProcessBlock{}, &types.MockStateTree{}
mpb.On("ProcessBlock", context.Background(), mock.AnythingOfType("*types.Block"), mst).Return([]*types.MessageReceipt{}, nil)
mst.On("Flush", context.Background()).Return(nextStateRoot, nil)
newMsg := types.NewMessageForTestGetter()
pool.Add(newMsg())
pool.Add(newMsg())
expectedMsgs := 2
require.Len(t, pool.Pending(), expectedMsgs)
g = NewBlockGenerator(pool, successfulGetStateTree, mpb.ProcessBlock)
next, err = g.Generate(context.Background(), &baseBlock, addr)
assert.NoError(err)
assert.Len(pool.Pending(), 2)
assert.Len(next.Messages, expectedMsgs+1) // Block reward message is in there too.
mpb.AssertExpectations(t)
mst.AssertExpectations(t)
// getStateTree fails.
mpb, mst = &MockProcessBlock{}, &types.MockStateTree{}
explodingGetStateTree := func(c context.Context, stateRootCid *cid.Cid) (types.StateTree, error) {
return nil, errors.New("boom getStateTree failed")
}
g = NewBlockGenerator(pool, explodingGetStateTree, mpb.ProcessBlock)
next, err = g.Generate(context.Background(), &baseBlock, addr)
if assert.Error(err) {
assert.Contains(err.Error(), "getStateTree")
}
assert.Nil(next)
mpb.AssertExpectations(t)
mst.AssertExpectations(t)
// processBlock fails.
mpb, mst = &MockProcessBlock{}, &types.MockStateTree{}
mpb.On("ProcessBlock", context.Background(), mock.AnythingOfType("*types.Block"), mst).Return(nil, errors.New("boom ProcessBlock failed"))
g = NewBlockGenerator(pool, successfulGetStateTree, mpb.ProcessBlock)
_, err = g.Generate(context.Background(), &baseBlock, addr)
if assert.Error(err) {
assert.Contains(err.Error(), "ProcessBlock")
}
mpb.AssertExpectations(t)
mst.AssertExpectations(t)
// tree.Flush fails.
mpb, mst = &MockProcessBlock{}, &types.MockStateTree{}
mpb.On("ProcessBlock", context.Background(), mock.AnythingOfType("*types.Block"), mst).Return([]*types.MessageReceipt{}, nil)
mst.On("Flush", context.Background()).Return(nil, errors.New("boom tree.Flush failed"))
g = NewBlockGenerator(pool, successfulGetStateTree, mpb.ProcessBlock)
_, err = g.Generate(context.Background(), &baseBlock, addr)
if assert.Error(err) {
assert.Contains(err.Error(), "Flush")
}
mpb.AssertExpectations(t)
mst.AssertExpectations(t)
}
| 1 | 11,730 | sorry these tests suck so much we are working to kill them | filecoin-project-venus | go |
@@ -701,7 +701,7 @@ import 'emby-ratingbutton';
const player = this;
currentRuntimeTicks = playbackManager.duration(player);
- updateTimeDisplay(playbackManager.currentTime(player), currentRuntimeTicks, playbackManager.getBufferedRanges(player));
+ updateTimeDisplay(playbackManager.currentTime(player) * 10000, currentRuntimeTicks, playbackManager.getBufferedRanges(player));
}
function releaseCurrentPlayer() { | 1 | import datetime from 'datetime';
import events from 'events';
import browser from 'browser';
import imageLoader from 'imageLoader';
import layoutManager from 'layoutManager';
import playbackManager from 'playbackManager';
import nowPlayingHelper from 'nowPlayingHelper';
import appHost from 'apphost';
import dom from 'dom';
import connectionManager from 'connectionManager';
import itemContextMenu from 'itemContextMenu';
import 'paper-icon-button-light';
import 'emby-ratingbutton';
/* eslint-disable indent */
let currentPlayer;
let currentPlayerSupportedCommands = [];
let currentTimeElement;
let nowPlayingImageElement;
let nowPlayingTextElement;
let nowPlayingUserData;
let muteButton;
let volumeSlider;
let volumeSliderContainer;
let playPauseButtons;
let positionSlider;
let toggleRepeatButton;
let toggleRepeatButtonIcon;
let lastUpdateTime = 0;
let lastPlayerState = {};
let isEnabled;
let currentRuntimeTicks = 0;
let isVisibilityAllowed = true;
function getNowPlayingBarHtml() {
let html = '';
html += '<div class="nowPlayingBar hide nowPlayingBar-hidden">';
html += '<div class="nowPlayingBarTop">';
html += '<div class="nowPlayingBarPositionContainer sliderContainer">';
html += '<input type="range" is="emby-slider" pin step=".01" min="0" max="100" value="0" class="slider-medium-thumb nowPlayingBarPositionSlider" data-slider-keep-progress="true"/>';
html += '</div>';
html += '<div class="nowPlayingBarInfoContainer">';
html += '<div class="nowPlayingImage"></div>';
html += '<div class="nowPlayingBarText"></div>';
html += '</div>';
// The onclicks are needed due to the return false above
html += '<div class="nowPlayingBarCenter">';
html += '<button is="paper-icon-button-light" class="previousTrackButton mediaButton"><span class="material-icons skip_previous"></span></button>';
html += '<button is="paper-icon-button-light" class="playPauseButton mediaButton"><span class="material-icons pause"></span></button>';
html += '<button is="paper-icon-button-light" class="stopButton mediaButton"><span class="material-icons stop"></span></button>';
if (!layoutManager.mobile) {
html += '<button is="paper-icon-button-light" class="nextTrackButton mediaButton"><span class="material-icons skip_next"></span></button>';
}
html += '<div class="nowPlayingBarCurrentTime"></div>';
html += '</div>';
html += '<div class="nowPlayingBarRight">';
html += '<button is="paper-icon-button-light" class="muteButton mediaButton"><span class="material-icons volume_up"></span></button>';
html += '<div class="sliderContainer nowPlayingBarVolumeSliderContainer hide" style="width:9em;vertical-align:middle;display:inline-flex;">';
html += '<input type="range" is="emby-slider" pin step="1" min="0" max="100" value="0" class="slider-medium-thumb nowPlayingBarVolumeSlider"/>';
html += '</div>';
html += '<button is="paper-icon-button-light" class="toggleRepeatButton mediaButton"><span class="material-icons repeat"></span></button>';
html += '<button is="paper-icon-button-light" class="btnShuffleQueue mediaButton"><span class="material-icons shuffle"></span></button>';
html += '<div class="nowPlayingBarUserDataButtons">';
html += '</div>';
html += '<button is="paper-icon-button-light" class="playPauseButton mediaButton"><span class="material-icons pause"></span></button>';
if (layoutManager.mobile) {
html += '<button is="paper-icon-button-light" class="nextTrackButton mediaButton"><span class="material-icons skip_next"></span></button>';
} else {
html += '<button is="paper-icon-button-light" class="btnToggleContextMenu mediaButton"><span class="material-icons more_vert"></span></button>';
}
html += '</div>';
html += '</div>';
html += '</div>';
return html;
}
function onSlideDownComplete() {
this.classList.add('hide');
}
function slideDown(elem) {
// trigger reflow
void elem.offsetWidth;
elem.classList.add('nowPlayingBar-hidden');
dom.addEventListener(elem, dom.whichTransitionEvent(), onSlideDownComplete, {
once: true
});
}
function slideUp(elem) {
dom.removeEventListener(elem, dom.whichTransitionEvent(), onSlideDownComplete, {
once: true
});
elem.classList.remove('hide');
// trigger reflow
void elem.offsetWidth;
elem.classList.remove('nowPlayingBar-hidden');
}
function onPlayPauseClick() {
playbackManager.playPause(currentPlayer);
}
function bindEvents(elem) {
currentTimeElement = elem.querySelector('.nowPlayingBarCurrentTime');
nowPlayingImageElement = elem.querySelector('.nowPlayingImage');
nowPlayingTextElement = elem.querySelector('.nowPlayingBarText');
nowPlayingUserData = elem.querySelector('.nowPlayingBarUserDataButtons');
positionSlider = elem.querySelector('.nowPlayingBarPositionSlider');
muteButton = elem.querySelector('.muteButton');
playPauseButtons = elem.querySelectorAll('.playPauseButton');
toggleRepeatButton = elem.querySelector('.toggleRepeatButton');
volumeSlider = elem.querySelector('.nowPlayingBarVolumeSlider');
volumeSliderContainer = elem.querySelector('.nowPlayingBarVolumeSliderContainer');
muteButton.addEventListener('click', function () {
if (currentPlayer) {
playbackManager.toggleMute(currentPlayer);
}
});
elem.querySelector('.stopButton').addEventListener('click', function () {
if (currentPlayer) {
playbackManager.stop(currentPlayer);
}
});
playPauseButtons.forEach((button) => {
button.addEventListener('click', onPlayPauseClick);
});
elem.querySelector('.nextTrackButton').addEventListener('click', function () {
if (currentPlayer) {
playbackManager.nextTrack(currentPlayer);
}
});
elem.querySelector('.previousTrackButton').addEventListener('click', function (e) {
if (currentPlayer) {
if (lastPlayerState.NowPlayingItem.MediaType === 'Audio' && (currentPlayer._currentTime >= 5 || !playbackManager.previousTrack(currentPlayer))) {
// Cancel this event if doubleclick is fired
if (e.detail > 1 && playbackManager.previousTrack(currentPlayer)) {
return;
}
playbackManager.seekPercent(0, currentPlayer);
// This is done automatically by playbackManager, however, setting this here gives instant visual feedback.
// TODO: Check why seekPercentage doesn't reflect the changes inmmediately, so we can remove this workaround.
positionSlider.value = 0;
} else {
playbackManager.previousTrack(currentPlayer);
}
}
});
elem.querySelector('.previousTrackButton').addEventListener('dblclick', function () {
if (currentPlayer) {
playbackManager.previousTrack(currentPlayer);
}
});
elem.querySelector('.btnShuffleQueue').addEventListener('click', function () {
if (currentPlayer) {
playbackManager.toggleQueueShuffleMode();
}
});
toggleRepeatButton = elem.querySelector('.toggleRepeatButton');
toggleRepeatButton.addEventListener('click', function () {
switch (playbackManager.getRepeatMode()) {
case 'RepeatAll':
playbackManager.setRepeatMode('RepeatOne');
break;
case 'RepeatOne':
playbackManager.setRepeatMode('RepeatNone');
break;
case 'RepeatNone':
playbackManager.setRepeatMode('RepeatAll');
}
});
toggleRepeatButtonIcon = toggleRepeatButton.querySelector('.material-icons');
volumeSliderContainer.classList.toggle('hide', appHost.supports('physicalvolumecontrol'));
volumeSlider.addEventListener('input', (e) => {
if (currentPlayer) {
currentPlayer.setVolume(e.target.value);
}
});
positionSlider.addEventListener('change', function () {
if (currentPlayer) {
const newPercent = parseFloat(this.value);
playbackManager.seekPercent(newPercent, currentPlayer);
}
});
positionSlider.getBubbleText = function (value) {
const state = lastPlayerState;
if (!state || !state.NowPlayingItem || !currentRuntimeTicks) {
return '--:--';
}
let ticks = currentRuntimeTicks;
ticks /= 100;
ticks *= value;
return datetime.getDisplayRunningTime(ticks);
};
elem.addEventListener('click', function (e) {
if (!dom.parentWithTag(e.target, ['BUTTON', 'INPUT'])) {
showRemoteControl();
}
});
}
function showRemoteControl() {
import('appRouter').then(({default: appRouter}) => {
appRouter.showNowPlaying();
});
}
let nowPlayingBarElement;
function getNowPlayingBar() {
if (nowPlayingBarElement) {
return Promise.resolve(nowPlayingBarElement);
}
return new Promise(function (resolve, reject) {
Promise.all([
import('appFooter-shared'),
import('itemShortcuts'),
import('css!./nowPlayingBar.css'),
import('emby-slider')
])
.then(([appfooter, itemShortcuts]) => {
const parentContainer = appfooter.element;
nowPlayingBarElement = parentContainer.querySelector('.nowPlayingBar');
if (nowPlayingBarElement) {
resolve(nowPlayingBarElement);
return;
}
parentContainer.insertAdjacentHTML('afterbegin', getNowPlayingBarHtml());
nowPlayingBarElement = parentContainer.querySelector('.nowPlayingBar');
if (layoutManager.mobile) {
hideButton(nowPlayingBarElement.querySelector('.btnShuffleQueue'));
hideButton(nowPlayingBarElement.querySelector('.nowPlayingBarCenter'));
}
if (browser.safari && browser.slow) {
// Not handled well here. The wrong elements receive events, bar doesn't update quickly enough, etc.
nowPlayingBarElement.classList.add('noMediaProgress');
}
itemShortcuts.on(nowPlayingBarElement);
bindEvents(nowPlayingBarElement);
resolve(nowPlayingBarElement);
});
});
}
function showButton(button) {
button.classList.remove('hide');
}
function hideButton(button) {
button.classList.add('hide');
}
function updatePlayPauseState(isPaused) {
if (playPauseButtons) {
playPauseButtons.forEach((button) => {
const icon = button.querySelector('.material-icons');
icon.classList.remove('play_arrow', 'pause');
icon.classList.add(isPaused ? 'play_arrow' : 'pause');
});
}
}
function updatePlayerStateInternal(event, state, player) {
showNowPlayingBar();
lastPlayerState = state;
const playerInfo = playbackManager.getPlayerInfo();
const playState = state.PlayState || {};
updatePlayPauseState(playState.IsPaused);
const supportedCommands = playerInfo.supportedCommands;
currentPlayerSupportedCommands = supportedCommands;
if (supportedCommands.indexOf('SetRepeatMode') === -1) {
toggleRepeatButton.classList.add('hide');
} else {
toggleRepeatButton.classList.remove('hide');
}
updateRepeatModeDisplay(playbackManager.getRepeatMode());
onQueueShuffleModeChange();
updatePlayerVolumeState(playState.IsMuted, playState.VolumeLevel);
if (positionSlider && !positionSlider.dragging) {
positionSlider.disabled = !playState.CanSeek;
// determines if both forward and backward buffer progress will be visible
const isProgressClear = state.MediaSource && state.MediaSource.RunTimeTicks == null;
positionSlider.setIsClear(isProgressClear);
}
const nowPlayingItem = state.NowPlayingItem || {};
updateTimeDisplay(playState.PositionTicks, nowPlayingItem.RunTimeTicks, playbackManager.getBufferedRanges(player));
updateNowPlayingInfo(state);
}
function updateRepeatModeDisplay(repeatMode) {
toggleRepeatButtonIcon.classList.remove('repeat', 'repeat_one');
const cssClass = 'buttonActive';
switch (repeatMode) {
case 'RepeatAll':
toggleRepeatButtonIcon.classList.add('repeat');
toggleRepeatButton.classList.add(cssClass);
break;
case 'RepeatOne':
toggleRepeatButtonIcon.classList.add('repeat_one');
toggleRepeatButton.classList.add(cssClass);
break;
case 'RepeatNone':
default:
toggleRepeatButtonIcon.classList.add('repeat');
toggleRepeatButton.classList.remove(cssClass);
break;
}
}
function updateTimeDisplay(positionTicks, runtimeTicks, bufferedRanges) {
// See bindEvents for why this is necessary
if (positionSlider && !positionSlider.dragging) {
if (runtimeTicks) {
let pct = positionTicks / runtimeTicks;
pct *= 100;
positionSlider.value = pct;
} else {
positionSlider.value = 0;
}
}
if (positionSlider) {
positionSlider.setBufferedRanges(bufferedRanges, runtimeTicks, positionTicks);
}
if (currentTimeElement) {
let timeText = positionTicks == null ? '--:--' : datetime.getDisplayRunningTime(positionTicks);
if (runtimeTicks) {
timeText += ' / ' + datetime.getDisplayRunningTime(runtimeTicks);
}
currentTimeElement.innerHTML = timeText;
}
}
function updatePlayerVolumeState(isMuted, volumeLevel) {
const supportedCommands = currentPlayerSupportedCommands;
let showMuteButton = true;
let showVolumeSlider = true;
if (supportedCommands.indexOf('ToggleMute') === -1) {
showMuteButton = false;
}
const muteButtonIcon = muteButton.querySelector('.material-icons');
muteButtonIcon.classList.remove('volume_off', 'volume_up');
muteButtonIcon.classList.add(isMuted ? 'volume_off' : 'volume_up');
if (supportedCommands.indexOf('SetVolume') === -1) {
showVolumeSlider = false;
}
if (currentPlayer.isLocalPlayer && appHost.supports('physicalvolumecontrol')) {
showMuteButton = false;
showVolumeSlider = false;
}
if (showMuteButton) {
showButton(muteButton);
} else {
hideButton(muteButton);
}
// See bindEvents for why this is necessary
if (volumeSlider) {
volumeSliderContainer.classList.toggle('hide', !showVolumeSlider);
if (!volumeSlider.dragging) {
volumeSlider.value = volumeLevel || 0;
}
}
}
function seriesImageUrl(item, options) {
if (!item) {
throw new Error('item cannot be null!');
}
if (item.Type !== 'Episode') {
return null;
}
options = options || {};
options.type = options.type || 'Primary';
if (options.type === 'Primary') {
if (item.SeriesPrimaryImageTag) {
options.tag = item.SeriesPrimaryImageTag;
return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options);
}
}
if (options.type === 'Thumb') {
if (item.SeriesThumbImageTag) {
options.tag = item.SeriesThumbImageTag;
return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options);
}
if (item.ParentThumbImageTag) {
options.tag = item.ParentThumbImageTag;
return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId, options);
}
}
return null;
}
function imageUrl(item, options) {
if (!item) {
throw new Error('item cannot be null!');
}
options = options || {};
options.type = options.type || 'Primary';
if (item.ImageTags && item.ImageTags[options.type]) {
options.tag = item.ImageTags[options.type];
return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId || item.Id, options);
}
if (item.AlbumId && item.AlbumPrimaryImageTag) {
options.tag = item.AlbumPrimaryImageTag;
return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId, options);
}
return null;
}
let currentImgUrl;
function updateNowPlayingInfo(state) {
const nowPlayingItem = state.NowPlayingItem;
const textLines = nowPlayingItem ? nowPlayingHelper.getNowPlayingNames(nowPlayingItem) : [];
nowPlayingTextElement.innerHTML = '';
if (textLines) {
const itemText = document.createElement('div');
const secondaryText = document.createElement('div');
secondaryText.classList.add('nowPlayingBarSecondaryText');
if (textLines.length > 1) {
textLines[1].secondary = true;
if (textLines[1].text) {
const text = document.createElement('a');
text.innerHTML = textLines[1].text;
secondaryText.appendChild(text);
}
}
if (textLines[0].text) {
const text = document.createElement('a');
text.innerHTML = textLines[0].text;
itemText.appendChild(text);
}
nowPlayingTextElement.appendChild(itemText);
nowPlayingTextElement.appendChild(secondaryText);
}
const imgHeight = 70;
const url = nowPlayingItem ? (seriesImageUrl(nowPlayingItem, {
height: imgHeight
}) || imageUrl(nowPlayingItem, {
height: imgHeight
})) : null;
let isRefreshing = false;
if (url !== currentImgUrl) {
currentImgUrl = url;
isRefreshing = true;
if (url) {
imageLoader.lazyImage(nowPlayingImageElement, url);
nowPlayingImageElement.style.display = null;
nowPlayingTextElement.style.marginLeft = null;
} else {
nowPlayingImageElement.style.backgroundImage = '';
nowPlayingImageElement.style.display = 'none';
nowPlayingTextElement.style.marginLeft = '1em';
}
}
if (nowPlayingItem.Id) {
if (isRefreshing) {
const apiClient = connectionManager.getApiClient(nowPlayingItem.ServerId);
apiClient.getItem(apiClient.getCurrentUserId(), nowPlayingItem.Id).then(function (item) {
const userData = item.UserData || {};
const likes = userData.Likes == null ? '' : userData.Likes;
if (!layoutManager.mobile) {
let contextButton = nowPlayingBarElement.querySelector('.btnToggleContextMenu');
// We remove the previous event listener by replacing the item in each update event
const contextButtonClone = contextButton.cloneNode(true);
contextButton.parentNode.replaceChild(contextButtonClone, contextButton);
contextButton = nowPlayingBarElement.querySelector('.btnToggleContextMenu');
const options = {
play: false,
queue: false,
clearQueue: true,
positionTo: contextButton
};
apiClient.getCurrentUser().then(function (user) {
contextButton.addEventListener('click', function () {
itemContextMenu.show(Object.assign({
item: item,
user: user
}, options));
});
});
}
nowPlayingUserData.innerHTML = '<button is="emby-ratingbutton" type="button" class="listItemButton mediaButton paper-icon-button-light" data-id="' + item.Id + '" data-serverid="' + item.ServerId + '" data-itemtype="' + item.Type + '" data-likes="' + likes + '" data-isfavorite="' + (userData.IsFavorite) + '"><span class="material-icons favorite"></span></button>';
});
}
} else {
nowPlayingUserData.innerHTML = '';
}
}
function onPlaybackStart(e, state) {
console.debug('nowplaying event: ' + e.type);
var player = this;
onStateChanged.call(player, e, state);
}
function onRepeatModeChange() {
if (!isEnabled) {
return;
}
updateRepeatModeDisplay(playbackManager.getRepeatMode());
}
function onQueueShuffleModeChange() {
if (!isEnabled) {
return;
}
const shuffleMode = playbackManager.getQueueShuffleMode();
const context = nowPlayingBarElement;
const cssClass = 'buttonActive';
const toggleShuffleButton = context.querySelector('.btnShuffleQueue');
switch (shuffleMode) {
case 'Shuffle':
toggleShuffleButton.classList.add(cssClass);
break;
case 'Sorted':
default:
toggleShuffleButton.classList.remove(cssClass);
break;
}
}
function showNowPlayingBar() {
if (!isVisibilityAllowed) {
hideNowPlayingBar();
return;
}
getNowPlayingBar().then(slideUp);
}
function hideNowPlayingBar() {
isEnabled = false;
// Use a timeout to prevent the bar from hiding and showing quickly
// in the event of a stop->play command
// Don't call getNowPlayingBar here because we don't want to end up creating it just to hide it
const elem = document.getElementsByClassName('nowPlayingBar')[0];
if (elem) {
slideDown(elem);
}
}
function onPlaybackStopped(e, state) {
console.debug('nowplaying event: ' + e.type);
const player = this;
if (player.isLocalPlayer) {
if (state.NextMediaType !== 'Audio') {
hideNowPlayingBar();
}
} else {
if (!state.NextMediaType) {
hideNowPlayingBar();
}
}
}
function onPlayPauseStateChanged(e) {
if (!isEnabled) {
return;
}
const player = this;
updatePlayPauseState(player.paused());
}
function onStateChanged(event, state) {
console.debug('nowplaying event: ' + event.type);
const player = this;
if (!state.NowPlayingItem || layoutManager.tv) {
hideNowPlayingBar();
return;
}
if (player.isLocalPlayer && state.NowPlayingItem && state.NowPlayingItem.MediaType === 'Video') {
hideNowPlayingBar();
return;
}
isEnabled = true;
if (nowPlayingBarElement) {
updatePlayerStateInternal(event, state, player);
return;
}
getNowPlayingBar().then(function () {
updatePlayerStateInternal(event, state, player);
});
}
function onTimeUpdate(e) {
if (!isEnabled) {
return;
}
// Try to avoid hammering the document with changes
const now = new Date().getTime();
if ((now - lastUpdateTime) < 700) {
return;
}
lastUpdateTime = now;
const player = this;
currentRuntimeTicks = playbackManager.duration(player);
updateTimeDisplay(playbackManager.currentTime(player), currentRuntimeTicks, playbackManager.getBufferedRanges(player));
}
function releaseCurrentPlayer() {
const player = currentPlayer;
if (player) {
events.off(player, 'playbackstart', onPlaybackStart);
events.off(player, 'statechange', onPlaybackStart);
events.off(player, 'repeatmodechange', onRepeatModeChange);
events.off(player, 'shufflequeuemodechange', onQueueShuffleModeChange);
events.off(player, 'playbackstop', onPlaybackStopped);
events.off(player, 'volumechange', onVolumeChanged);
events.off(player, 'pause', onPlayPauseStateChanged);
events.off(player, 'unpause', onPlayPauseStateChanged);
events.off(player, 'timeupdate', onTimeUpdate);
currentPlayer = null;
hideNowPlayingBar();
}
}
function onVolumeChanged(e) {
if (!isEnabled) {
return;
}
const player = this;
updatePlayerVolumeState(player.isMuted(), player.getVolume());
}
function refreshFromPlayer(player) {
const state = playbackManager.getPlayerState(player);
onStateChanged.call(player, { type: 'init' }, state);
}
function bindToPlayer(player) {
if (player === currentPlayer) {
return;
}
releaseCurrentPlayer();
currentPlayer = player;
if (!player) {
return;
}
refreshFromPlayer(player);
events.on(player, 'playbackstart', onPlaybackStart);
events.on(player, 'statechange', onPlaybackStart);
events.on(player, 'repeatmodechange', onRepeatModeChange);
events.on(player, 'shufflequeuemodechange', onQueueShuffleModeChange);
events.on(player, 'playbackstop', onPlaybackStopped);
events.on(player, 'volumechange', onVolumeChanged);
events.on(player, 'pause', onPlayPauseStateChanged);
events.on(player, 'unpause', onPlayPauseStateChanged);
events.on(player, 'timeupdate', onTimeUpdate);
}
events.on(playbackManager, 'playerchange', function () {
bindToPlayer(playbackManager.getCurrentPlayer());
});
bindToPlayer(playbackManager.getCurrentPlayer());
document.addEventListener('viewbeforeshow', function (e) {
if (!e.detail.options.enableMediaControl) {
if (isVisibilityAllowed) {
isVisibilityAllowed = false;
hideNowPlayingBar();
}
} else if (!isVisibilityAllowed) {
isVisibilityAllowed = true;
if (currentPlayer) {
refreshFromPlayer(currentPlayer);
} else {
hideNowPlayingBar();
}
}
});
/* eslint-enable indent */
| 1 | 17,367 | Why not adjust `currentTime` to be in ms directly? | jellyfin-jellyfin-web | js |
@@ -3697,7 +3697,8 @@ instr_is_reg_spill_or_restore_ex(void *drcontext, instr_t *instr, bool DR_only,
if (reg == NULL)
reg = &myreg;
if (instr_check_tls_spill_restore(instr, spill, reg, &check_disp)) {
- if (!DR_only ||
+ /* We do not want to count an mcontext base load as a reg spill/restore. */
+ if ((!DR_only && check_disp != os_tls_offset((ushort)TLS_DCONTEXT_SLOT)) ||
(reg_spill_tls_offs(*reg) != -1 &&
/* Mangling may choose to spill registers to a not natural tls offset,
* e.g. rip-rel mangling will, if rax is used by the instruction. We | 1 | /* **********************************************************
* Copyright (c) 2011-2021 Google, Inc. All rights reserved.
* Copyright (c) 2000-2010 VMware, Inc. 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 VMware, Inc. 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 VMWARE, INC. 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.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/* Copyright (c) 2001-2003 Massachusetts Institute of Technology */
/* Copyright (c) 2000-2001 Hewlett-Packard Company */
/* file "instr_shared.c" -- IR instr_t utilities */
/* We need to provide at least one out-of-line definition for our inline
* functions in instr_inline.h in case they are all inlined away within DR.
*
* For gcc, we use -std=gnu99, which uses the C99 inlining model. Using "extern
* inline" will provide a definition, but we can only do this in one C file.
* Elsewhere we use plain "inline", which will not emit an out of line
* definition if inlining fails.
*
* MSVC always emits link_once definitions for dllexported inline functions, so
* this macro magic is unnecessary.
* http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
*/
#define INSTR_INLINE extern inline
#include "../globals.h"
#include "instr.h"
#include "arch.h"
#include "../link.h"
#include "decode.h"
#include "decode_fast.h"
#include "instr_create_shared.h"
/* FIXME i#1551: refactor this file and avoid this x86-specific include in base arch/ */
#include "x86/decode_private.h"
#ifdef DEBUG
# include "disassemble.h"
#endif
#ifdef VMX86_SERVER
# include "vmkuw.h" /* VMKUW_SYSCALL_GATEWAY */
#endif
#if defined(DEBUG) && !defined(STANDALONE_DECODER)
/* case 10450: give messages to clients */
/* we can't undef ASSERT b/c of DYNAMO_OPTION */
# undef ASSERT_TRUNCATE
# undef ASSERT_BITFIELD_TRUNCATE
# undef ASSERT_NOT_REACHED
# define ASSERT_TRUNCATE DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
# define ASSERT_BITFIELD_TRUNCATE DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
# define ASSERT_NOT_REACHED DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
#endif
/* returns an empty instr_t object */
instr_t *
instr_create(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *instr = (instr_t *)heap_alloc(dcontext, sizeof(instr_t) HEAPACCT(ACCT_IR));
/* everything initializes to 0, even flags, to indicate
* an uninitialized instruction */
memset((void *)instr, 0, sizeof(instr_t));
#if defined(X86) && defined(X64)
instr_set_isa_mode(instr, X64_CACHE_MODE_DC(dcontext) ? DR_ISA_AMD64 : DR_ISA_IA32);
#elif defined(ARM)
instr_set_isa_mode(instr, dr_get_isa_mode(dcontext));
#endif
return instr;
}
/* deletes the instr_t object with handle "instr" and frees its storage */
void
instr_destroy(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
#ifdef ARM
/* i#4680: Reset encode state to avoid dangling pointers. This doesn't cover
* auto-scope instr_t vars so the whole IT tracking is still fragile.
*/
if (instr_get_isa_mode(instr) == DR_ISA_ARM_THUMB)
encode_instr_freed_event(dcontext, instr);
#endif
instr_free(dcontext, instr);
/* CAUTION: assumes that instr is not part of any instrlist */
heap_free(dcontext, instr, sizeof(instr_t) HEAPACCT(ACCT_IR));
}
/* returns a clone of orig, but with next and prev fields set to NULL */
instr_t *
instr_clone(void *drcontext, instr_t *orig)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
/* We could heap-allocate an instr_noalloc_t but it's intended for use in a
* signal handler or other places where we don't want any heap allocation.
*/
CLIENT_ASSERT(!TEST(INSTR_IS_NOALLOC_STRUCT, orig->flags),
"Cloning an instr_noalloc_t is not supported.");
instr_t *instr = (instr_t *)heap_alloc(dcontext, sizeof(instr_t) HEAPACCT(ACCT_IR));
memcpy((void *)instr, (void *)orig, sizeof(instr_t));
instr->next = NULL;
instr->prev = NULL;
/* PR 214962: clients can see some of our mangling
* (dr_insert_mbr_instrumentation(), traces), but don't let the flag
* mark other client instrs, which could mess up state translation
*/
instr_set_our_mangling(instr, false);
if ((orig->flags & INSTR_RAW_BITS_ALLOCATED) != 0) {
/* instr length already set from memcpy */
instr->bytes =
(byte *)heap_reachable_alloc(dcontext, instr->length HEAPACCT(ACCT_IR));
memcpy((void *)instr->bytes, (void *)orig->bytes, instr->length);
} else if (instr_is_label(orig) && instr_get_label_callback(instr) != NULL) {
/* We don't know what this callback does, we can't copy this. The caller that
* makes the clone needs to take care of this, xref i#3926.
*/
instr_clear_label_callback(instr);
}
if (orig->num_dsts > 0) { /* checking num_dsts, not dsts, b/c of label data */
instr->dsts = (opnd_t *)heap_alloc(
dcontext, instr->num_dsts * sizeof(opnd_t) HEAPACCT(ACCT_IR));
memcpy((void *)instr->dsts, (void *)orig->dsts, instr->num_dsts * sizeof(opnd_t));
}
if (orig->num_srcs > 1) { /* checking num_src, not srcs, b/c of label data */
instr->srcs = (opnd_t *)heap_alloc(
dcontext, (instr->num_srcs - 1) * sizeof(opnd_t) HEAPACCT(ACCT_IR));
memcpy((void *)instr->srcs, (void *)orig->srcs,
(instr->num_srcs - 1) * sizeof(opnd_t));
}
/* copy note (we make no guarantee, and have no way, to do a deep clone) */
instr->note = orig->note;
if (instr_is_label(orig))
memcpy(&instr->label_data, &orig->label_data, sizeof(instr->label_data));
return instr;
}
/* zeroes out the fields of instr */
void
instr_init(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
/* everything initializes to 0, even flags, to indicate
* an uninitialized instruction */
memset((void *)instr, 0, sizeof(instr_t));
instr_set_isa_mode(instr, dr_get_isa_mode(dcontext));
}
/* zeroes out the fields of instr */
void
instr_noalloc_init(void *drcontext, instr_noalloc_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
memset(instr, 0, sizeof(*instr));
instr->instr.flags |= INSTR_IS_NOALLOC_STRUCT;
instr_set_isa_mode(&instr->instr, dr_get_isa_mode(dcontext));
}
/* Frees all dynamically allocated storage that was allocated by instr */
void
instr_free(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
if (instr_is_label(instr) && instr_get_label_callback(instr) != NULL)
(*instr->label_cb)(dcontext, instr);
if (TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags))
return;
if (TEST(INSTR_RAW_BITS_ALLOCATED, instr->flags)) {
instr_free_raw_bits(dcontext, instr);
}
if (instr->num_dsts > 0) { /* checking num_dsts, not dsts, b/c of label data */
heap_free(dcontext, instr->dsts,
instr->num_dsts * sizeof(opnd_t) HEAPACCT(ACCT_IR));
instr->dsts = NULL;
instr->num_dsts = 0;
}
if (instr->num_srcs > 1) { /* checking num_src, not src, b/c of label data */
/* remember one src is static, rest are dynamic */
heap_free(dcontext, instr->srcs,
(instr->num_srcs - 1) * sizeof(opnd_t) HEAPACCT(ACCT_IR));
instr->srcs = NULL;
instr->num_srcs = 0;
}
}
int
instr_mem_usage(instr_t *instr)
{
if (TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags))
return sizeof(instr_noalloc_t);
int usage = 0;
if ((instr->flags & INSTR_RAW_BITS_ALLOCATED) != 0) {
usage += instr->length;
}
if (instr->dsts != NULL) {
usage += instr->num_dsts * sizeof(opnd_t);
}
if (instr->srcs != NULL) {
/* remember one src is static, rest are dynamic */
usage += (instr->num_srcs - 1) * sizeof(opnd_t);
}
usage += sizeof(instr_t);
return usage;
}
/* Frees all dynamically allocated storage that was allocated by instr
* Also zeroes out instr's fields
* This instr must have been initialized before!
*/
void
instr_reset(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_free(dcontext, instr);
if (TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags)) {
instr_init(dcontext, instr);
instr->flags |= INSTR_IS_NOALLOC_STRUCT;
} else {
instr_init(dcontext, instr);
}
}
/* Frees all dynamically allocated storage that was allocated by instr,
* except for allocated raw bits.
* Also zeroes out instr's fields, except for raw bit fields and next and prev
* fields, whether instr is ok to mangle, and instr's x86 mode.
* Use this routine when you want to decode more information into the
* same instr_t structure.
* This instr must have been initialized before!
*/
void
instr_reuse(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
byte *bits = NULL;
uint len = 0;
bool alloc = false;
bool mangle = instr_is_app(instr);
dr_isa_mode_t isa_mode = instr_get_isa_mode(instr);
#ifdef X86
uint rip_rel_pos = instr_rip_rel_valid(instr) ? instr->rip_rel_pos : 0;
#endif
instr_t *next = instr->next;
instr_t *prev = instr->prev;
if (instr_raw_bits_valid(instr)) {
if (instr_has_allocated_bits(instr)) {
/* pretend has no allocated bits to prevent freeing of them */
instr->flags &= ~INSTR_RAW_BITS_ALLOCATED;
alloc = true;
}
bits = instr->bytes;
len = instr->length;
}
instr_free(dcontext, instr);
instr_init(dcontext, instr);
/* now re-add them */
instr->next = next;
instr->prev = prev;
if (bits != NULL) {
instr->bytes = bits;
instr->length = len;
/* assume that the bits are now valid and the operands are not
* (operand and eflags flags are already unset from init)
*/
instr->flags |= INSTR_RAW_BITS_VALID;
if (alloc)
instr->flags |= INSTR_RAW_BITS_ALLOCATED;
}
/* preserve across the up-decode */
instr_set_isa_mode(instr, isa_mode);
#ifdef X86
if (rip_rel_pos > 0)
instr_set_rip_rel_pos(instr, rip_rel_pos);
#endif
if (!mangle)
instr->flags |= INSTR_DO_NOT_MANGLE;
}
instr_t *
instr_build(void *drcontext, int opcode, int instr_num_dsts, int instr_num_srcs)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *instr = instr_create(dcontext);
instr_set_opcode(instr, opcode);
instr_set_num_opnds(dcontext, instr, instr_num_dsts, instr_num_srcs);
return instr;
}
instr_t *
instr_build_bits(void *drcontext, int opcode, uint num_bytes)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *instr = instr_create(dcontext);
instr_set_opcode(instr, opcode);
instr_allocate_raw_bits(dcontext, instr, num_bytes);
return instr;
}
/* encodes to buffer, then returns length.
* needed for things we must have encoding for: length and eflags.
* if !always_cache, only caches the encoding if instr_is_app();
* if always_cache, the caller should invalidate the cache when done.
*/
static int
private_instr_encode(dcontext_t *dcontext, instr_t *instr, bool always_cache)
{
byte *buf;
byte stack_buf[MAX_INSTR_LENGTH];
if (TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags)) {
/* We have no choice: we live with no persistent caching if the stack is
* too far away, because the instr's raw bits will be on the stack.
* (We can't use encode_buf here bc the re-rel below does not support
* the same buffer; maybe it could w/ a memmove in the encode code?)
*/
buf = stack_buf;
} else {
/* We cannot efficiently use a stack buffer for encoding since our stack on x64
* linux can be too far to reach from our heap. We need reachable heap.
* Otherwise we can't keep the encoding around since re-relativization won't
* work.
*/
buf = heap_reachable_alloc(dcontext, MAX_INSTR_LENGTH HEAPACCT(ACCT_IR));
}
uint len;
/* Do not cache instr opnds as they are pc-relative to final encoding location.
* Rather than us walking all of the operands separately here, we have
* instr_encode_check_reachability tell us while it does its normal walk.
* Xref i#731.
*/
bool has_instr_opnds;
byte *nxt = instr_encode_check_reachability(dcontext, instr, buf, &has_instr_opnds);
bool valid_to_cache = !has_instr_opnds;
if (nxt == NULL) {
nxt = instr_encode_ignore_reachability(dcontext, instr, buf);
if (nxt == NULL) {
SYSLOG_INTERNAL_WARNING("cannot encode %s",
opcode_to_encoding_info(instr->opcode,
instr_get_isa_mode(instr)
_IF_ARM(false))
->name);
if (!TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags))
heap_reachable_free(dcontext, buf, MAX_INSTR_LENGTH HEAPACCT(ACCT_IR));
return 0;
}
/* if unreachable, we can't cache, since re-relativization won't work */
valid_to_cache = false;
}
len = (int)(nxt - buf);
CLIENT_ASSERT(len > 0 || instr_is_label(instr),
"encode instr for length/eflags error: zero length");
CLIENT_ASSERT(len <= MAX_INSTR_LENGTH,
"encode instr for length/eflags error: instr too long");
/* do not cache encoding if mangle is false, that way we can have
* non-cti-instructions that are pc-relative.
* we also cannot cache if a rip-relative operand is unreachable.
* we can cache if a rip-relative operand is present b/c instr_encode()
* sets instr_set_rip_rel_pos() for us.
*/
if (len > 0 &&
((valid_to_cache && instr_is_app(instr)) ||
always_cache /*caller will use then invalidate*/)) {
bool valid = instr_operands_valid(instr);
#ifdef X86
/* we can't call instr_rip_rel_valid() b/c the raw bytes are not yet
* set up: we rely on instr_encode() setting instr->rip_rel_pos and
* the valid flag, even though raw bytes weren't there at the time.
* we rely on the INSTR_RIP_REL_VALID flag being invalidated whenever
* the raw bits are.
*/
bool rip_rel_valid = TEST(INSTR_RIP_REL_VALID, instr->flags);
#endif
byte *tmp;
CLIENT_ASSERT(!instr_raw_bits_valid(instr),
"encode instr: bit validity error"); /* else shouldn't get here */
instr_allocate_raw_bits(dcontext, instr, len);
/* we use a hack in order to take advantage of
* copy_and_re_relativize_raw_instr(), which copies from instr->bytes
* using rip-rel-calculating routines that also use instr->bytes.
*/
tmp = instr->bytes;
instr->bytes = buf;
#ifdef X86
instr_set_rip_rel_valid(instr, rip_rel_valid);
#endif
copy_and_re_relativize_raw_instr(dcontext, instr, tmp, tmp);
instr->bytes = tmp;
instr_set_operands_valid(instr, valid);
}
if (!TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags))
heap_reachable_free(dcontext, buf, MAX_INSTR_LENGTH HEAPACCT(ACCT_IR));
return len;
}
#define inlined_instr_get_opcode(instr) \
(IF_DEBUG_(CLIENT_ASSERT(sizeof(*instr) == sizeof(instr_t), "invalid type"))( \
((instr)->opcode == OP_UNDECODED) \
? (instr_decode_with_current_dcontext(instr), (instr)->opcode) \
: (instr)->opcode))
int
instr_get_opcode(instr_t *instr)
{
return inlined_instr_get_opcode(instr);
}
/* in rest of file, directly de-reference for performance (PR 622253) */
#define instr_get_opcode inlined_instr_get_opcode
static inline void
instr_being_modified(instr_t *instr, bool raw_bits_valid)
{
if (!raw_bits_valid) {
/* if we're modifying the instr, don't use original bits to encode! */
instr_set_raw_bits_valid(instr, false);
}
/* PR 214962: if client changes our mangling, un-mark to avoid bad translation */
instr_set_our_mangling(instr, false);
}
void
instr_set_opcode(instr_t *instr, int opcode)
{
instr->opcode = opcode;
/* if we're modifying opcode, don't use original bits to encode! */
instr_being_modified(instr, false /*raw bits invalid*/);
/* do not assume operands are valid, they are separate from opcode,
* but if opcode is invalid operands shouldn't be valid
*/
CLIENT_ASSERT((opcode != OP_INVALID && opcode != OP_UNDECODED) ||
!instr_operands_valid(instr),
"instr_set_opcode: operand-opcode validity mismatch");
}
/* Returns true iff instr's opcode is NOT OP_INVALID.
* Not to be confused with an invalid opcode, which can be OP_INVALID or
* OP_UNDECODED. OP_INVALID means an instruction with no valid fields:
* raw bits (may exist but do not correspond to a valid instr), opcode,
* eflags, or operands. It could be an uninitialized
* instruction or the result of decoding an invalid sequence of bytes.
*/
bool
instr_valid(instr_t *instr)
{
return (instr->opcode != OP_INVALID);
}
DR_API
/* Get the original application PC of the instruction if it exists. */
app_pc
instr_get_app_pc(instr_t *instr)
{
return instr_get_translation(instr);
}
/* Returns true iff instr's opcode is valid. If the opcode is not
* OP_INVALID or OP_UNDECODED it is assumed to be valid. However, calling
* instr_get_opcode() will attempt to decode an OP_UNDECODED opcode, hence the
* purpose of this routine.
*/
bool
instr_opcode_valid(instr_t *instr)
{
return (instr->opcode != OP_INVALID && instr->opcode != OP_UNDECODED);
}
const instr_info_t *
instr_get_instr_info(instr_t *instr)
{
dr_isa_mode_t isa_mode;
#ifdef ARM
bool in_it_block = false;
#endif
if (instr == NULL)
return NULL;
isa_mode = instr_get_isa_mode(instr);
#ifdef ARM
if (isa_mode == DR_ISA_ARM_THUMB) {
/* A predicated OP_b_short could be either in an IT block or not,
* we assume it is not in an IT block in the case of OP_b_short.
*/
if (instr_get_opcode(instr) != OP_b_short &&
instr_get_predicate(instr) != DR_PRED_NONE)
in_it_block = true;
}
#endif
return opcode_to_encoding_info(instr_get_opcode(instr),
isa_mode _IF_ARM(in_it_block));
}
const instr_info_t *
get_instr_info(int opcode)
{
/* Assuming the use case of this function is to get the opcode related info,
*e.g., eflags in instr_get_opcode_eflags for OP_adds vs OP_add, so it does
* not matter whether it is in an IT block or not.
*/
return opcode_to_encoding_info(
opcode, dr_get_isa_mode(get_thread_private_dcontext()) _IF_ARM(false));
}
#undef instr_get_src
opnd_t
instr_get_src(instr_t *instr, uint pos)
{
return INSTR_GET_SRC(instr, pos);
}
#define instr_get_src INSTR_GET_SRC
#undef instr_get_dst
opnd_t
instr_get_dst(instr_t *instr, uint pos)
{
return INSTR_GET_DST(instr, pos);
}
#define instr_get_dst INSTR_GET_DST
/* allocates storage for instr_num_srcs src operands and instr_num_dsts dst operands
* assumes that instr is currently all zeroed out!
*/
void
instr_set_num_opnds(void *drcontext, instr_t *instr, int instr_num_dsts,
int instr_num_srcs)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
if (instr_num_dsts > 0) {
CLIENT_ASSERT(instr->num_dsts == 0 && instr->dsts == NULL,
"instr_set_num_opnds: dsts are already set");
CLIENT_ASSERT_TRUNCATE(instr->num_dsts, byte, instr_num_dsts,
"instr_set_num_opnds: too many dsts");
instr->num_dsts = (byte)instr_num_dsts;
if (TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags)) {
instr_noalloc_t *noalloc = (instr_noalloc_t *)instr;
noalloc->instr.dsts = noalloc->dsts;
} else {
instr->dsts = (opnd_t *)heap_alloc(
dcontext, instr_num_dsts * sizeof(opnd_t) HEAPACCT(ACCT_IR));
}
}
if (instr_num_srcs > 0) {
/* remember that src0 is static, rest are dynamic */
if (instr_num_srcs > 1) {
CLIENT_ASSERT(instr->num_srcs <= 1 && instr->srcs == NULL,
"instr_set_num_opnds: srcs are already set");
if (TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags)) {
instr_noalloc_t *noalloc = (instr_noalloc_t *)instr;
noalloc->instr.srcs = noalloc->srcs;
} else {
instr->srcs = (opnd_t *)heap_alloc(
dcontext, (instr_num_srcs - 1) * sizeof(opnd_t) HEAPACCT(ACCT_IR));
}
}
CLIENT_ASSERT_TRUNCATE(instr->num_srcs, byte, instr_num_srcs,
"instr_set_num_opnds: too many srcs");
instr->num_srcs = (byte)instr_num_srcs;
}
instr_being_modified(instr, false /*raw bits invalid*/);
/* assume all operands are valid */
instr_set_operands_valid(instr, true);
}
/* sets the src opnd at position pos in instr */
void
instr_set_src(instr_t *instr, uint pos, opnd_t opnd)
{
CLIENT_ASSERT(pos >= 0 && pos < instr->num_srcs, "instr_set_src: ordinal invalid");
/* remember that src0 is static, rest are dynamic */
if (pos == 0)
instr->src0 = opnd;
else
instr->srcs[pos - 1] = opnd;
/* if we're modifying operands, don't use original bits to encode! */
instr_being_modified(instr, false /*raw bits invalid*/);
/* assume all operands are valid */
instr_set_operands_valid(instr, true);
}
/* sets the dst opnd at position pos in instr */
void
instr_set_dst(instr_t *instr, uint pos, opnd_t opnd)
{
CLIENT_ASSERT(pos >= 0 && pos < instr->num_dsts, "instr_set_dst: ordinal invalid");
instr->dsts[pos] = opnd;
/* if we're modifying operands, don't use original bits to encode! */
instr_being_modified(instr, false /*raw bits invalid*/);
/* assume all operands are valid */
instr_set_operands_valid(instr, true);
}
/* end is open-ended (so pass pos,pos+1 to remove just the pos-th src) */
void
instr_remove_srcs(void *drcontext, instr_t *instr, uint start, uint end)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
opnd_t *new_srcs;
CLIENT_ASSERT(!TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags),
/* We could implement, but it does not seem an important use case. */
"instr_remove_srcs not supported for instr_noalloc_t");
CLIENT_ASSERT(start >= 0 && end <= instr->num_srcs && start < end,
"instr_remove_srcs: ordinals invalid");
if (instr->num_srcs - 1 > (byte)(end - start)) {
new_srcs = (opnd_t *)heap_alloc(dcontext,
(instr->num_srcs - 1 - (end - start)) *
sizeof(opnd_t) HEAPACCT(ACCT_IR));
if (start > 1)
memcpy(new_srcs, instr->srcs, (start - 1) * sizeof(opnd_t));
if ((byte)end < instr->num_srcs - 1) {
memcpy(new_srcs + (start == 0 ? 0 : (start - 1)), instr->srcs + end,
(instr->num_srcs - 1 - end) * sizeof(opnd_t));
}
} else
new_srcs = NULL;
if (start == 0 && end < instr->num_srcs)
instr->src0 = instr->srcs[end - 1];
heap_free(dcontext, instr->srcs,
(instr->num_srcs - 1) * sizeof(opnd_t) HEAPACCT(ACCT_IR));
instr->num_srcs -= (byte)(end - start);
instr->srcs = new_srcs;
instr_being_modified(instr, false /*raw bits invalid*/);
instr_set_operands_valid(instr, true);
}
/* end is open-ended (so pass pos,pos+1 to remove just the pos-th dst) */
void
instr_remove_dsts(void *drcontext, instr_t *instr, uint start, uint end)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
opnd_t *new_dsts;
CLIENT_ASSERT(!TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags),
/* We could implement, but it does not seem an important use case. */
"instr_remove_srcs not supported for instr_noalloc_t");
CLIENT_ASSERT(start >= 0 && end <= instr->num_dsts && start < end,
"instr_remove_dsts: ordinals invalid");
if (instr->num_dsts > (byte)(end - start)) {
new_dsts = (opnd_t *)heap_alloc(dcontext,
(instr->num_dsts - (end - start)) *
sizeof(opnd_t) HEAPACCT(ACCT_IR));
if (start > 0)
memcpy(new_dsts, instr->dsts, start * sizeof(opnd_t));
if (end < instr->num_dsts) {
memcpy(new_dsts + start, instr->dsts + end,
(instr->num_dsts - end) * sizeof(opnd_t));
}
} else
new_dsts = NULL;
heap_free(dcontext, instr->dsts, instr->num_dsts * sizeof(opnd_t) HEAPACCT(ACCT_IR));
instr->num_dsts -= (byte)(end - start);
instr->dsts = new_dsts;
instr_being_modified(instr, false /*raw bits invalid*/);
instr_set_operands_valid(instr, true);
}
#undef instr_get_target
opnd_t
instr_get_target(instr_t *instr)
{
return INSTR_GET_TARGET(instr);
}
#define instr_get_target INSTR_GET_TARGET
/* Assumes that if an instr has a jump target, it's stored in the 0th src
* location.
*/
void
instr_set_target(instr_t *instr, opnd_t target)
{
CLIENT_ASSERT(instr->num_srcs >= 1, "instr_set_target: instr has no sources");
instr->src0 = target;
/* if we're modifying operands, don't use original bits to encode,
* except for jecxz/loop*
*/
instr_being_modified(instr, instr_is_cti_short_rewrite(instr, NULL));
/* assume all operands are valid */
instr_set_operands_valid(instr, true);
}
instr_t *
instr_set_prefix_flag(instr_t *instr, uint prefix)
{
instr->prefixes |= prefix;
instr_being_modified(instr, false /*raw bits invalid*/);
return instr;
}
bool
instr_get_prefix_flag(instr_t *instr, uint prefix)
{
return ((instr->prefixes & prefix) != 0);
}
void
instr_set_prefixes(instr_t *instr, uint prefixes)
{
instr->prefixes = prefixes;
instr_being_modified(instr, false /*raw bits invalid*/);
}
uint
instr_get_prefixes(instr_t *instr)
{
return instr->prefixes;
}
bool
instr_is_predicated(instr_t *instr)
{
/* XXX i#1556: we should also mark conditional branches and string loops
* as predicated!
*/
dr_pred_type_t pred = instr_get_predicate(instr);
return instr_predicate_is_cond(pred);
}
dr_pred_type_t
instr_get_predicate(instr_t *instr)
{
/* Optimization: we assume prefixes are the high bits to avoid an & */
return instr->prefixes >> PREFIX_PRED_BITPOS;
}
instr_t *
instr_set_predicate(instr_t *instr, dr_pred_type_t pred)
{
instr->prefixes |= ((pred << PREFIX_PRED_BITPOS) & PREFIX_PRED_MASK);
return instr;
}
bool
instr_branch_is_padded(instr_t *instr)
{
return TEST(INSTR_BRANCH_PADDED, instr->flags);
}
void
instr_branch_set_padded(instr_t *instr, bool val)
{
if (val)
instr->flags |= INSTR_BRANCH_PADDED;
else
instr->flags &= ~INSTR_BRANCH_PADDED;
}
/* Returns true iff instr has been marked as a special exit cti */
bool
instr_branch_special_exit(instr_t *instr)
{
return TEST(INSTR_BRANCH_SPECIAL_EXIT, instr->flags);
}
/* If val is true, indicates that instr is a special exit cti.
* If val is false, indicates otherwise
*/
void
instr_branch_set_special_exit(instr_t *instr, bool val)
{
if (val)
instr->flags |= INSTR_BRANCH_SPECIAL_EXIT;
else
instr->flags &= ~INSTR_BRANCH_SPECIAL_EXIT;
}
/* Returns the type of the original indirect branch of an exit
*/
int
instr_exit_branch_type(instr_t *instr)
{
return instr->flags & EXIT_CTI_TYPES;
}
/* Set type of indirect branch exit
*/
void
instr_exit_branch_set_type(instr_t *instr, uint type)
{
/* set only expected flags */
type &= EXIT_CTI_TYPES;
instr->flags &= ~EXIT_CTI_TYPES;
instr->flags |= type;
}
void
instr_set_ok_to_mangle(instr_t *instr, bool val)
{
if (val)
instr_set_app(instr);
else
instr_set_meta(instr);
}
void
instr_set_app(instr_t *instr)
{
instr->flags &= ~INSTR_DO_NOT_MANGLE;
}
void
instr_set_meta(instr_t *instr)
{
instr->flags |= INSTR_DO_NOT_MANGLE;
}
bool
instr_is_meta_may_fault(instr_t *instr)
{
/* no longer using a special flag (i#496) */
return instr_is_meta(instr) && instr_get_translation(instr) != NULL;
}
void
instr_set_meta_may_fault(instr_t *instr, bool val)
{
/* no longer using a special flag (i#496) */
instr_set_meta(instr);
CLIENT_ASSERT(instr_get_translation(instr) != NULL,
"meta_may_fault instr must have translation");
}
/* convenience routine */
void
instr_set_meta_no_translation(instr_t *instr)
{
instr_set_meta(instr);
instr_set_translation(instr, NULL);
}
void
instr_set_ok_to_emit(instr_t *instr, bool val)
{
CLIENT_ASSERT(instr != NULL, "instr_set_ok_to_emit: passed NULL");
if (val)
instr->flags &= ~INSTR_DO_NOT_EMIT;
else
instr->flags |= INSTR_DO_NOT_EMIT;
}
uint
instr_eflags_conditionally(uint full_eflags, dr_pred_type_t pred,
dr_opnd_query_flags_t flags)
{
if (!TEST(DR_QUERY_INCLUDE_COND_SRCS, flags) && instr_predicate_is_cond(pred) &&
!instr_predicate_reads_srcs(pred)) {
/* i#1836: the predicate itself reads some flags */
full_eflags &= ~EFLAGS_READ_NON_PRED;
}
if (!TEST(DR_QUERY_INCLUDE_COND_DSTS, flags) && instr_predicate_is_cond(pred) &&
!instr_predicate_writes_eflags(pred))
full_eflags &= ~EFLAGS_WRITE_ALL;
return full_eflags;
}
uint
instr_get_eflags(instr_t *instr, dr_opnd_query_flags_t flags)
{
if ((instr->flags & INSTR_EFLAGS_VALID) == 0) {
bool encoded = false;
dcontext_t *dcontext = get_thread_private_dcontext();
dr_isa_mode_t old_mode;
/* we assume we cannot trust the opcode independently of operands */
if (instr_needs_encoding(instr)) {
int len;
encoded = true;
len = private_instr_encode(dcontext, instr, true /*cache*/);
if (len == 0) {
if (!instr_is_label(instr))
CLIENT_ASSERT(false, "instr_get_eflags: invalid instr");
return 0;
}
}
dr_set_isa_mode(dcontext, instr_get_isa_mode(instr), &old_mode);
decode_eflags_usage(dcontext, instr_get_raw_bits(instr), &instr->eflags,
DR_QUERY_INCLUDE_ALL);
dr_set_isa_mode(dcontext, old_mode, NULL);
if (encoded) {
/* if private_instr_encode passed us back whether it's valid
* to cache (i.e., non-meta instr that can reach) we could skip
* this invalidation for such cases */
instr_free_raw_bits(dcontext, instr);
CLIENT_ASSERT(!instr_raw_bits_valid(instr), "internal encoding buf error");
}
/* even if decode fails, set valid to true -- ok? FIXME */
instr_set_eflags_valid(instr, true);
}
return instr_eflags_conditionally(instr->eflags, instr_get_predicate(instr), flags);
}
DR_API
/* Returns the eflags usage of instructions with opcode "opcode",
* as EFLAGS_ constants or'ed together
*/
uint
instr_get_opcode_eflags(int opcode)
{
/* assumption: all encoding of an opcode have same eflags behavior! */
const instr_info_t *info = get_instr_info(opcode);
return info->eflags;
}
uint
instr_get_arith_flags(instr_t *instr, dr_opnd_query_flags_t flags)
{
if ((instr->flags & INSTR_EFLAGS_6_VALID) == 0) {
/* just get info on all the flags */
return instr_get_eflags(instr, flags);
}
return instr_eflags_conditionally(instr->eflags, instr_get_predicate(instr), flags);
}
bool
instr_eflags_valid(instr_t *instr)
{
return ((instr->flags & INSTR_EFLAGS_VALID) != 0);
}
void
instr_set_eflags_valid(instr_t *instr, bool valid)
{
if (valid) {
instr->flags |= INSTR_EFLAGS_VALID;
instr->flags |= INSTR_EFLAGS_6_VALID;
} else {
/* assume that arith flags are also invalid */
instr->flags &= ~INSTR_EFLAGS_VALID;
instr->flags &= ~INSTR_EFLAGS_6_VALID;
}
}
/* Returns true iff instr's arithmetic flags (the 6 bottom eflags) are
* up to date */
bool
instr_arith_flags_valid(instr_t *instr)
{
return ((instr->flags & INSTR_EFLAGS_6_VALID) != 0);
}
/* Sets instr's arithmetic flags (the 6 bottom eflags) to be valid if
* valid is true, invalid otherwise */
void
instr_set_arith_flags_valid(instr_t *instr, bool valid)
{
if (valid)
instr->flags |= INSTR_EFLAGS_6_VALID;
else {
instr->flags &= ~INSTR_EFLAGS_VALID;
instr->flags &= ~INSTR_EFLAGS_6_VALID;
}
}
void
instr_set_operands_valid(instr_t *instr, bool valid)
{
if (valid)
instr->flags |= INSTR_OPERANDS_VALID;
else
instr->flags &= ~INSTR_OPERANDS_VALID;
}
/* N.B.: this routine sets the "raw bits are valid" flag */
void
instr_set_raw_bits(instr_t *instr, byte *addr, uint length)
{
if ((instr->flags & INSTR_RAW_BITS_ALLOCATED) != 0) {
/* this does happen, when up-decoding an instr using its
* own raw bits, so let it happen, but make sure allocated
* bits aren't being lost
*/
CLIENT_ASSERT(addr == instr->bytes && length == instr->length,
"instr_set_raw_bits: bits already there, but different");
}
if (!instr_valid(instr))
instr_set_opcode(instr, OP_UNDECODED);
instr->flags |= INSTR_RAW_BITS_VALID;
instr->bytes = addr;
instr->length = length;
#ifdef X86
instr_set_rip_rel_valid(instr, false); /* relies on original raw bits */
#endif
}
/* this is sort of a hack, used to allow dynamic reallocation of
* the trace buffer, which requires shifting the addresses of all
* the trace Instrs since they point into the old buffer
*/
void
instr_shift_raw_bits(instr_t *instr, ssize_t offs)
{
if ((instr->flags & INSTR_RAW_BITS_VALID) != 0)
instr->bytes += offs;
#ifdef X86
instr_set_rip_rel_valid(instr, false); /* relies on original raw bits */
#endif
}
/* moves the instruction from USE_ORIGINAL_BITS state to a
* needs-full-encoding state
*/
void
instr_set_raw_bits_valid(instr_t *instr, bool valid)
{
if (valid)
instr->flags |= INSTR_RAW_BITS_VALID;
else {
instr->flags &= ~INSTR_RAW_BITS_VALID;
/* DO NOT set bytes to NULL or length to 0, we still want to be
* able to point at the original instruction for use in translating
* addresses for exception/signal handlers
* Also do not de-allocate allocated bits
*/
#ifdef X86
instr_set_rip_rel_valid(instr, false);
#endif
}
}
void
instr_free_raw_bits(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
if ((instr->flags & INSTR_RAW_BITS_ALLOCATED) == 0)
return;
if (!TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags))
heap_reachable_free(dcontext, instr->bytes, instr->length HEAPACCT(ACCT_IR));
instr->bytes = NULL;
instr->flags &= ~INSTR_RAW_BITS_VALID;
instr->flags &= ~INSTR_RAW_BITS_ALLOCATED;
}
/* creates array of bytes to store raw bytes of an instr into
* (original bits are read-only)
* initializes array to the original bits!
*/
void
instr_allocate_raw_bits(void *drcontext, instr_t *instr, uint num_bytes)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
byte *original_bits = NULL;
if (TEST(INSTR_RAW_BITS_VALID, instr->flags))
original_bits = instr->bytes;
if (!TEST(INSTR_RAW_BITS_ALLOCATED, instr->flags) || instr->length != num_bytes) {
byte *new_bits;
if (TEST(INSTR_IS_NOALLOC_STRUCT, instr->flags)) {
/* This may not be reachable, so re-relativization is limited. */
instr_noalloc_t *noalloc = (instr_noalloc_t *)instr;
CLIENT_ASSERT(num_bytes <= sizeof(noalloc->encode_buf),
"instr_allocate_raw_bits exceeds instr_noalloc_t capacity");
new_bits = noalloc->encode_buf;
} else {
/* We need reachable heap for rip-rel re-relativization. */
new_bits =
(byte *)heap_reachable_alloc(dcontext, num_bytes HEAPACCT(ACCT_IR));
}
if (original_bits != NULL) {
/* copy original bits into modified bits so can just modify
* a few and still have all info in one place
*/
memcpy(new_bits, original_bits,
(num_bytes < instr->length) ? num_bytes : instr->length);
}
if ((instr->flags & INSTR_RAW_BITS_ALLOCATED) != 0)
instr_free_raw_bits(dcontext, instr);
instr->bytes = new_bits;
instr->length = num_bytes;
}
/* assume that the bits are now valid and the operands are not */
instr->flags |= INSTR_RAW_BITS_VALID;
instr->flags |= INSTR_RAW_BITS_ALLOCATED;
instr->flags &= ~INSTR_OPERANDS_VALID;
instr->flags &= ~INSTR_EFLAGS_VALID;
#ifdef X86
instr_set_rip_rel_valid(instr, false); /* relies on original raw bits */
#endif
}
void
instr_set_label_callback(instr_t *instr, instr_label_callback_t cb)
{
CLIENT_ASSERT(instr_is_label(instr),
"only set callback functions for label instructions");
CLIENT_ASSERT(instr->label_cb == NULL, "label callback function is already set");
CLIENT_ASSERT(!TEST(INSTR_RAW_BITS_ALLOCATED, instr->flags),
"instruction's raw bits occupying label callback memory");
instr->label_cb = cb;
}
void
instr_clear_label_callback(instr_t *instr)
{
CLIENT_ASSERT(instr_is_label(instr),
"only set callback functions for label instructions");
CLIENT_ASSERT(instr->label_cb != NULL, "label callback function not set");
CLIENT_ASSERT(!TEST(INSTR_RAW_BITS_ALLOCATED, instr->flags),
"instruction's raw bits occupying label callback memory");
instr->label_cb = NULL;
}
instr_label_callback_t
instr_get_label_callback(instr_t *instr)
{
CLIENT_ASSERT(instr_is_label(instr),
"only label instructions have a callback function");
CLIENT_ASSERT(!TEST(INSTR_RAW_BITS_ALLOCATED, instr->flags),
"instruction's raw bits occupying label callback memory");
return instr->label_cb;
}
instr_t *
instr_set_translation(instr_t *instr, app_pc addr)
{
#if defined(WINDOWS) && !defined(STANDALONE_DECODER)
addr = get_app_pc_from_intercept_pc_if_necessary(addr);
#endif
instr->translation = addr;
return instr;
}
app_pc
instr_get_translation(instr_t *instr)
{
return instr->translation;
}
/* This makes it safe to keep an instr around indefinitely when an instrs raw
* bits point into the cache. It allocates memory local to the instr to hold
* a copy of the raw bits. If this was not done the original raw bits could
* be deleted at some point. This is necessary if you want to keep an instr
* around for a long time (for clients, beyond returning from the call that
* gave you the instr)
*/
void
instr_make_persistent(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
if ((instr->flags & INSTR_RAW_BITS_VALID) != 0 &&
(instr->flags & INSTR_RAW_BITS_ALLOCATED) == 0) {
instr_allocate_raw_bits(dcontext, instr, instr->length);
}
}
byte *
instr_get_raw_bits(instr_t *instr)
{
return instr->bytes;
}
/* returns the pos-th instr byte */
byte
instr_get_raw_byte(instr_t *instr, uint pos)
{
CLIENT_ASSERT(pos >= 0 && pos < instr->length && instr->bytes != NULL,
"instr_get_raw_byte: ordinal invalid, or no raw bits");
return instr->bytes[pos];
}
/* returns the 4 bytes starting at position pos */
uint
instr_get_raw_word(instr_t *instr, uint pos)
{
CLIENT_ASSERT(pos >= 0 && pos + 3 < instr->length && instr->bytes != NULL,
"instr_get_raw_word: ordinal invalid, or no raw bits");
return *((uint *)(instr->bytes + pos));
}
/* Sets the pos-th instr byte by storing the unsigned
* character value in the pos-th slot
* Must call instr_allocate_raw_bits before calling this function
* (original bits are read-only!)
*/
void
instr_set_raw_byte(instr_t *instr, uint pos, byte val)
{
CLIENT_ASSERT((instr->flags & INSTR_RAW_BITS_ALLOCATED) != 0,
"instr_set_raw_byte: no raw bits");
CLIENT_ASSERT(pos >= 0 && pos < instr->length && instr->bytes != NULL,
"instr_set_raw_byte: ordinal invalid, or no raw bits");
instr->bytes[pos] = (byte)val;
#ifdef X86
instr_set_rip_rel_valid(instr, false); /* relies on original raw bits */
#endif
}
/* Copies num_bytes bytes from start into the mangled bytes
* array of instr.
* Must call instr_allocate_raw_bits before calling this function.
*/
void
instr_set_raw_bytes(instr_t *instr, byte *start, uint num_bytes)
{
CLIENT_ASSERT((instr->flags & INSTR_RAW_BITS_ALLOCATED) != 0,
"instr_set_raw_bytes: no raw bits");
CLIENT_ASSERT(num_bytes <= instr->length && instr->bytes != NULL,
"instr_set_raw_bytes: ordinal invalid, or no raw bits");
memcpy(instr->bytes, start, num_bytes);
#ifdef X86
instr_set_rip_rel_valid(instr, false); /* relies on original raw bits */
#endif
}
/* Stores 32-bit value word in positions pos through pos+3 in
* modified_bits.
* Must call instr_allocate_raw_bits before calling this function.
*/
void
instr_set_raw_word(instr_t *instr, uint pos, uint word)
{
CLIENT_ASSERT((instr->flags & INSTR_RAW_BITS_ALLOCATED) != 0,
"instr_set_raw_word: no raw bits");
CLIENT_ASSERT(pos >= 0 && pos + 3 < instr->length && instr->bytes != NULL,
"instr_set_raw_word: ordinal invalid, or no raw bits");
*((uint *)(instr->bytes + pos)) = word;
#ifdef X86
instr_set_rip_rel_valid(instr, false); /* relies on original raw bits */
#endif
}
int
instr_length(void *drcontext, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
int res;
#ifdef ARM
/* We can't handle IT blocks if we only track state on some instrs that
* we have to encode for length, so unfortunately we must pay the cost
* of tracking for every length call.
*/
encode_track_it_block(dcontext, instr);
#endif
if (!instr_needs_encoding(instr))
return instr->length;
res = instr_length_arch(dcontext, instr);
if (res != -1)
return res;
/* else, encode to find length */
return private_instr_encode(dcontext, instr, false /*don't need to cache*/);
}
instr_t *
instr_set_encoding_hint(instr_t *instr, dr_encoding_hint_type_t hint)
{
instr->encoding_hints |= hint;
return instr;
}
bool
instr_has_encoding_hint(instr_t *instr, dr_encoding_hint_type_t hint)
{
return TEST(hint, instr->encoding_hints);
}
/***********************************************************************/
/* decoding routines */
/* If instr is at Level 0 (i.e., a bundled group of instrs as raw bits),
* expands instr into a sequence of Level 1 instrs using decode_raw() which
* are added in place to ilist.
* Returns the replacement of instr, if any expansion is performed
* (in which case the old instr is destroyed); otherwise returns
* instr unchanged.
* If encounters an invalid instr, stops expanding at that instr, and keeps
* instr in the ilist pointing to the invalid bits as an invalid instr.
*/
instr_t *
instr_expand(dcontext_t *dcontext, instrlist_t *ilist, instr_t *instr)
{
/* Sometimes deleting instr but sometimes not (when return early)
* is painful -- so we go to the trouble of re-using instr
* for the first expanded instr
*/
instr_t *newinstr, *firstinstr = NULL;
int remaining_bytes, cur_inst_len;
byte *curbytes, *newbytes;
dr_isa_mode_t old_mode;
/* make it easy for iterators: handle NULL
* assume that if opcode is valid, is at Level 2, so not a bundle
* do not expand meta-instrs -- FIXME: is that the right thing to do?
*/
if (instr == NULL || instr_opcode_valid(instr) || instr_is_meta(instr) ||
/* if an invalid instr (not just undecoded) do not try to expand */
!instr_valid(instr))
return instr;
DOLOG(5, LOG_ALL, {
/* disassembling might change the instruction object, we're cloning it
* for the logger */
instr_t *log_instr = instr_clone(dcontext, instr);
d_r_loginst(dcontext, 4, log_instr, "instr_expand");
instr_destroy(dcontext, log_instr);
});
/* decode routines use dcontext mode, but we want instr mode */
dr_set_isa_mode(dcontext, instr_get_isa_mode(instr), &old_mode);
/* never have opnds but not opcode */
CLIENT_ASSERT(!instr_operands_valid(instr), "instr_expand: opnds are already valid");
CLIENT_ASSERT(instr_raw_bits_valid(instr), "instr_expand: raw bits are invalid");
curbytes = instr->bytes;
if ((uint)decode_sizeof(dcontext, curbytes, NULL _IF_X86_64(NULL)) == instr->length) {
dr_set_isa_mode(dcontext, old_mode, NULL);
return instr; /* Level 1 */
}
remaining_bytes = instr->length;
while (remaining_bytes > 0) {
/* insert every separated instr into list */
newinstr = instr_create(dcontext);
newbytes = decode_raw(dcontext, curbytes, newinstr);
#ifndef NOT_DYNAMORIO_CORE_PROPER
if (expand_should_set_translation(dcontext))
instr_set_translation(newinstr, curbytes);
#endif
if (newbytes == NULL) {
/* invalid instr -- stop expanding, point instr at remaining bytes */
instr_set_raw_bits(instr, curbytes, remaining_bytes);
instr_set_opcode(instr, OP_INVALID);
if (firstinstr == NULL)
firstinstr = instr;
instr_destroy(dcontext, newinstr);
dr_set_isa_mode(dcontext, old_mode, NULL);
return firstinstr;
}
DOLOG(5, LOG_ALL,
{ d_r_loginst(dcontext, 4, newinstr, "\tjust expanded into"); });
/* CAREFUL of what you call here -- don't call anything that
* auto-upgrades instr to Level 2, it will fail on Level 0 bundles!
*/
if (instr_has_allocated_bits(instr) &&
!instr_is_cti_short_rewrite(newinstr, curbytes)) {
/* make sure to have our own copy of any allocated bits
* before we destroy the original instr
*/
IF_X64(CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_uint(newbytes - curbytes),
"instr_expand: internal truncation error"));
instr_allocate_raw_bits(dcontext, newinstr, (uint)(newbytes - curbytes));
}
/* special case: for cti_short, do not fully decode the
* constituent instructions, leave as a bundle.
* the instr will still have operands valid.
*/
if (instr_is_cti_short_rewrite(newinstr, curbytes)) {
newbytes = remangle_short_rewrite(dcontext, newinstr, curbytes, 0);
} else if (instr_is_cti_short(newinstr)) {
/* make sure non-mangled short ctis, which are generated by
* us and never left there from app's, are not marked as exit ctis
*/
instr_set_meta(newinstr);
}
IF_X64(CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_int(newbytes - curbytes),
"instr_expand: internal truncation error"));
cur_inst_len = (int)(newbytes - curbytes);
remaining_bytes -= cur_inst_len;
curbytes = newbytes;
instrlist_preinsert(ilist, instr, newinstr);
if (firstinstr == NULL)
firstinstr = newinstr;
}
/* delete original instr from list */
instrlist_remove(ilist, instr);
instr_destroy(dcontext, instr);
CLIENT_ASSERT(firstinstr != NULL, "instr_expand failure");
dr_set_isa_mode(dcontext, old_mode, NULL);
return firstinstr;
}
bool
instr_is_level_0(instr_t *instr)
{
dcontext_t *dcontext = get_thread_private_dcontext();
dr_isa_mode_t old_mode;
/* assume that if opcode is valid, is at Level 2, so not a bundle
* do not expand meta-instrs -- FIXME: is that the right to do? */
if (instr == NULL || instr_opcode_valid(instr) || instr_is_meta(instr) ||
/* if an invalid instr (not just undecoded) do not try to expand */
!instr_valid(instr))
return false;
/* never have opnds but not opcode */
CLIENT_ASSERT(!instr_operands_valid(instr),
"instr_is_level_0: opnds are already valid");
CLIENT_ASSERT(instr_raw_bits_valid(instr), "instr_is_level_0: raw bits are invalid");
dr_set_isa_mode(dcontext, instr_get_isa_mode(instr), &old_mode);
if ((uint)decode_sizeof(dcontext, instr->bytes, NULL _IF_X86_64(NULL)) ==
instr->length) {
dr_set_isa_mode(dcontext, old_mode, NULL);
return false; /* Level 1 */
}
dr_set_isa_mode(dcontext, old_mode, NULL);
return true;
}
/* If the next instr is at Level 0 (i.e., a bundled group of instrs as raw bits),
* expands it into a sequence of Level 1 instrs using decode_raw() which
* are added in place to ilist. Then returns the new next instr.
*/
instr_t *
instr_get_next_expanded(dcontext_t *dcontext, instrlist_t *ilist, instr_t *instr)
{
instr_expand(dcontext, ilist, instr_get_next(instr));
return instr_get_next(instr);
}
/* If the prev instr is at Level 0 (i.e., a bundled group of instrs as raw bits),
* expands it into a sequence of Level 1 instrs using decode_raw() which
* are added in place to ilist. Then returns the new prev instr.
*/
instr_t *
instr_get_prev_expanded(dcontext_t *dcontext, instrlist_t *ilist, instr_t *instr)
{
instr_expand(dcontext, ilist, instr_get_prev(instr));
return instr_get_prev(instr);
}
/* If the first instr is at Level 0 (i.e., a bundled group of instrs as raw bits),
* expands it into a sequence of Level 1 instrs using decode_raw() which
* are added in place to ilist. Then returns the new first instr.
*/
instr_t *
instrlist_first_expanded(dcontext_t *dcontext, instrlist_t *ilist)
{
instr_expand(dcontext, ilist, instrlist_first(ilist));
return instrlist_first(ilist);
}
/* If the last instr is at Level 0 (i.e., a bundled group of instrs as raw bits),
* expands it into a sequence of Level 1 instrs using decode_raw() which
* are added in place to ilist. Then returns the new last instr.
*/
instr_t *
instrlist_last_expanded(dcontext_t *dcontext, instrlist_t *ilist)
{
instr_expand(dcontext, ilist, instrlist_last(ilist));
return instrlist_last(ilist);
}
/* If instr is not already at the level of decode_cti, decodes enough
* from the raw bits pointed to by instr to bring it to that level.
* Assumes that instr is a single instr (i.e., NOT Level 0).
*
* decode_cti decodes only enough of instr to determine
* its size, its effects on the 6 arithmetic eflags, and whether it is
* a control-transfer instruction. If it is, the operands fields of
* instr are filled in. If not, only the raw bits fields of instr are
* filled in. This corresponds to a Level 3 decoding for control
* transfer instructions but a Level 1 decoding plus arithmetic eflags
* information for all other instructions.
*/
void
instr_decode_cti(dcontext_t *dcontext, instr_t *instr)
{
/* if arith flags are missing but otherwise decoded, who cares,
* next get_arith_flags() will fill it in
*/
if (!instr_opcode_valid(instr) ||
(instr_is_cti(instr) && !instr_operands_valid(instr))) {
byte *next_pc;
DEBUG_EXT_DECLARE(int old_len = instr->length;)
/* decode_cti() will use the dcontext mode, but we want the instr mode */
dr_isa_mode_t old_mode;
dr_set_isa_mode(dcontext, instr_get_isa_mode(instr), &old_mode);
CLIENT_ASSERT(instr_raw_bits_valid(instr),
"instr_decode_cti: raw bits are invalid");
instr_reuse(dcontext, instr);
next_pc = decode_cti(dcontext, instr->bytes, instr);
dr_set_isa_mode(dcontext, old_mode, NULL);
/* ok to be invalid, let caller deal with it */
CLIENT_ASSERT(next_pc == NULL || (next_pc - instr->bytes == old_len),
"instr_decode_cti requires a Level 1 or higher instruction");
}
}
/* If instr is not already at the level of decode_opcode, decodes enough
* from the raw bits pointed to by instr to bring it to that level.
* Assumes that instr is a single instr (i.e., NOT Level 0).
*
* decode_opcode decodes the opcode and eflags usage of the instruction.
* This corresponds to a Level 2 decoding.
*/
void
instr_decode_opcode(dcontext_t *dcontext, instr_t *instr)
{
if (!instr_opcode_valid(instr)) {
byte *next_pc;
DEBUG_EXT_DECLARE(int old_len = instr->length;)
#ifdef X86
bool rip_rel_valid = instr_rip_rel_valid(instr);
#endif
/* decode_opcode() will use the dcontext mode, but we want the instr mode */
dr_isa_mode_t old_mode;
dr_set_isa_mode(dcontext, instr_get_isa_mode(instr), &old_mode);
CLIENT_ASSERT(instr_raw_bits_valid(instr),
"instr_decode_opcode: raw bits are invalid");
instr_reuse(dcontext, instr);
next_pc = decode_opcode(dcontext, instr->bytes, instr);
dr_set_isa_mode(dcontext, old_mode, NULL);
#ifdef X86
/* decode_opcode sets raw bits which invalidates rip_rel, but
* it should still be valid on an up-decode of the opcode */
if (rip_rel_valid)
instr_set_rip_rel_pos(instr, instr->rip_rel_pos);
#endif
/* ok to be invalid, let caller deal with it */
CLIENT_ASSERT(next_pc == NULL || (next_pc - instr->bytes == old_len),
"instr_decode_opcode requires a Level 1 or higher instruction");
}
}
/* If instr is not already fully decoded, decodes enough
* from the raw bits pointed to by instr to bring it Level 3.
* Assumes that instr is a single instr (i.e., NOT Level 0).
*/
void
instr_decode(dcontext_t *dcontext, instr_t *instr)
{
if (!instr_operands_valid(instr)) {
byte *next_pc;
DEBUG_EXT_DECLARE(int old_len = instr->length;)
#ifdef X86
bool rip_rel_valid = instr_rip_rel_valid(instr);
#endif
/* decode() will use the current dcontext mode, but we want the instr mode */
dr_isa_mode_t old_mode;
dr_set_isa_mode(dcontext, instr_get_isa_mode(instr), &old_mode);
CLIENT_ASSERT(instr_raw_bits_valid(instr), "instr_decode: raw bits are invalid");
instr_reuse(dcontext, instr);
next_pc = decode(dcontext, instr_get_raw_bits(instr), instr);
#ifndef NOT_DYNAMORIO_CORE_PROPER
if (expand_should_set_translation(dcontext))
instr_set_translation(instr, instr_get_raw_bits(instr));
#endif
dr_set_isa_mode(dcontext, old_mode, NULL);
#ifdef X86
/* decode sets raw bits which invalidates rip_rel, but
* it should still be valid on an up-decode */
if (rip_rel_valid)
instr_set_rip_rel_pos(instr, instr->rip_rel_pos);
#endif
/* ok to be invalid, let caller deal with it */
CLIENT_ASSERT(next_pc == NULL || (next_pc - instr->bytes == old_len),
"instr_decode requires a Level 1 or higher instruction");
}
}
/* Calls instr_decode() with the current dcontext. Mostly useful as the slow
* path for IR routines that get inlined.
*/
NOINLINE /* rarely called */
instr_t *
instr_decode_with_current_dcontext(instr_t *instr)
{
instr_decode(get_thread_private_dcontext(), instr);
return instr;
}
/* Brings all instrs in ilist up to the decode_cti level, and
* hooks up intra-ilist cti targets to use instr_t targets, by
* matching pc targets to each instruction's raw bits.
*
* decode_cti decodes only enough of instr to determine
* its size, its effects on the 6 arithmetic eflags, and whether it is
* a control-transfer instruction. If it is, the operands fields of
* instr are filled in. If not, only the raw bits fields of instr are
* filled in. This corresponds to a Level 3 decoding for control
* transfer instructions but a Level 1 decoding plus arithmetic eflags
* information for all other instructions.
*/
void
instrlist_decode_cti(dcontext_t *dcontext, instrlist_t *ilist)
{
instr_t *instr;
LOG(THREAD, LOG_ALL, 3, "\ninstrlist_decode_cti\n");
DOLOG(4, LOG_ALL, {
LOG(THREAD, LOG_ALL, 4, "beforehand:\n");
instrlist_disassemble(dcontext, 0, ilist, THREAD);
});
/* just use the expanding iterator to get to Level 1, then decode cti */
for (instr = instrlist_first_expanded(dcontext, ilist); instr != NULL;
instr = instr_get_next_expanded(dcontext, ilist, instr)) {
/* if arith flags are missing but otherwise decoded, who cares,
* next get_arith_flags() will fill it in
*/
if (!instr_opcode_valid(instr) ||
(instr_is_cti(instr) && !instr_operands_valid(instr))) {
DOLOG(4, LOG_ALL, {
d_r_loginst(dcontext, 4, instr, "instrlist_decode_cti: about to decode");
});
instr_decode_cti(dcontext, instr);
DOLOG(4, LOG_ALL, { d_r_loginst(dcontext, 4, instr, "\tjust decoded"); });
}
}
/* must fix up intra-ilist cti's to have instr_t targets
* assumption: all intra-ilist cti's have been marked as do-not-mangle,
* plus all targets have their raw bits already set
*/
for (instr = instrlist_first(ilist); instr != NULL; instr = instr_get_next(instr)) {
/* N.B.: if we change exit cti's to have instr_t targets, we have to
* change other modules like emit to handle that!
* FIXME
*/
if (!instr_is_exit_cti(instr) &&
instr_opcode_valid(instr) && /* decode_cti only filled in cti opcodes */
instr_is_cti(instr) && instr_num_srcs(instr) > 0 &&
opnd_is_near_pc(instr_get_src(instr, 0))) {
instr_t *tgt;
DOLOG(4, LOG_ALL, {
d_r_loginst(dcontext, 4, instr,
"instrlist_decode_cti: found cti w/ pc target");
});
for (tgt = instrlist_first(ilist); tgt != NULL; tgt = instr_get_next(tgt)) {
DOLOG(4, LOG_ALL, { d_r_loginst(dcontext, 4, tgt, "\tchecking"); });
LOG(THREAD, LOG_INTERP | LOG_OPTS, 4, "\t\taddress is " PFX "\n",
instr_get_raw_bits(tgt));
if (opnd_get_pc(instr_get_target(instr)) == instr_get_raw_bits(tgt)) {
/* cti targets this instr */
app_pc bits = 0;
int len = 0;
if (instr_raw_bits_valid(instr)) {
bits = instr_get_raw_bits(instr);
len = instr_length(dcontext, instr);
}
instr_set_target(instr, opnd_create_instr(tgt));
if (bits != 0)
instr_set_raw_bits(instr, bits, len);
DOLOG(4, LOG_ALL,
{ d_r_loginst(dcontext, 4, tgt, "\tcti targets this"); });
break;
}
}
}
}
DOLOG(4, LOG_ALL, {
LOG(THREAD, LOG_ALL, 4, "afterward:\n");
instrlist_disassemble(dcontext, 0, ilist, THREAD);
});
LOG(THREAD, LOG_ALL, 4, "done with instrlist_decode_cti\n");
}
/****************************************************************************/
/* utility routines */
void
d_r_loginst(dcontext_t *dcontext, uint level, instr_t *instr, const char *string)
{
DOLOG(level, LOG_ALL, {
LOG(THREAD, LOG_ALL, level, "%s: ", string);
instr_disassemble(dcontext, instr, THREAD);
LOG(THREAD, LOG_ALL, level, "\n");
});
}
void
d_r_logopnd(dcontext_t *dcontext, uint level, opnd_t opnd, const char *string)
{
DOLOG(level, LOG_ALL, {
LOG(THREAD, LOG_ALL, level, "%s: ", string);
opnd_disassemble(dcontext, opnd, THREAD);
LOG(THREAD, LOG_ALL, level, "\n");
});
}
void
d_r_logtrace(dcontext_t *dcontext, uint level, instrlist_t *trace, const char *string)
{
DOLOG(level, LOG_ALL, {
instr_t *inst;
instr_t *next_inst;
LOG(THREAD, LOG_ALL, level, "%s:\n", string);
for (inst = instrlist_first(trace); inst != NULL; inst = next_inst) {
next_inst = instr_get_next(inst);
instr_disassemble(dcontext, inst, THREAD);
LOG(THREAD, LOG_ALL, level, "\n");
}
LOG(THREAD, LOG_ALL, level, "\n");
});
}
/* Shrinks all registers not used as addresses, and all immed int and
* address sizes, to 16 bits
*/
void
instr_shrink_to_16_bits(instr_t *instr)
{
int i;
opnd_t opnd;
const instr_info_t *info;
byte optype;
CLIENT_ASSERT(instr_operands_valid(instr), "instr_shrink_to_16_bits: invalid opnds");
info = get_encoding_info(instr);
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd = instr_get_dst(instr, i);
/* some non-memory references vary in size by addr16, not data16:
* e.g., the edi/esi inc/dec of string instrs
*/
optype = instr_info_opnd_type(info, false /*dst*/, i);
if (!opnd_is_memory_reference(opnd) && !optype_is_indir_reg(optype)) {
instr_set_dst(instr, i, opnd_shrink_to_16_bits(opnd));
}
}
for (i = 0; i < instr_num_srcs(instr); i++) {
opnd = instr_get_src(instr, i);
optype = instr_info_opnd_type(info, true /*dst*/, i);
if (!opnd_is_memory_reference(opnd) && !optype_is_indir_reg(optype)) {
instr_set_src(instr, i, opnd_shrink_to_16_bits(opnd));
}
}
}
#ifdef X64
/* Shrinks all registers, including addresses, and all immed int and
* address sizes, to 32 bits
*/
void
instr_shrink_to_32_bits(instr_t *instr)
{
int i;
opnd_t opnd;
CLIENT_ASSERT(instr_operands_valid(instr), "instr_shrink_to_32_bits: invalid opnds");
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd = instr_get_dst(instr, i);
instr_set_dst(instr, i, opnd_shrink_to_32_bits(opnd));
}
for (i = 0; i < instr_num_srcs(instr); i++) {
opnd = instr_get_src(instr, i);
if (opnd_is_immed_int(opnd)) {
CLIENT_ASSERT(opnd_get_immed_int(opnd) <= INT_MAX,
"instr_shrink_to_32_bits: immed int will be truncated");
}
instr_set_src(instr, i, opnd_shrink_to_32_bits(opnd));
}
}
#endif
bool
instr_uses_reg(instr_t *instr, reg_id_t reg)
{
return (instr_reg_in_dst(instr, reg) || instr_reg_in_src(instr, reg));
}
bool
instr_reg_in_dst(instr_t *instr, reg_id_t reg)
{
int i;
for (i = 0; i < instr_num_dsts(instr); i++) {
if (opnd_uses_reg(instr_get_dst(instr, i), reg))
return true;
}
return false;
}
bool
instr_reg_in_src(instr_t *instr, reg_id_t reg)
{
int i;
#ifdef X86
/* special case (we don't want all of instr_is_nop() special-cased: just this one) */
if (instr_get_opcode(instr) == OP_nop_modrm)
return false;
#endif
for (i = 0; i < instr_num_srcs(instr); i++) {
if (opnd_uses_reg(instr_get_src(instr, i), reg))
return true;
}
return false;
}
/* checks regs in dest base-disp but not dest reg */
bool
instr_reads_from_reg(instr_t *instr, reg_id_t reg, dr_opnd_query_flags_t flags)
{
int i;
opnd_t opnd;
if (!TEST(DR_QUERY_INCLUDE_COND_SRCS, flags) && instr_is_predicated(instr) &&
!instr_predicate_reads_srcs(instr_get_predicate(instr)))
return false;
if (instr_reg_in_src(instr, reg))
return true;
/* As a special case, the addressing registers inside a destination memory
* operand are covered by DR_QUERY_INCLUDE_COND_SRCS rather than
* DR_QUERY_INCLUDE_COND_DSTS (i#1849).
*/
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd = instr_get_dst(instr, i);
if (!opnd_is_reg(opnd) && opnd_uses_reg(opnd, reg))
return true;
}
return false;
}
/* In this func, it must be the exact same register, not a sub reg. ie. eax!=ax */
bool
instr_reads_from_exact_reg(instr_t *instr, reg_id_t reg, dr_opnd_query_flags_t flags)
{
int i;
opnd_t opnd;
if (!TEST(DR_QUERY_INCLUDE_COND_SRCS, flags) && instr_is_predicated(instr) &&
!instr_predicate_reads_srcs(instr_get_predicate(instr)))
return false;
#ifdef X86
/* special case */
if (instr_get_opcode(instr) == OP_nop_modrm)
return false;
#endif
for (i = 0; i < instr_num_srcs(instr); i++) {
opnd = instr_get_src(instr, i);
if (opnd_is_reg(opnd) && opnd_get_reg(opnd) == reg &&
opnd_get_size(opnd) == reg_get_size(reg))
return true;
else if (opnd_is_base_disp(opnd) &&
(opnd_get_base(opnd) == reg || opnd_get_index(opnd) == reg ||
opnd_get_segment(opnd) == reg))
return true;
}
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd = instr_get_dst(instr, i);
if (opnd_is_base_disp(opnd) &&
(opnd_get_base(opnd) == reg || opnd_get_index(opnd) == reg ||
opnd_get_segment(opnd) == reg))
return true;
}
return false;
}
/* this checks sub-registers */
bool
instr_writes_to_reg(instr_t *instr, reg_id_t reg, dr_opnd_query_flags_t flags)
{
int i;
opnd_t opnd;
if (!TEST(DR_QUERY_INCLUDE_COND_DSTS, flags) && instr_is_predicated(instr))
return false;
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd = instr_get_dst(instr, i);
if (opnd_is_reg(opnd) && (dr_reg_fixer[opnd_get_reg(opnd)] == dr_reg_fixer[reg]))
return true;
}
return false;
}
/* In this func, it must be the exact same register, not a sub reg. ie. eax!=ax */
bool
instr_writes_to_exact_reg(instr_t *instr, reg_id_t reg, dr_opnd_query_flags_t flags)
{
int i;
opnd_t opnd;
if (!TEST(DR_QUERY_INCLUDE_COND_DSTS, flags) && instr_is_predicated(instr))
return false;
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd = instr_get_dst(instr, i);
if (opnd_is_reg(opnd) &&
(opnd_get_reg(opnd) == reg)
/* for case like OP_movt on ARM and SIMD regs on X86,
* partial reg written with full reg name in opnd
*/
&& opnd_get_size(opnd) == reg_get_size(reg))
return true;
}
return false;
}
bool
instr_replace_src_opnd(instr_t *instr, opnd_t old_opnd, opnd_t new_opnd)
{
int srcs, a;
srcs = instr_num_srcs(instr);
for (a = 0; a < srcs; a++) {
if (opnd_same(instr_get_src(instr, a), old_opnd) ||
opnd_same_address(instr_get_src(instr, a), old_opnd)) {
instr_set_src(instr, a, new_opnd);
return true;
}
}
return false;
}
bool
instr_replace_reg_resize(instr_t *instr, reg_id_t old_reg, reg_id_t new_reg)
{
int i;
bool found = false;
for (i = 0; i < instr_num_srcs(instr); i++) {
opnd_t opnd = instr_get_src(instr, i);
if (opnd_uses_reg(opnd, old_reg)) {
found = true;
opnd_replace_reg_resize(&opnd, old_reg, new_reg);
instr_set_src(instr, i, opnd);
}
}
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd_t opnd = instr_get_dst(instr, i);
if (opnd_uses_reg(opnd, old_reg)) {
found = true;
opnd_replace_reg_resize(&opnd, old_reg, new_reg);
instr_set_dst(instr, i, opnd);
}
}
return found;
}
bool
instr_same(instr_t *inst1, instr_t *inst2)
{
int dsts, srcs, a;
if (instr_get_opcode(inst1) != instr_get_opcode(inst2))
return false;
if ((srcs = instr_num_srcs(inst1)) != instr_num_srcs(inst2))
return false;
for (a = 0; a < srcs; a++) {
if (!opnd_same(instr_get_src(inst1, a), instr_get_src(inst2, a)))
return false;
}
if ((dsts = instr_num_dsts(inst1)) != instr_num_dsts(inst2))
return false;
for (a = 0; a < dsts; a++) {
if (!opnd_same(instr_get_dst(inst1, a), instr_get_dst(inst2, a)))
return false;
}
/* We encode some prefixes in the operands themselves, such that
* we shouldn't consider the whole-instr_t flags when considering
* equality of Instrs
*/
if ((instr_get_prefixes(inst1) & PREFIX_SIGNIFICANT) !=
(instr_get_prefixes(inst2) & PREFIX_SIGNIFICANT))
return false;
if (instr_get_isa_mode(inst1) != instr_get_isa_mode(inst2))
return false;
if (instr_get_predicate(inst1) != instr_get_predicate(inst2))
return false;
return true;
}
bool
instr_reads_memory(instr_t *instr)
{
int a;
opnd_t curop;
int opc = instr_get_opcode(instr);
if (opc_is_not_a_real_memory_load(opc))
return false;
for (a = 0; a < instr_num_srcs(instr); a++) {
curop = instr_get_src(instr, a);
if (opnd_is_memory_reference(curop)) {
return true;
}
}
return false;
}
bool
instr_writes_memory(instr_t *instr)
{
int a;
opnd_t curop;
for (a = 0; a < instr_num_dsts(instr); a++) {
curop = instr_get_dst(instr, a);
if (opnd_is_memory_reference(curop)) {
return true;
}
}
return false;
}
#ifdef X86
bool
instr_zeroes_ymmh(instr_t *instr)
{
int i;
const instr_info_t *info = get_encoding_info(instr);
if (info == NULL)
return false;
/* Legacy (SSE) instructions always preserve top half of YMM.
* Moreover, EVEX encoded instructions clear upper ZMM bits, but also
* YMM bits if an XMM reg is used.
*/
if (!TEST(REQUIRES_VEX, info->flags) && !TEST(REQUIRES_EVEX, info->flags))
return false;
/* Handle zeroall special case. */
if (instr->opcode == OP_vzeroall)
return true;
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd_t opnd = instr_get_dst(instr, i);
if (opnd_is_reg(opnd) && reg_is_vector_simd(opnd_get_reg(opnd)) &&
reg_is_strictly_xmm(opnd_get_reg(opnd)))
return true;
}
return false;
}
bool
instr_zeroes_zmmh(instr_t *instr)
{
int i;
const instr_info_t *info = get_encoding_info(instr);
if (info == NULL)
return false;
if (!TEST(REQUIRES_VEX, info->flags) && !TEST(REQUIRES_EVEX, info->flags))
return false;
/* Handle special cases, namely zeroupper and zeroall. */
/* XXX: DR ir should actually have these two instructions have all SIMD vector regs
* as operand even though they are implicit.
*/
if (instr->opcode == OP_vzeroall || instr->opcode == OP_vzeroupper)
return true;
for (i = 0; i < instr_num_dsts(instr); i++) {
opnd_t opnd = instr_get_dst(instr, i);
if (opnd_is_reg(opnd) && reg_is_vector_simd(opnd_get_reg(opnd)) &&
(reg_is_strictly_xmm(opnd_get_reg(opnd)) ||
reg_is_strictly_ymm(opnd_get_reg(opnd))))
return true;
}
return false;
}
bool
instr_is_xsave(instr_t *instr)
{
int opcode = instr_get_opcode(instr); /* force decode */
if (opcode == OP_xsave32 || opcode == OP_xsaveopt32 || opcode == OP_xsave64 ||
opcode == OP_xsaveopt64 || opcode == OP_xsavec32 || opcode == OP_xsavec64)
return true;
return false;
}
#endif /* X86 */
/* PR 251479: support general re-relativization. If INSTR_RIP_REL_VALID is set and
* the raw bits are valid, instr->rip_rel_pos is assumed to hold the offset into the
* instr of a 32-bit rip-relative displacement, which is used to re-relativize during
* encoding. We only use this for level 1-3 instrs, and we invalidate it if the raw
* bits are modified at all.
* For caching the encoded bytes of a Level 4 instr, instr_encode() sets
* the rip_rel_pos field and flag without setting the raw bits valid:
* private_instr_encode() then sets the raw bits, after examing the rip rel flag
* by itself. Thus, we must invalidate the rip rel flag when we invalidate
* raw bits: we can't rely just on the raw bits invalidation.
* There can only be one rip-relative operand per instruction.
*/
/* TODO i#4016: for AArchXX we don't have a large displacement on every reference.
* Some have no disp at all, others have just 12 bits or smaller.
* We need to come up with a strategy for handling encode-time re-relativization.
* Xref copy_and_re_relativize_raw_instr().
* For now, we do use some of these routines, but none that use the rip_rel_pos.
*/
#ifdef X86
bool
instr_rip_rel_valid(instr_t *instr)
{
return instr_raw_bits_valid(instr) && TEST(INSTR_RIP_REL_VALID, instr->flags);
}
void
instr_set_rip_rel_valid(instr_t *instr, bool valid)
{
if (valid)
instr->flags |= INSTR_RIP_REL_VALID;
else
instr->flags &= ~INSTR_RIP_REL_VALID;
}
uint
instr_get_rip_rel_pos(instr_t *instr)
{
return instr->rip_rel_pos;
}
void
instr_set_rip_rel_pos(instr_t *instr, uint pos)
{
CLIENT_ASSERT_TRUNCATE(instr->rip_rel_pos, byte, pos,
"instr_set_rip_rel_pos: offs must be <= 256");
instr->rip_rel_pos = (byte)pos;
instr_set_rip_rel_valid(instr, true);
}
#endif /* X86 */
#ifdef X86
static bool
instr_has_rip_rel_instr_operand(instr_t *instr)
{
/* XXX: See comment in instr_get_rel_target() about distinguishing data from
* instr rip-rel operands. We don't want to go so far as adding yet more
* data plumbed through the decode_fast tables.
* Perhaps we should instead break compatibility and have all these relative
* target and operand index routines include instr operands, and update
* mangle_rel_addr() to somehow distinguish instr on its own?
* For now we get by with the simple check for a cti or xbegin.
* No instruction has 2 rip-rel immeds so a direct cti must be instr.
*/
return (instr_is_cti(instr) && !instr_is_mbr(instr)) ||
instr_get_opcode(instr) == OP_xbegin;
}
#endif
bool
instr_get_rel_target(instr_t *instr, /*OUT*/ app_pc *target, bool data_only)
{
if (!instr_valid(instr))
return false;
/* For PC operands we have to look at the high-level *before* rip_rel_pos, to
* support decode_from_copy(). As documented, we ignore instr_t targets.
*/
if (!data_only && instr_operands_valid(instr) && instr_num_srcs(instr) > 0 &&
opnd_is_pc(instr_get_src(instr, 0))) {
if (target != NULL)
*target = opnd_get_pc(instr_get_src(instr, 0));
return true;
}
#ifdef X86
/* PR 251479: we support rip-rel info in level 1 instrs */
if (instr_rip_rel_valid(instr)) {
int rip_rel_pos = instr_get_rip_rel_pos(instr);
if (rip_rel_pos > 0) {
if (data_only) {
/* XXX: Distinguishing data from instr is a pain here b/c it might be
* during init (e.g., callback.c's copy_app_code()) and we can't
* easily do an up-decode (hence the separate "local" instr_t below).
* We do it partly for backward compatibility for external callers,
* but also for our own mangle_rel_addr(). Would it be cleaner some
* other way: breaking compat and not supporting data-only here and
* having mangle call instr_set_rip_rel_valid() for all cti's (and
* xbegin)?
*/
bool not_data = false;
if (!instr_opcode_valid(instr) && get_thread_private_dcontext() == NULL) {
instr_t local;
instr_init(GLOBAL_DCONTEXT, &local);
if (decode_opcode(GLOBAL_DCONTEXT, instr_get_raw_bits(instr),
&local) != NULL) {
not_data = instr_has_rip_rel_instr_operand(&local);
}
instr_free(GLOBAL_DCONTEXT, &local);
} else
not_data = instr_has_rip_rel_instr_operand(instr);
if (not_data)
return false;
}
if (target != NULL) {
/* We only support non-4-byte rip-rel disps for 1-byte instr-final
* (jcc_short).
*/
if (rip_rel_pos + 1 == (int)instr->length) {
*target = instr->bytes + instr->length +
*((char *)(instr->bytes + rip_rel_pos));
} else {
ASSERT(rip_rel_pos + 4 <= (int)instr->length);
*target = instr->bytes + instr->length +
*((int *)(instr->bytes + rip_rel_pos));
}
}
return true;
} else
return false;
}
#endif
#if defined(X64) || defined(ARM)
int i;
opnd_t curop;
/* else go to level 3 operands */
for (i = 0; i < instr_num_dsts(instr); i++) {
curop = instr_get_dst(instr, i);
IF_ARM_ELSE(
{
/* DR_REG_PC as an index register is not allowed */
if (opnd_is_base_disp(curop) && opnd_get_base(curop) == DR_REG_PC) {
if (target != NULL) {
*target = opnd_get_disp(curop) +
decode_cur_pc(instr_get_app_pc(instr),
instr_get_isa_mode(instr),
instr_get_opcode(instr), instr);
}
return true;
}
},
{
if (opnd_is_rel_addr(curop)) {
if (target != NULL)
*target = opnd_get_addr(curop);
return true;
}
});
}
for (i = 0; i < instr_num_srcs(instr); i++) {
curop = instr_get_src(instr, i);
IF_ARM_ELSE(
{
/* DR_REG_PC as an index register is not allowed */
if (opnd_is_base_disp(curop) && opnd_get_base(curop) == DR_REG_PC) {
if (target != NULL) {
*target = opnd_get_disp(curop) +
decode_cur_pc(instr_get_app_pc(instr),
instr_get_isa_mode(instr),
instr_get_opcode(instr), instr);
}
return true;
}
},
{
if (opnd_is_rel_addr(curop)) {
if (target != NULL)
*target = opnd_get_addr(curop);
return true;
}
});
}
#endif
return false;
}
bool
instr_get_rel_data_or_instr_target(instr_t *instr, /*OUT*/ app_pc *target)
{
return instr_get_rel_target(instr, target, false /*all*/);
}
#if defined(X64) || defined(ARM)
bool
instr_get_rel_addr_target(instr_t *instr, /*OUT*/ app_pc *target)
{
return instr_get_rel_target(instr, target, true /*data-only*/);
}
bool
instr_has_rel_addr_reference(instr_t *instr)
{
return instr_get_rel_addr_target(instr, NULL);
}
int
instr_get_rel_addr_dst_idx(instr_t *instr)
{
int i;
opnd_t curop;
if (!instr_valid(instr))
return -1;
/* must go to level 3 operands */
for (i = 0; i < instr_num_dsts(instr); i++) {
curop = instr_get_dst(instr, i);
IF_ARM_ELSE(
{
if (opnd_is_base_disp(curop) && opnd_get_base(curop) == DR_REG_PC)
return i;
},
{
if (opnd_is_rel_addr(curop))
return i;
});
}
return -1;
}
int
instr_get_rel_addr_src_idx(instr_t *instr)
{
int i;
opnd_t curop;
if (!instr_valid(instr))
return -1;
/* must go to level 3 operands */
for (i = 0; i < instr_num_srcs(instr); i++) {
curop = instr_get_src(instr, i);
IF_ARM_ELSE(
{
if (opnd_is_base_disp(curop) && opnd_get_base(curop) == DR_REG_PC)
return i;
},
{
if (opnd_is_rel_addr(curop))
return i;
});
}
return -1;
}
#endif /* X64 || ARM */
bool
instr_is_our_mangling(instr_t *instr)
{
return TEST(INSTR_OUR_MANGLING, instr->flags);
}
void
instr_set_our_mangling(instr_t *instr, bool ours)
{
if (ours)
instr->flags |= INSTR_OUR_MANGLING;
else
instr->flags &= ~INSTR_OUR_MANGLING;
}
bool
instr_is_our_mangling_epilogue(instr_t *instr)
{
ASSERT(!TEST(INSTR_OUR_MANGLING_EPILOGUE, instr->flags) ||
instr_is_our_mangling(instr));
return TEST(INSTR_OUR_MANGLING_EPILOGUE, instr->flags);
}
void
instr_set_our_mangling_epilogue(instr_t *instr, bool epilogue)
{
if (epilogue) {
instr->flags |= INSTR_OUR_MANGLING_EPILOGUE;
} else
instr->flags &= ~INSTR_OUR_MANGLING_EPILOGUE;
}
instr_t *
instr_set_translation_mangling_epilogue(dcontext_t *dcontext, instrlist_t *ilist,
instr_t *instr)
{
if (instrlist_get_translation_target(ilist) != NULL) {
int sz = decode_sizeof(dcontext, instrlist_get_translation_target(ilist),
NULL _IF_X86_64(NULL));
instr_set_translation(instr, instrlist_get_translation_target(ilist) + sz);
}
instr_set_our_mangling_epilogue(instr, true);
return instr;
}
/* Emulates instruction to find the address of the index-th memory operand.
* Either or both OUT variables can be NULL.
*/
static bool
instr_compute_address_helper(instr_t *instr, priv_mcontext_t *mc, size_t mc_size,
dr_mcontext_flags_t mc_flags, uint index, OUT app_pc *addr,
OUT bool *is_write, OUT uint *pos)
{
/* for string instr, even w/ rep prefix, assume want value at point of
* register snapshot passed in
*/
int i;
opnd_t curop = { 0 };
int memcount = -1;
bool write = false;
bool have_addr = false;
/* We allow not selecting xmm fields since clients may legitimately
* emulate a memref w/ just GPRs
*/
CLIENT_ASSERT(TESTALL(DR_MC_CONTROL | DR_MC_INTEGER, mc_flags),
"dr_mcontext_t.flags must include DR_MC_CONTROL and DR_MC_INTEGER");
for (i = 0; i < instr_num_dsts(instr); i++) {
curop = instr_get_dst(instr, i);
if (opnd_is_memory_reference(curop)) {
if (opnd_is_vsib(curop)) {
#ifdef X86
if (instr_compute_address_VSIB(instr, mc, mc_size, mc_flags, curop, index,
&have_addr, addr, &write)) {
CLIENT_ASSERT(
write,
"VSIB found in destination but instruction is not a scatter");
break;
} else {
return false;
}
#else
CLIENT_ASSERT(false, "VSIB should be x86-only");
#endif
}
memcount++;
if (memcount == (int)index) {
write = true;
break;
}
}
}
if (!write && memcount != (int)index &&
/* lea has a mem_ref source operand, but doesn't actually read */
!opc_is_not_a_real_memory_load(instr_get_opcode(instr))) {
for (i = 0; i < instr_num_srcs(instr); i++) {
curop = instr_get_src(instr, i);
if (opnd_is_memory_reference(curop)) {
if (opnd_is_vsib(curop)) {
#ifdef X86
if (instr_compute_address_VSIB(instr, mc, mc_size, mc_flags, curop,
index, &have_addr, addr, &write))
break;
else
return false;
#else
CLIENT_ASSERT(false, "VSIB should be x86-only");
#endif
}
memcount++;
if (memcount == (int)index)
break;
}
}
}
if (!have_addr) {
if (memcount != (int)index)
return false;
if (addr != NULL)
*addr = opnd_compute_address_priv(curop, mc);
}
if (is_write != NULL)
*is_write = write;
if (pos != 0)
*pos = i;
return true;
}
bool
instr_compute_address_ex_priv(instr_t *instr, priv_mcontext_t *mc, uint index,
OUT app_pc *addr, OUT bool *is_write, OUT uint *pos)
{
return instr_compute_address_helper(instr, mc, sizeof(*mc), DR_MC_ALL, index, addr,
is_write, pos);
}
DR_API
bool
instr_compute_address_ex(instr_t *instr, dr_mcontext_t *mc, uint index, OUT app_pc *addr,
OUT bool *is_write)
{
return instr_compute_address_helper(instr, dr_mcontext_as_priv_mcontext(mc), mc->size,
mc->flags, index, addr, is_write, NULL);
}
/* i#682: add pos so that the caller knows which opnd is used. */
DR_API
bool
instr_compute_address_ex_pos(instr_t *instr, dr_mcontext_t *mc, uint index,
OUT app_pc *addr, OUT bool *is_write, OUT uint *pos)
{
return instr_compute_address_helper(instr, dr_mcontext_as_priv_mcontext(mc), mc->size,
mc->flags, index, addr, is_write, pos);
}
/* Returns NULL if none of instr's operands is a memory reference.
* Otherwise, returns the effective address of the first memory operand
* when the operands are considered in this order: destinations and then
* sources. The address is computed using the passed-in registers.
*/
app_pc
instr_compute_address_priv(instr_t *instr, priv_mcontext_t *mc)
{
app_pc addr;
if (!instr_compute_address_ex_priv(instr, mc, 0, &addr, NULL, NULL))
return NULL;
return addr;
}
DR_API
app_pc
instr_compute_address(instr_t *instr, dr_mcontext_t *mc)
{
app_pc addr;
if (!instr_compute_address_ex(instr, mc, 0, &addr, NULL))
return NULL;
return addr;
}
/* Calculates the size, in bytes, of the memory read or write of instr
* If instr does not reference memory, or is invalid, returns 0
*/
uint
instr_memory_reference_size(instr_t *instr)
{
int i;
if (!instr_valid(instr))
return 0;
for (i = 0; i < instr_num_dsts(instr); i++) {
if (opnd_is_memory_reference(instr_get_dst(instr, i))) {
return opnd_size_in_bytes(opnd_get_size(instr_get_dst(instr, i)));
}
}
for (i = 0; i < instr_num_srcs(instr); i++) {
if (opnd_is_memory_reference(instr_get_src(instr, i))) {
return opnd_size_in_bytes(opnd_get_size(instr_get_src(instr, i)));
}
}
return 0;
}
/* Calculates the size, in bytes, of the memory read or write of
* the instr at pc.
* Returns the pc of the following instr.
* If the instr at pc does not reference memory, or is invalid,
* returns NULL.
*/
app_pc
decode_memory_reference_size(void *drcontext, app_pc pc, uint *size_in_bytes)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
app_pc next_pc;
instr_t instr;
instr_init(dcontext, &instr);
next_pc = decode(dcontext, pc, &instr);
if (!instr_valid(&instr))
return NULL;
CLIENT_ASSERT(size_in_bytes != NULL, "decode_memory_reference_size: passed NULL");
*size_in_bytes = instr_memory_reference_size(&instr);
instr_free(dcontext, &instr);
return next_pc;
}
DR_API
dr_instr_label_data_t *
instr_get_label_data_area(instr_t *instr)
{
CLIENT_ASSERT(instr != NULL, "invalid arg");
if (instr_is_label(instr))
return &instr->label_data;
else
return NULL;
}
DR_API
/* return the taken target pc of the (direct branch) inst */
app_pc
instr_get_branch_target_pc(instr_t *cti_instr)
{
CLIENT_ASSERT(opnd_is_pc(instr_get_target(cti_instr)),
"instr_branch_target_pc: target not pc");
return opnd_get_pc(instr_get_target(cti_instr));
}
DR_API
/* set the taken target pc of the (direct branch) inst */
void
instr_set_branch_target_pc(instr_t *cti_instr, app_pc pc)
{
opnd_t op = opnd_create_pc(pc);
instr_set_target(cti_instr, op);
}
bool
instr_is_call(instr_t *instr)
{
instr_get_opcode(instr); /* force decode */
return instr_is_call_arch(instr);
}
bool
instr_is_cbr(instr_t *instr)
{
instr_get_opcode(instr); /* force decode */
return instr_is_cbr_arch(instr);
}
bool
instr_is_mbr(instr_t *instr)
{
instr_get_opcode(instr); /* force decode */
return instr_is_mbr_arch(instr);
}
bool
instr_is_ubr(instr_t *instr)
{
instr_get_opcode(instr); /* force decode */
return instr_is_ubr_arch(instr);
}
/* An exit CTI is a control-transfer instruction whose target
* is a pc (and not an instr_t pointer). This routine assumes
* that no other input operands exist in a CTI.
* An undecoded instr cannot be an exit cti.
* This routine does NOT try to decode an opcode in a Level 1 or Level
* 0 routine, and can thus be called on Level 0 routines.
*/
bool
instr_is_exit_cti(instr_t *instr)
{
if (!instr_operands_valid(instr) || /* implies !opcode_valid */
instr_is_meta(instr))
return false;
/* The _arch versions assume the opcode is already valid, avoiding
* the conditional decode in instr_get_opcode().
*/
if (instr_is_ubr_arch(instr) || instr_is_cbr_arch(instr)) {
/* far pc should only happen for mangle's call to here */
return opnd_is_pc(instr_get_target(instr));
}
return false;
}
bool
instr_is_cti(instr_t *instr) /* any control-transfer instruction */
{
instr_get_opcode(instr); /* force opcode decode, just once */
return (instr_is_cbr_arch(instr) || instr_is_ubr_arch(instr) ||
instr_is_mbr_arch(instr) || instr_is_call_arch(instr));
}
int
instr_get_interrupt_number(instr_t *instr)
{
CLIENT_ASSERT(instr_get_opcode(instr) == IF_X86_ELSE(OP_int, OP_svc),
"instr_get_interrupt_number: instr not interrupt");
if (instr_operands_valid(instr)) {
ptr_int_t val = opnd_get_immed_int(instr_get_src(instr, 0));
/* undo the sign extension. prob return value shouldn't be signed but
* too late to bother changing that.
*/
CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_sbyte(val), "invalid interrupt number");
return (int)(byte)val;
} else if (instr_raw_bits_valid(instr)) {
/* widen as unsigned */
return (int)(uint)instr_get_raw_byte(instr, 1);
} else {
CLIENT_ASSERT(false, "instr_get_interrupt_number: invalid instr");
return 0;
}
}
/* Returns true iff instr is a label meta-instruction */
bool
instr_is_label(instr_t *instr)
{
return instr_opcode_valid(instr) && instr_get_opcode(instr) == OP_LABEL;
}
bool
instr_uses_fp_reg(instr_t *instr)
{
int a;
opnd_t curop;
for (a = 0; a < instr_num_dsts(instr); a++) {
curop = instr_get_dst(instr, a);
if (opnd_is_reg(curop) && reg_is_fp(opnd_get_reg(curop)))
return true;
else if (opnd_is_memory_reference(curop)) {
if (reg_is_fp(opnd_get_base(curop)))
return true;
else if (reg_is_fp(opnd_get_index(curop)))
return true;
}
}
for (a = 0; a < instr_num_srcs(instr); a++) {
curop = instr_get_src(instr, a);
if (opnd_is_reg(curop) && reg_is_fp(opnd_get_reg(curop)))
return true;
else if (opnd_is_memory_reference(curop)) {
if (reg_is_fp(opnd_get_base(curop)))
return true;
else if (reg_is_fp(opnd_get_index(curop)))
return true;
}
}
return false;
}
/* We place these here rather than in mangle_shared.c to avoid the work of
* linking mangle_shared.c into drdecodelib.
*/
instr_t *
convert_to_near_rel_meta(dcontext_t *dcontext, instrlist_t *ilist, instr_t *instr)
{
return convert_to_near_rel_arch(dcontext, ilist, instr);
}
void
convert_to_near_rel(dcontext_t *dcontext, instr_t *instr)
{
convert_to_near_rel_arch(dcontext, NULL, instr);
}
instr_t *
instr_convert_short_meta_jmp_to_long(void *drcontext, instrlist_t *ilist, instr_t *instr)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
/* PR 266292: we convert to a sequence of separate meta instrs for jecxz, etc. */
CLIENT_ASSERT(instr_is_meta(instr),
"instr_convert_short_meta_jmp_to_long: instr is not meta");
CLIENT_ASSERT(instr_is_cti_short(instr),
"instr_convert_short_meta_jmp_to_long: instr is not a short cti");
if (instr_is_app(instr) || !instr_is_cti_short(instr))
return instr;
return convert_to_near_rel_meta(dcontext, ilist, instr);
}
/***********************************************************************
* instr_t creation routines
* To use 16-bit data sizes, must call set_prefix after creating instr
* To support this, all relevant registers must be of eAX form!
* FIXME: how do that?
* will an all-operand replacement work, or do some instrs have some
* var-size regs but some const-size also?
*
* XXX: what if want eflags or modrm info on constructed instr?!?
*
* fld pushes onto top of stack, call that writing to ST0 or ST7?
* f*p pops the stack -- not modeled at all!
* should floating point constants be doubles, not floats?!?
*
* opcode complaints:
* OP_imm vs. OP_st
* OP_ret: build routines have to separate ret_imm and ret_far_imm
* others, see FIXME's in instr_create_api.h
*/
instr_t *
instr_create_0dst_0src(void *drcontext, int opcode)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 0, 0);
return in;
}
instr_t *
instr_create_0dst_1src(void *drcontext, int opcode, opnd_t src)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 0, 1);
instr_set_src(in, 0, src);
return in;
}
instr_t *
instr_create_0dst_2src(void *drcontext, int opcode, opnd_t src1, opnd_t src2)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 0, 2);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
return in;
}
instr_t *
instr_create_0dst_3src(void *drcontext, int opcode, opnd_t src1, opnd_t src2, opnd_t src3)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 0, 3);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
return in;
}
instr_t *
instr_create_0dst_4src(void *drcontext, int opcode, opnd_t src1, opnd_t src2, opnd_t src3,
opnd_t src4)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 0, 4);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
return in;
}
instr_t *
instr_create_1dst_0src(void *drcontext, int opcode, opnd_t dst)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 1, 0);
instr_set_dst(in, 0, dst);
return in;
}
instr_t *
instr_create_1dst_1src(void *drcontext, int opcode, opnd_t dst, opnd_t src)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 1, 1);
instr_set_dst(in, 0, dst);
instr_set_src(in, 0, src);
return in;
}
instr_t *
instr_create_1dst_2src(void *drcontext, int opcode, opnd_t dst, opnd_t src1, opnd_t src2)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 1, 2);
instr_set_dst(in, 0, dst);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
return in;
}
instr_t *
instr_create_1dst_3src(void *drcontext, int opcode, opnd_t dst, opnd_t src1, opnd_t src2,
opnd_t src3)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 1, 3);
instr_set_dst(in, 0, dst);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
return in;
}
instr_t *
instr_create_1dst_4src(void *drcontext, int opcode, opnd_t dst, opnd_t src1, opnd_t src2,
opnd_t src3, opnd_t src4)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 1, 4);
instr_set_dst(in, 0, dst);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
return in;
}
instr_t *
instr_create_1dst_5src(void *drcontext, int opcode, opnd_t dst, opnd_t src1, opnd_t src2,
opnd_t src3, opnd_t src4, opnd_t src5)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 1, 5);
instr_set_dst(in, 0, dst);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
instr_set_src(in, 4, src5);
return in;
}
instr_t *
instr_create_2dst_0src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 2, 0);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
return in;
}
instr_t *
instr_create_2dst_1src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t src)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 2, 1);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_src(in, 0, src);
return in;
}
instr_t *
instr_create_2dst_2src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t src1,
opnd_t src2)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 2, 2);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
return in;
}
instr_t *
instr_create_2dst_3src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t src1,
opnd_t src2, opnd_t src3)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 2, 3);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
return in;
}
instr_t *
instr_create_2dst_4src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t src1,
opnd_t src2, opnd_t src3, opnd_t src4)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 2, 4);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
return in;
}
instr_t *
instr_create_2dst_5src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t src1,
opnd_t src2, opnd_t src3, opnd_t src4, opnd_t src5)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 2, 5);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
instr_set_src(in, 4, src5);
return in;
}
instr_t *
instr_create_3dst_0src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 3, 0);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
return in;
}
instr_t *
instr_create_3dst_1src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t src1)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 3, 1);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_src(in, 0, src1);
return in;
}
instr_t *
instr_create_3dst_2src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t src1, opnd_t src2)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 3, 2);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
return in;
}
instr_t *
instr_create_3dst_3src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t src1, opnd_t src2, opnd_t src3)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 3, 3);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
return in;
}
instr_t *
instr_create_3dst_4src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t src1, opnd_t src2, opnd_t src3, opnd_t src4)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 3, 4);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
return in;
}
instr_t *
instr_create_3dst_5src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t src1, opnd_t src2, opnd_t src3, opnd_t src4, opnd_t src5)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 3, 5);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
instr_set_src(in, 4, src5);
return in;
}
instr_t *
instr_create_3dst_6src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t src1, opnd_t src2, opnd_t src3, opnd_t src4, opnd_t src5,
opnd_t src6)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 3, 6);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
instr_set_src(in, 4, src5);
instr_set_src(in, 5, src6);
return in;
}
instr_t *
instr_create_4dst_1src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t src)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 4, 1);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_src(in, 0, src);
return in;
}
instr_t *
instr_create_4dst_2src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t src1, opnd_t src2)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 4, 2);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
return in;
}
instr_t *
instr_create_4dst_3src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t src1, opnd_t src2, opnd_t src3)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 4, 3);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
return in;
}
instr_t *
instr_create_4dst_4src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t src1, opnd_t src2, opnd_t src3, opnd_t src4)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 4, 4);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
return in;
}
instr_t *
instr_create_4dst_7src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t src1, opnd_t src2, opnd_t src3, opnd_t src4,
opnd_t src5, opnd_t src6, opnd_t src7)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 4, 7);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
instr_set_src(in, 4, src5);
instr_set_src(in, 5, src6);
instr_set_src(in, 6, src7);
return in;
}
instr_t *
instr_create_5dst_3src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t dst5, opnd_t src1, opnd_t src2, opnd_t src3)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 5, 3);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_dst(in, 4, dst5);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
return in;
}
instr_t *
instr_create_5dst_4src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t dst5, opnd_t src1, opnd_t src2, opnd_t src3,
opnd_t src4)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 5, 4);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_dst(in, 4, dst5);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
return in;
}
instr_t *
instr_create_5dst_8src(void *drcontext, int opcode, opnd_t dst1, opnd_t dst2, opnd_t dst3,
opnd_t dst4, opnd_t dst5, opnd_t src1, opnd_t src2, opnd_t src3,
opnd_t src4, opnd_t src5, opnd_t src6, opnd_t src7, opnd_t src8)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
instr_t *in = instr_build(dcontext, opcode, 5, 8);
instr_set_dst(in, 0, dst1);
instr_set_dst(in, 1, dst2);
instr_set_dst(in, 2, dst3);
instr_set_dst(in, 3, dst4);
instr_set_dst(in, 4, dst5);
instr_set_src(in, 0, src1);
instr_set_src(in, 1, src2);
instr_set_src(in, 2, src3);
instr_set_src(in, 3, src4);
instr_set_src(in, 4, src5);
instr_set_src(in, 5, src6);
instr_set_src(in, 6, src7);
instr_set_src(in, 7, src8);
return in;
}
instr_t *
instr_create_Ndst_Msrc_varsrc(void *drcontext, int opcode, uint fixed_dsts,
uint fixed_srcs, uint var_srcs, uint var_ord, ...)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
va_list ap;
instr_t *in = instr_build(dcontext, opcode, fixed_dsts, fixed_srcs + var_srcs);
uint i;
reg_id_t prev_reg = REG_NULL;
bool check_order;
va_start(ap, var_ord);
for (i = 0; i < fixed_dsts; i++)
instr_set_dst(in, i, va_arg(ap, opnd_t));
for (i = 0; i < MIN(var_ord, fixed_srcs); i++)
instr_set_src(in, i, va_arg(ap, opnd_t));
for (i = var_ord; i < fixed_srcs; i++)
instr_set_src(in, var_srcs + i, va_arg(ap, opnd_t));
/* we require regs in reglist are stored in order for easy split if necessary */
check_order = IF_ARM_ELSE(true, false);
for (i = 0; i < var_srcs; i++) {
opnd_t opnd = va_arg(ap, opnd_t);
/* assuming non-reg opnds (if any) are in the fixed positon */
CLIENT_ASSERT(!check_order ||
(opnd_is_reg(opnd) && opnd_get_reg(opnd) > prev_reg),
"instr_create_Ndst_Msrc_varsrc: wrong register order in reglist");
instr_set_src(in, var_ord + i, opnd_add_flags(opnd, DR_OPND_IN_LIST));
if (check_order)
prev_reg = opnd_get_reg(opnd);
}
va_end(ap);
return in;
}
instr_t *
instr_create_Ndst_Msrc_vardst(void *drcontext, int opcode, uint fixed_dsts,
uint fixed_srcs, uint var_dsts, uint var_ord, ...)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
va_list ap;
instr_t *in = instr_build(dcontext, opcode, fixed_dsts + var_dsts, fixed_srcs);
uint i;
reg_id_t prev_reg = REG_NULL;
bool check_order;
va_start(ap, var_ord);
for (i = 0; i < MIN(var_ord, fixed_dsts); i++)
instr_set_dst(in, i, va_arg(ap, opnd_t));
for (i = var_ord; i < fixed_dsts; i++)
instr_set_dst(in, var_dsts + i, va_arg(ap, opnd_t));
for (i = 0; i < fixed_srcs; i++)
instr_set_src(in, i, va_arg(ap, opnd_t));
/* we require regs in reglist are stored in order for easy split if necessary */
check_order = IF_ARM_ELSE(true, false);
for (i = 0; i < var_dsts; i++) {
opnd_t opnd = va_arg(ap, opnd_t);
/* assuming non-reg opnds (if any) are in the fixed positon */
CLIENT_ASSERT(!check_order ||
(opnd_is_reg(opnd) && opnd_get_reg(opnd) > prev_reg),
"instr_create_Ndst_Msrc_vardst: wrong register order in reglist");
instr_set_dst(in, var_ord + i, opnd_add_flags(opnd, DR_OPND_IN_LIST));
if (check_order)
prev_reg = opnd_get_reg(opnd);
}
va_end(ap);
return in;
}
/****************************************************************************/
/* build instructions from raw bits
* convention: give them OP_UNDECODED opcodes
*/
instr_t *
instr_create_raw_1byte(dcontext_t *dcontext, byte byte1)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 1);
instr_set_raw_byte(in, 0, byte1);
return in;
}
instr_t *
instr_create_raw_2bytes(dcontext_t *dcontext, byte byte1, byte byte2)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 2);
instr_set_raw_byte(in, 0, byte1);
instr_set_raw_byte(in, 1, byte2);
return in;
}
instr_t *
instr_create_raw_3bytes(dcontext_t *dcontext, byte byte1, byte byte2, byte byte3)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 3);
instr_set_raw_byte(in, 0, byte1);
instr_set_raw_byte(in, 1, byte2);
instr_set_raw_byte(in, 2, byte3);
return in;
}
instr_t *
instr_create_raw_4bytes(dcontext_t *dcontext, byte byte1, byte byte2, byte byte3,
byte byte4)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 4);
instr_set_raw_byte(in, 0, byte1);
instr_set_raw_byte(in, 1, byte2);
instr_set_raw_byte(in, 2, byte3);
instr_set_raw_byte(in, 3, byte4);
return in;
}
instr_t *
instr_create_raw_5bytes(dcontext_t *dcontext, byte byte1, byte byte2, byte byte3,
byte byte4, byte byte5)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 5);
instr_set_raw_byte(in, 0, byte1);
instr_set_raw_byte(in, 1, byte2);
instr_set_raw_byte(in, 2, byte3);
instr_set_raw_byte(in, 3, byte4);
instr_set_raw_byte(in, 4, byte5);
return in;
}
instr_t *
instr_create_raw_6bytes(dcontext_t *dcontext, byte byte1, byte byte2, byte byte3,
byte byte4, byte byte5, byte byte6)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 6);
instr_set_raw_byte(in, 0, byte1);
instr_set_raw_byte(in, 1, byte2);
instr_set_raw_byte(in, 2, byte3);
instr_set_raw_byte(in, 3, byte4);
instr_set_raw_byte(in, 4, byte5);
instr_set_raw_byte(in, 5, byte6);
return in;
}
instr_t *
instr_create_raw_7bytes(dcontext_t *dcontext, byte byte1, byte byte2, byte byte3,
byte byte4, byte byte5, byte byte6, byte byte7)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 7);
instr_set_raw_byte(in, 0, byte1);
instr_set_raw_byte(in, 1, byte2);
instr_set_raw_byte(in, 2, byte3);
instr_set_raw_byte(in, 3, byte4);
instr_set_raw_byte(in, 4, byte5);
instr_set_raw_byte(in, 5, byte6);
instr_set_raw_byte(in, 6, byte7);
return in;
}
instr_t *
instr_create_raw_8bytes(dcontext_t *dcontext, byte byte1, byte byte2, byte byte3,
byte byte4, byte byte5, byte byte6, byte byte7, byte byte8)
{
instr_t *in = instr_build_bits(dcontext, OP_UNDECODED, 8);
instr_set_raw_byte(in, 0, byte1);
instr_set_raw_byte(in, 1, byte2);
instr_set_raw_byte(in, 2, byte3);
instr_set_raw_byte(in, 3, byte4);
instr_set_raw_byte(in, 4, byte5);
instr_set_raw_byte(in, 5, byte6);
instr_set_raw_byte(in, 6, byte7);
instr_set_raw_byte(in, 7, byte8);
return in;
}
#ifndef STANDALONE_DECODER
/****************************************************************************/
/* dcontext convenience routines */
instr_t *
instr_create_restore_from_dcontext(dcontext_t *dcontext, reg_id_t reg, int offs)
{
opnd_t memopnd = opnd_create_dcontext_field(dcontext, offs);
/* use movd for xmm/mmx */
if (reg_is_xmm(reg) || reg_is_mmx(reg))
return XINST_CREATE_load_simd(dcontext, opnd_create_reg(reg), memopnd);
else
return XINST_CREATE_load(dcontext, opnd_create_reg(reg), memopnd);
}
instr_t *
instr_create_save_to_dcontext(dcontext_t *dcontext, reg_id_t reg, int offs)
{
opnd_t memopnd = opnd_create_dcontext_field(dcontext, offs);
CLIENT_ASSERT(dcontext != GLOBAL_DCONTEXT,
"instr_create_save_to_dcontext: invalid dcontext");
/* use movd for xmm/mmx */
if (reg_is_xmm(reg) || reg_is_mmx(reg))
return XINST_CREATE_store_simd(dcontext, memopnd, opnd_create_reg(reg));
else
return XINST_CREATE_store(dcontext, memopnd, opnd_create_reg(reg));
}
/* Use basereg==REG_NULL to get default (xdi, or xsi for upcontext)
* Auto-magically picks the mem opnd size to match reg if it's a GPR.
*/
instr_t *
instr_create_restore_from_dc_via_reg(dcontext_t *dcontext, reg_id_t basereg, reg_id_t reg,
int offs)
{
/* use movd for xmm/mmx, and OPSZ_PTR */
if (reg_is_xmm(reg) || reg_is_mmx(reg)) {
opnd_t memopnd = opnd_create_dcontext_field_via_reg(dcontext, basereg, offs);
return XINST_CREATE_load_simd(dcontext, opnd_create_reg(reg), memopnd);
} else {
opnd_t memopnd = opnd_create_dcontext_field_via_reg_sz(dcontext, basereg, offs,
reg_get_size(reg));
return XINST_CREATE_load(dcontext, opnd_create_reg(reg), memopnd);
}
}
/* Use basereg==REG_NULL to get default (xdi, or xsi for upcontext)
* Auto-magically picks the mem opnd size to match reg if it's a GPR.
*/
instr_t *
instr_create_save_to_dc_via_reg(dcontext_t *dcontext, reg_id_t basereg, reg_id_t reg,
int offs)
{
/* use movd for xmm/mmx, and OPSZ_PTR */
if (reg_is_xmm(reg) || reg_is_mmx(reg)) {
opnd_t memopnd = opnd_create_dcontext_field_via_reg(dcontext, basereg, offs);
return XINST_CREATE_store_simd(dcontext, memopnd, opnd_create_reg(reg));
} else {
opnd_t memopnd = opnd_create_dcontext_field_via_reg_sz(dcontext, basereg, offs,
reg_get_size(reg));
return XINST_CREATE_store(dcontext, memopnd, opnd_create_reg(reg));
}
}
static instr_t *
instr_create_save_immedN_to_dcontext(dcontext_t *dcontext, opnd_size_t sz,
opnd_t immed_op, int offs)
{
opnd_t memopnd = opnd_create_dcontext_field_sz(dcontext, offs, sz);
/* PR 244737: thread-private scratch space needs to fixed for x64 */
IF_X64(ASSERT_NOT_IMPLEMENTED(false));
/* There is no immed to mem instr on ARM/AArch64. */
IF_AARCHXX(ASSERT_NOT_IMPLEMENTED(false));
return XINST_CREATE_store(dcontext, memopnd, immed_op);
}
instr_t *
instr_create_save_immed32_to_dcontext(dcontext_t *dcontext, int immed, int offs)
{
return instr_create_save_immedN_to_dcontext(dcontext, OPSZ_4,
OPND_CREATE_INT32(immed), offs);
}
instr_t *
instr_create_save_immed16_to_dcontext(dcontext_t *dcontext, int immed, int offs)
{
return instr_create_save_immedN_to_dcontext(dcontext, OPSZ_2,
OPND_CREATE_INT16(immed), offs);
}
instr_t *
instr_create_save_immed8_to_dcontext(dcontext_t *dcontext, int immed, int offs)
{
return instr_create_save_immedN_to_dcontext(dcontext, OPSZ_1, OPND_CREATE_INT8(immed),
offs);
}
instr_t *
instr_create_save_immed_to_dc_via_reg(dcontext_t *dcontext, reg_id_t basereg, int offs,
ptr_int_t immed, opnd_size_t sz)
{
opnd_t memopnd = opnd_create_dcontext_field_via_reg_sz(dcontext, basereg, offs, sz);
ASSERT(sz == OPSZ_1 || sz == OPSZ_2 || sz == OPSZ_4);
/* There is no immed to mem instr on ARM or AArch64. */
IF_NOT_X86(ASSERT_NOT_IMPLEMENTED(false));
return XINST_CREATE_store(dcontext, memopnd, opnd_create_immed_int(immed, sz));
}
instr_t *
instr_create_jump_via_dcontext(dcontext_t *dcontext, int offs)
{
# ifdef AARCH64
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return 0;
# else
opnd_t memopnd = opnd_create_dcontext_field(dcontext, offs);
return XINST_CREATE_jump_mem(dcontext, memopnd);
# endif
}
/* there is no corresponding save routine since we no longer support
* keeping state on the stack while code other than our own is running
* (in the same thread)
*/
instr_t *
instr_create_restore_dynamo_stack(dcontext_t *dcontext)
{
return instr_create_restore_from_dcontext(dcontext, REG_XSP, DSTACK_OFFSET);
}
/* make sure to keep in sync w/ emit_utils.c's insert_spill_or_restore() */
bool
instr_raw_is_tls_spill(byte *pc, reg_id_t reg, ushort offs)
{
# ifdef X86
ASSERT_NOT_IMPLEMENTED(reg != REG_XAX);
# ifdef X64
/* match insert_jmp_to_ibl */
if (*pc == TLS_SEG_OPCODE &&
*(pc + 1) == (REX_PREFIX_BASE_OPCODE | REX_PREFIX_W_OPFLAG) &&
*(pc + 2) == MOV_REG2MEM_OPCODE &&
/* 0x1c for ebx, 0x0c for ecx, 0x04 for eax */
*(pc + 3) == MODRM_BYTE(0 /*mod*/, reg_get_bits(reg), 4 /*rm*/) &&
*(pc + 4) == 0x25 && *((uint *)(pc + 5)) == (uint)os_tls_offset(offs))
return true;
/* we also check for 32-bit. we could take in flags and only check for one
* version, but we're not worried about false positives.
*/
# endif
/* looking for: 67 64 89 1e e4 0e addr16 mov %ebx -> %fs:0xee4 */
/* ASSUMPTION: when addr16 prefix is used, prefix order is fixed */
return (*pc == ADDR_PREFIX_OPCODE && *(pc + 1) == TLS_SEG_OPCODE &&
*(pc + 2) == MOV_REG2MEM_OPCODE &&
/* 0x1e for ebx, 0x0e for ecx, 0x06 for eax */
*(pc + 3) == MODRM_BYTE(0 /*mod*/, reg_get_bits(reg), 6 /*rm*/) &&
*((ushort *)(pc + 4)) == os_tls_offset(offs)) ||
/* PR 209709: allow for no addr16 prefix */
(*pc == TLS_SEG_OPCODE && *(pc + 1) == MOV_REG2MEM_OPCODE &&
/* 0x1e for ebx, 0x0e for ecx, 0x06 for eax */
*(pc + 2) == MODRM_BYTE(0 /*mod*/, reg_get_bits(reg), 6 /*rm*/) &&
*((uint *)(pc + 4)) == os_tls_offset(offs));
# elif defined(AARCHXX)
/* FIXME i#1551, i#1569: NYI on ARM/AArch64 */
ASSERT_NOT_IMPLEMENTED(false);
return false;
# endif /* X86/ARM */
}
/* this routine may upgrade a level 1 instr */
static bool
instr_check_tls_spill_restore(instr_t *instr, bool *spill, reg_id_t *reg, int *offs)
{
opnd_t regop, memop;
CLIENT_ASSERT(instr != NULL,
"internal error: tls spill/restore check: NULL argument");
if (instr_get_opcode(instr) == OP_store) {
regop = instr_get_src(instr, 0);
memop = instr_get_dst(instr, 0);
if (spill != NULL)
*spill = true;
} else if (instr_get_opcode(instr) == OP_load) {
regop = instr_get_dst(instr, 0);
memop = instr_get_src(instr, 0);
if (spill != NULL)
*spill = false;
# ifdef X86
} else if (instr_get_opcode(instr) == OP_xchg) {
/* we use xchg to restore in dr_insert_mbr_instrumentation */
regop = instr_get_src(instr, 0);
memop = instr_get_dst(instr, 0);
if (spill != NULL)
*spill = false;
# endif
} else
return false;
if (opnd_is_reg(regop) &&
# ifdef X86
opnd_is_far_base_disp(memop) && opnd_get_segment(memop) == SEG_TLS &&
opnd_is_abs_base_disp(memop)
# elif defined(AARCHXX)
opnd_is_base_disp(memop) && opnd_get_base(memop) == dr_reg_stolen &&
opnd_get_index(memop) == DR_REG_NULL
# endif
) {
if (reg != NULL)
*reg = opnd_get_reg(regop);
if (offs != NULL)
*offs = opnd_get_disp(memop);
return true;
}
return false;
}
/* if instr is level 1, does not upgrade it and instead looks at raw bits,
* to support identification w/o ruining level 0 in decode_fragment, etc.
*/
bool
instr_is_tls_spill(instr_t *instr, reg_id_t reg, ushort offs)
{
reg_id_t check_reg = REG_NULL; /* init to satisfy some compilers */
int check_disp = 0; /* init to satisfy some compilers */
bool spill;
return (instr_check_tls_spill_restore(instr, &spill, &check_reg, &check_disp) &&
spill && check_reg == reg && check_disp == os_tls_offset(offs));
}
/* if instr is level 1, does not upgrade it and instead looks at raw bits,
* to support identification w/o ruining level 0 in decode_fragment, etc.
*/
bool
instr_is_tls_restore(instr_t *instr, reg_id_t reg, ushort offs)
{
reg_id_t check_reg = REG_NULL; /* init to satisfy some compilers */
int check_disp = 0; /* init to satisfy some compilers */
bool spill;
return (instr_check_tls_spill_restore(instr, &spill, &check_reg, &check_disp) &&
!spill && (reg == REG_NULL || check_reg == reg) &&
check_disp == os_tls_offset(offs));
}
/* if instr is level 1, does not upgrade it and instead looks at raw bits,
* to support identification w/o ruining level 0 in decode_fragment, etc.
*/
bool
instr_is_tls_xcx_spill(instr_t *instr)
{
# ifdef X86
if (instr_raw_bits_valid(instr)) {
/* avoid upgrading instr */
return instr_raw_is_tls_spill(instr_get_raw_bits(instr), REG_ECX,
MANGLE_XCX_SPILL_SLOT);
} else
return instr_is_tls_spill(instr, REG_ECX, MANGLE_XCX_SPILL_SLOT);
# elif defined(AARCHXX)
/* FIXME i#1551, i#1569: NYI on ARM/AArch64 */
ASSERT_NOT_IMPLEMENTED(false);
return false;
# endif
}
/* this routine may upgrade a level 1 instr */
static bool
instr_check_mcontext_spill_restore(dcontext_t *dcontext, instr_t *instr, bool *spill,
reg_id_t *reg, int *offs)
{
# ifdef X64
/* PR 244737: we always use tls for x64 */
return false;
# else
opnd_t regop, memop;
if (instr_get_opcode(instr) == OP_store) {
regop = instr_get_src(instr, 0);
memop = instr_get_dst(instr, 0);
if (spill != NULL)
*spill = true;
} else if (instr_get_opcode(instr) == OP_load) {
regop = instr_get_dst(instr, 0);
memop = instr_get_src(instr, 0);
if (spill != NULL)
*spill = false;
# ifdef X86
} else if (instr_get_opcode(instr) == OP_xchg) {
/* we use xchg to restore in dr_insert_mbr_instrumentation */
regop = instr_get_src(instr, 0);
memop = instr_get_dst(instr, 0);
if (spill != NULL)
*spill = false;
# endif /* X86 */
} else
return false;
if (opnd_is_near_base_disp(memop) && opnd_is_abs_base_disp(memop) &&
opnd_is_reg(regop)) {
byte *pc = (byte *)opnd_get_disp(memop);
byte *mc = (byte *)get_mcontext(dcontext);
if (pc >= mc && pc < mc + sizeof(priv_mcontext_t)) {
if (reg != NULL)
*reg = opnd_get_reg(regop);
if (offs != NULL)
*offs = pc - (byte *)dcontext;
return true;
}
}
return false;
# endif
}
static bool
instr_is_reg_spill_or_restore_ex(void *drcontext, instr_t *instr, bool DR_only, bool *tls,
bool *spill, reg_id_t *reg, uint *offs_out)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
int check_disp = 0; /* init to satisfy some compilers */
reg_id_t myreg;
CLIENT_ASSERT(instr != NULL, "invalid NULL argument");
if (reg == NULL)
reg = &myreg;
if (instr_check_tls_spill_restore(instr, spill, reg, &check_disp)) {
if (!DR_only ||
(reg_spill_tls_offs(*reg) != -1 &&
/* Mangling may choose to spill registers to a not natural tls offset,
* e.g. rip-rel mangling will, if rax is used by the instruction. We
* allow for all possible internal DR slots to recognize a DR spill.
*/
(check_disp == os_tls_offset((ushort)TLS_REG0_SLOT) ||
check_disp == os_tls_offset((ushort)TLS_REG1_SLOT) ||
check_disp == os_tls_offset((ushort)TLS_REG2_SLOT) ||
check_disp == os_tls_offset((ushort)TLS_REG3_SLOT)
# ifdef AARCHXX
|| check_disp == os_tls_offset((ushort)TLS_REG4_SLOT) ||
check_disp == os_tls_offset((ushort)TLS_REG5_SLOT)
# endif
))) {
if (tls != NULL)
*tls = true;
if (offs_out != NULL)
*offs_out = check_disp;
return true;
}
}
if (dcontext != GLOBAL_DCONTEXT &&
instr_check_mcontext_spill_restore(dcontext, instr, spill, reg, &check_disp)) {
int offs = opnd_get_reg_dcontext_offs(dr_reg_fixer[*reg]);
if (!DR_only || (offs != -1 && check_disp == offs)) {
if (tls != NULL)
*tls = false;
if (offs_out != NULL)
*offs_out = check_disp;
return true;
}
}
return false;
}
DR_API
bool
instr_is_reg_spill_or_restore(void *drcontext, instr_t *instr, bool *tls, bool *spill,
reg_id_t *reg, uint *offs)
{
return instr_is_reg_spill_or_restore_ex(drcontext, instr, false, tls, spill, reg,
offs);
}
bool
instr_is_DR_reg_spill_or_restore(void *drcontext, instr_t *instr, bool *tls, bool *spill,
reg_id_t *reg, uint *offs)
{
return instr_is_reg_spill_or_restore_ex(drcontext, instr, true, tls, spill, reg,
offs);
}
/* N.B. : client meta routines (dr_insert_* etc.) should never use anything other
* then TLS_XAX_SLOT unless the client has specified a slot to use as we let the
* client use the rest. */
instr_t *
instr_create_save_to_tls(dcontext_t *dcontext, reg_id_t reg, ushort offs)
{
return XINST_CREATE_store(dcontext, opnd_create_tls_slot(os_tls_offset(offs)),
opnd_create_reg(reg));
}
instr_t *
instr_create_restore_from_tls(dcontext_t *dcontext, reg_id_t reg, ushort offs)
{
return XINST_CREATE_load(dcontext, opnd_create_reg(reg),
opnd_create_tls_slot(os_tls_offset(offs)));
}
/* For -x86_to_x64, we can spill to 64-bit extra registers (xref i#751). */
instr_t *
instr_create_save_to_reg(dcontext_t *dcontext, reg_id_t reg1, reg_id_t reg2)
{
return XINST_CREATE_move(dcontext, opnd_create_reg(reg2), opnd_create_reg(reg1));
}
instr_t *
instr_create_restore_from_reg(dcontext_t *dcontext, reg_id_t reg1, reg_id_t reg2)
{
return XINST_CREATE_move(dcontext, opnd_create_reg(reg1), opnd_create_reg(reg2));
}
# ifdef X86_64
/* Returns NULL if pc is not the start of a rip-rel lea.
* If it could be, returns the address it refers to (which we assume is
* never NULL).
*/
byte *
instr_raw_is_rip_rel_lea(byte *pc, byte *read_end)
{
/* PR 215408: look for "lea reg, [rip+disp]"
* We assume no extraneous prefixes, and we require rex.w, though not strictly
* necessary for say WOW64 or other known-lower-4GB situations
*/
if (pc + 7 <= read_end) {
if (*(pc + 1) == RAW_OPCODE_lea &&
(TESTALL(REX_PREFIX_BASE_OPCODE | REX_PREFIX_W_OPFLAG, *pc) &&
!TESTANY(~(REX_PREFIX_BASE_OPCODE | REX_PREFIX_ALL_OPFLAGS), *pc)) &&
/* does mod==0 and rm==5? */
((*(pc + 2)) | MODRM_BYTE(0, 7, 0)) == MODRM_BYTE(0, 7, 5)) {
return pc + 7 + *(int *)(pc + 3);
}
}
return NULL;
}
# endif
uint
move_mm_reg_opcode(bool aligned16, bool aligned32)
{
# ifdef X86
if (YMM_ENABLED()) {
/* must preserve ymm registers */
return (aligned32 ? OP_vmovdqa : OP_vmovdqu);
} else if (proc_has_feature(FEATURE_SSE2)) {
return (aligned16 ? OP_movdqa : OP_movdqu);
} else {
CLIENT_ASSERT(proc_has_feature(FEATURE_SSE), "running on unsupported processor");
return (aligned16 ? OP_movaps : OP_movups);
}
# elif defined(ARM)
/* FIXME i#1551: which one we should return, OP_vmov, OP_vldr, or OP_vstr? */
return OP_vmov;
# elif defined(AARCH64)
ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */
return 0;
# endif /* X86/ARM */
}
uint
move_mm_avx512_reg_opcode(bool aligned64)
{
# ifdef X86
/* move_mm_avx512_reg_opcode can only be called on processors that support AVX-512. */
ASSERT(ZMM_ENABLED());
return (aligned64 ? OP_vmovaps : OP_vmovups);
# else
/* move_mm_avx512_reg_opcode not supported on ARM/AArch64. */
ASSERT_NOT_IMPLEMENTED(false);
return 0;
# endif /* X86 */
}
#endif /* !STANDALONE_DECODER */
/****************************************************************************/
| 1 | 24,119 | > restore, we find the matching spill for that restore which uses the same slot nit: Two separate sentences: separate with `.` or something besides `,`. | DynamoRIO-dynamorio | c |
@@ -89,12 +89,10 @@ var (
Chain: Chain{
ChainDBPath: "/tmp/chain.db",
TrieDBPath: "/tmp/trie.db",
- UseBadgerDB: false,
ID: 1,
Address: "",
ProducerPubKey: keypair.EncodePublicKey(keypair.ZeroPublicKey),
ProducerPrivKey: keypair.EncodePrivateKey(keypair.ZeroPrivateKey),
- InMemTest: false,
GenesisActionsPath: "",
EmptyGenesis: false,
NumCandidates: 101, | 1 | // Copyright (c) 2018 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package config
import (
"flag"
"os"
"time"
"github.com/pkg/errors"
uconfig "go.uber.org/config"
"google.golang.org/grpc/keepalive"
"github.com/iotexproject/iotex-core/address"
"github.com/iotexproject/iotex-core/crypto"
"github.com/iotexproject/iotex-core/pkg/keypair"
)
// IMPORTANT: to define a config, add a field or a new config type to the existing config types. In addition, provide
// the default value in Default var.
func init() {
flag.StringVar(&_overwritePath, "config-path", "", "Config path")
flag.StringVar(&_secretPath, "secret-path", "", "Secret path")
flag.StringVar(&_subChainPath, "sub-config-path", "", "Sub chain Config path")
}
var (
// overwritePath is the path to the config file which overwrite default values
_overwritePath string
// secretPath is the path to the config file store secret values
_secretPath string
_subChainPath string
)
const (
// DelegateType represents the delegate node type
DelegateType = "delegate"
// FullNodeType represents the full node type
FullNodeType = "full_node"
// LightweightType represents the lightweight type
LightweightType = "lightweight"
// RollDPoSScheme means randomized delegated proof of stake
RollDPoSScheme = "ROLLDPOS"
// StandaloneScheme means that the node creates a block periodically regardless of others (if there is any)
StandaloneScheme = "STANDALONE"
// NOOPScheme means that the node does not create only block
NOOPScheme = "NOOP"
)
var (
// Default is the default config
Default = Config{
NodeType: FullNodeType,
Network: Network{
Host: "127.0.0.1",
Port: 4689,
MsgLogsCleaningInterval: 2 * time.Second,
MsgLogRetention: 5 * time.Second,
HealthCheckInterval: time.Second,
SilentInterval: 5 * time.Second,
PeerMaintainerInterval: time.Second,
PeerForceDisconnectionRoundInterval: 0,
AllowMultiConnsPerHost: false,
NumPeersLowerBound: 5,
NumPeersUpperBound: 5,
PingInterval: time.Second,
RateLimitEnabled: false,
RateLimitPerSec: 10000,
RateLimitWindowSize: 60 * time.Second,
BootstrapNodes: make([]string, 0),
TLSEnabled: false,
CACrtPath: "",
PeerCrtPath: "",
PeerKeyPath: "",
KLClientParams: keepalive.ClientParameters{},
KLServerParams: keepalive.ServerParameters{},
KLPolicy: keepalive.EnforcementPolicy{},
MaxMsgSize: 10485760,
PeerDiscovery: true,
TopologyPath: "",
TTL: 3,
},
Chain: Chain{
ChainDBPath: "/tmp/chain.db",
TrieDBPath: "/tmp/trie.db",
UseBadgerDB: false,
ID: 1,
Address: "",
ProducerPubKey: keypair.EncodePublicKey(keypair.ZeroPublicKey),
ProducerPrivKey: keypair.EncodePrivateKey(keypair.ZeroPrivateKey),
InMemTest: false,
GenesisActionsPath: "",
EmptyGenesis: false,
NumCandidates: 101,
EnableFallBackToFreshDB: false,
EnableSubChainStartInGenesis: false,
EnableGasCharge: false,
},
ActPool: ActPool{
MaxNumActsPerPool: 32000,
MaxNumActsPerAcct: 2000,
MaxNumActsToPick: 0,
},
Consensus: Consensus{
Scheme: NOOPScheme,
RollDPoS: RollDPoS{
DelegateInterval: 10 * time.Second,
ProposerInterval: 10 * time.Second,
UnmatchedEventTTL: 3 * time.Second,
UnmatchedEventInterval: 100 * time.Millisecond,
RoundStartTTL: 10 * time.Second,
AcceptProposeTTL: time.Second,
AcceptProposalEndorseTTL: time.Second,
AcceptCommitEndorseTTL: time.Second,
Delay: 5 * time.Second,
NumSubEpochs: 1,
EventChanSize: 10000,
NumDelegates: 21,
TimeBasedRotation: false,
EnableDKG: false,
},
BlockCreationInterval: 10 * time.Second,
},
BlockSync: BlockSync{
Interval: 10 * time.Second,
BufferSize: 16,
},
Dispatcher: Dispatcher{
EventChanSize: 10000,
},
Explorer: Explorer{
Enabled: false,
UseRDS: false,
Port: 14004,
TpsWindow: 10,
GasStation: GasStation{
SuggestBlockWindow: 20,
DefaultGas: 1,
Percentile: 60,
},
MaxTransferPayloadBytes: 1024,
},
Indexer: Indexer{
Enabled: false,
NodeAddr: "",
},
System: System{
HeartbeatInterval: 10 * time.Second,
HTTPProfilingPort: 0,
HTTPMetricsPort: 8080,
StartSubChainInterval: 10 * time.Second,
},
DB: DB{
NumRetries: 3,
},
}
// ErrInvalidCfg indicates the invalid config value
ErrInvalidCfg = errors.New("invalid config value")
// Validates is the collection config validation functions
Validates = []Validate{
ValidateKeyPair,
ValidateConsensusScheme,
ValidateRollDPoS,
ValidateDispatcher,
ValidateExplorer,
ValidateNetwork,
ValidateActPool,
ValidateChain,
}
)
// Network is the config struct for network package
type (
Network struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
MsgLogsCleaningInterval time.Duration `yaml:"msgLogsCleaningInterval"`
MsgLogRetention time.Duration `yaml:"msgLogRetention"`
HealthCheckInterval time.Duration `yaml:"healthCheckInterval"`
SilentInterval time.Duration `yaml:"silentInterval"`
PeerMaintainerInterval time.Duration `yaml:"peerMaintainerInterval"`
// Force disconnecting a random peer every given number of peer maintenance round
PeerForceDisconnectionRoundInterval int `yaml:"peerForceDisconnectionRoundInterval"`
AllowMultiConnsPerHost bool `yaml:"allowMultiConnsPerHost"`
NumPeersLowerBound uint `yaml:"numPeersLowerBound"`
NumPeersUpperBound uint `yaml:"numPeersUpperBound"`
PingInterval time.Duration `yaml:"pingInterval"`
RateLimitEnabled bool `yaml:"rateLimitEnabled"`
RateLimitPerSec uint64 `yaml:"rateLimitPerSec"`
RateLimitWindowSize time.Duration `yaml:"rateLimitWindowSize"`
BootstrapNodes []string `yaml:"bootstrapNodes"`
TLSEnabled bool `yaml:"tlsEnabled"`
CACrtPath string `yaml:"caCrtPath"`
PeerCrtPath string `yaml:"peerCrtPath"`
PeerKeyPath string `yaml:"peerKeyPath"`
KLClientParams keepalive.ClientParameters `yaml:"klClientParams"`
KLServerParams keepalive.ServerParameters `yaml:"klServerParams"`
KLPolicy keepalive.EnforcementPolicy `yaml:"klPolicy"`
MaxMsgSize int `yaml:"maxMsgSize"`
PeerDiscovery bool `yaml:"peerDiscovery"`
TopologyPath string `yaml:"topologyPath"`
TTL int32 `yaml:"ttl"`
}
// Chain is the config struct for blockchain package
Chain struct {
ChainDBPath string `yaml:"chainDBPath"`
TrieDBPath string `yaml:"trieDBPath"`
UseBadgerDB bool `yaml:"useBadgerDB"`
ID uint32 `yaml:"id"`
Address string `yaml:"address"`
ProducerPubKey string `yaml:"producerPubKey"`
ProducerPrivKey string `yaml:"producerPrivKey"`
// InMemTest creates in-memory DB file for local testing
InMemTest bool `yaml:"inMemTest"`
GenesisActionsPath string `yaml:"genesisActionsPath"`
EmptyGenesis bool `yaml:"emptyGenesis"`
NumCandidates uint `yaml:"numCandidates"`
EnableFallBackToFreshDB bool `yaml:"enableFallbackToFreshDb"`
EnableSubChainStartInGenesis bool `yaml:"enableSubChainStartInGenesis"`
// enable gas charge for block producer
EnableGasCharge bool `yaml:"enableGasCharge"`
}
// Consensus is the config struct for consensus package
Consensus struct {
// There are three schemes that are supported
Scheme string `yaml:"scheme"`
RollDPoS RollDPoS `yaml:"rollDPoS"`
BlockCreationInterval time.Duration `yaml:"blockCreationInterval"`
}
// BlockSync is the config struct for the BlockSync
BlockSync struct {
Interval time.Duration `yaml:"interval"` // update duration
BufferSize uint64 `yaml:"bufferSize"`
}
// RollDPoS is the config struct for RollDPoS consensus package
RollDPoS struct {
DelegateInterval time.Duration `yaml:"delegateInterval"`
ProposerInterval time.Duration `yaml:"proposerInterval"`
UnmatchedEventTTL time.Duration `yaml:"unmatchedEventTTL"`
UnmatchedEventInterval time.Duration `yaml:"unmatchedEventInterval"`
RoundStartTTL time.Duration `yaml:"roundStartTTL"`
AcceptProposeTTL time.Duration `yaml:"acceptProposeTTL"`
AcceptProposalEndorseTTL time.Duration `yaml:"acceptProposalEndorseTTL"`
AcceptCommitEndorseTTL time.Duration `yaml:"acceptCommitEndorseTTL"`
Delay time.Duration `yaml:"delay"`
NumSubEpochs uint `yaml:"numSubEpochs"`
EventChanSize uint `yaml:"eventChanSize"`
NumDelegates uint `yaml:"numDelegates"`
TimeBasedRotation bool `yaml:"timeBasedRotation"`
EnableDKG bool `yaml:"enableDKG"`
}
// Dispatcher is the dispatcher config
Dispatcher struct {
EventChanSize uint `yaml:"eventChanSize"`
}
// Explorer is the explorer service config
Explorer struct {
Enabled bool `yaml:"enabled"`
IsTest bool `yaml:"isTest"`
UseRDS bool `yaml:"useRDS"`
Port int `yaml:"port"`
TpsWindow int `yaml:"tpsWindow"`
GasStation GasStation `yaml:"gasStation"`
// MaxTransferPayloadBytes limits how many bytes a playload can contain at most
MaxTransferPayloadBytes uint64 `yaml:"maxTransferPayloadBytes"`
}
// GasStation is the gas station config
GasStation struct {
SuggestBlockWindow int `yaml:"suggestBlockWindow"`
DefaultGas int `yaml:"defaultGas"`
Percentile int `yaml:"Percentile"`
}
// Indexer is the index service config
Indexer struct {
Enabled bool `yaml:"enabled"`
NodeAddr string `yaml:"nodeAddr"`
}
// System is the system config
System struct {
HeartbeatInterval time.Duration `yaml:"heartbeatInterval"`
// HTTPProfilingPort is the port number to access golang performance profiling data of a blockchain node. It is
// 0 by default, meaning performance profiling has been disabled
HTTPProfilingPort int `yaml:"httpProfilingPort"`
HTTPMetricsPort int `yaml:"httpMetricsPort"`
StartSubChainInterval time.Duration `yaml:"startSubChainInterval"`
}
// ActPool is the actpool config
ActPool struct {
// MaxNumActsPerPool indicates maximum number of actions the whole actpool can hold
MaxNumActsPerPool uint64 `yaml:"maxNumActsPerPool"`
// MaxNumActsPerAcct indicates maximum number of actions an account queue can hold
MaxNumActsPerAcct uint64 `yaml:"maxNumActsPerAcct"`
// MaxNumActsToPick indicates maximum number of actions to pick to mint a block. Default is 0, which means no
// limit on the number of actions to pick.
MaxNumActsToPick uint64 `yaml:"maxNumActsToPick"`
}
// DB is the blotDB config
DB struct {
// NumRetries is the number of retries
NumRetries uint8 `yaml:"numRetries"`
// RDS is the config fot rds
RDS RDS `yaml:"RDS"`
}
// RDS is the cloud rds config
RDS struct {
// AwsRDSEndpoint is the endpoint of aws rds
AwsRDSEndpoint string `yaml:"awsRDSEndpoint"`
// AwsRDSPort is the port of aws rds
AwsRDSPort uint64 `yaml:"awsRDSPort"`
// AwsRDSUser is the user to access aws rds
AwsRDSUser string `yaml:"awsRDSUser"`
// AwsPass is the pass to access aws rds
AwsPass string `yaml:"awsPass"`
// AwsDBName is the db name of aws rds
AwsDBName string `yaml:"awsDBName"`
}
// Config is the root config struct, each package's config should be put as its sub struct
Config struct {
NodeType string `yaml:"nodeType"`
Network Network `yaml:"network"`
Chain Chain `yaml:"chain"`
ActPool ActPool `yaml:"actPool"`
Consensus Consensus `yaml:"consensus"`
BlockSync BlockSync `yaml:"blockSync"`
Dispatcher Dispatcher `yaml:"dispatcher"`
Explorer Explorer `yaml:"explorer"`
Indexer Indexer `yaml:"indexer"`
System System `yaml:"system"`
DB DB `yaml:"db"`
}
// Validate is the interface of validating the config
Validate func(Config) error
)
// New creates a config instance. It first loads the default configs. If the config path is not empty, it will read from
// the file and override the default configs. By default, it will apply all validation functions. To bypass validation,
// use DoNotValidate instead.
func New(validates ...Validate) (Config, error) {
opts := make([]uconfig.YAMLOption, 0)
opts = append(opts, uconfig.Static(Default))
opts = append(opts, uconfig.Expand(os.LookupEnv))
if _overwritePath != "" {
opts = append(opts, uconfig.File(_overwritePath))
}
if _secretPath != "" {
opts = append(opts, uconfig.File(_secretPath))
}
yaml, err := uconfig.NewYAML(opts...)
if err != nil {
return Config{}, errors.Wrap(err, "failed to init config")
}
var cfg Config
if err := yaml.Get(uconfig.Root).Populate(&cfg); err != nil {
return Config{}, errors.Wrap(err, "failed to unmarshal YAML config to struct")
}
// By default, the config needs to pass all the validation
if len(validates) == 0 {
validates = Validates
}
for _, validate := range validates {
if err := validate(cfg); err != nil {
return Config{}, errors.Wrap(err, "failed to validate config")
}
}
return cfg, nil
}
// NewSub create config for sub chain.
func NewSub(validates ...Validate) (Config, error) {
if _subChainPath == "" {
return Config{}, nil
}
opts := make([]uconfig.YAMLOption, 0)
opts = append(opts, uconfig.Static(Default))
opts = append(opts, uconfig.Expand(os.LookupEnv))
opts = append(opts, uconfig.File(_subChainPath))
if _secretPath != "" {
opts = append(opts, uconfig.File(_secretPath))
}
yaml, err := uconfig.NewYAML(opts...)
if err != nil {
return Config{}, errors.Wrap(err, "failed to init config")
}
var cfg Config
if err := yaml.Get(uconfig.Root).Populate(&cfg); err != nil {
return Config{}, errors.Wrap(err, "failed to unmarshal YAML config to struct")
}
// By default, the config needs to pass all the validation
if len(validates) == 0 {
validates = Validates
}
for _, validate := range validates {
if err := validate(cfg); err != nil {
return Config{}, errors.Wrap(err, "failed to validate config")
}
}
return cfg, nil
}
// IsDelegate returns true if the node type is Delegate
func (cfg Config) IsDelegate() bool {
return cfg.NodeType == DelegateType
}
// IsFullnode returns true if the node type is Fullnode
func (cfg Config) IsFullnode() bool {
return cfg.NodeType == FullNodeType
}
// IsLightweight returns true if the node type is Lightweight
func (cfg Config) IsLightweight() bool {
return cfg.NodeType == LightweightType
}
// BlockchainAddress returns the address derived from the configured chain ID and public key
func (cfg Config) BlockchainAddress() (address.Address, error) {
pk, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey)
if err != nil {
return nil, errors.Wrapf(err, "error when decoding public key %s", cfg.Chain.ProducerPubKey)
}
pkHash := keypair.HashPubKey(pk)
return address.New(cfg.Chain.ID, pkHash[:]), nil
}
// KeyPair returns the decoded public and private key pair
func (cfg Config) KeyPair() (keypair.PublicKey, keypair.PrivateKey, error) {
pk, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey)
if err != nil {
return keypair.ZeroPublicKey,
keypair.ZeroPrivateKey,
errors.Wrapf(err, "error when decoding public key %s", cfg.Chain.ProducerPubKey)
}
sk, err := keypair.DecodePrivateKey(cfg.Chain.ProducerPrivKey)
if err != nil {
return keypair.ZeroPublicKey,
keypair.ZeroPrivateKey,
errors.Wrapf(err, "error when decoding private key %s", cfg.Chain.ProducerPrivKey)
}
return pk, sk, nil
}
// ValidateKeyPair validates the block producer address
func ValidateKeyPair(cfg Config) error {
priKey, err := keypair.DecodePrivateKey(cfg.Chain.ProducerPrivKey)
if err != nil {
return err
}
pubKey, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey)
if err != nil {
return err
}
// Validate producer pubkey and prikey by signing a dummy message and verify it
validationMsg := "connecting the physical world block by block"
sig := crypto.EC283.Sign(priKey, []byte(validationMsg))
if !crypto.EC283.Verify(pubKey, []byte(validationMsg), sig) {
return errors.Wrap(ErrInvalidCfg, "block producer has unmatched pubkey and prikey")
}
return nil
}
// ValidateChain validates the chain configure
func ValidateChain(cfg Config) error {
if cfg.Chain.NumCandidates <= 0 {
return errors.Wrapf(ErrInvalidCfg, "candidate number should be greater than 0")
}
if cfg.Consensus.Scheme == RollDPoSScheme && cfg.Chain.NumCandidates < cfg.Consensus.RollDPoS.NumDelegates {
return errors.Wrapf(ErrInvalidCfg, "candidate number should be greater than or equal to delegate number")
}
return nil
}
// ValidateConsensusScheme validates the if scheme and node type match
func ValidateConsensusScheme(cfg Config) error {
switch cfg.NodeType {
case DelegateType:
case FullNodeType:
if cfg.Consensus.Scheme != NOOPScheme {
return errors.Wrap(ErrInvalidCfg, "consensus scheme of fullnode should be NOOP")
}
case LightweightType:
if cfg.Consensus.Scheme != NOOPScheme {
return errors.Wrap(ErrInvalidCfg, "consensus scheme of lightweight node should be NOOP")
}
default:
return errors.Wrapf(ErrInvalidCfg, "unknown node type %s", cfg.NodeType)
}
return nil
}
// ValidateDispatcher validates the dispatcher configs
func ValidateDispatcher(cfg Config) error {
if cfg.Dispatcher.EventChanSize <= 0 {
return errors.Wrap(ErrInvalidCfg, "dispatcher event chan size should be greater than 0")
}
return nil
}
// ValidateRollDPoS validates the roll-DPoS configs
func ValidateRollDPoS(cfg Config) error {
if cfg.Consensus.Scheme != RollDPoSScheme {
return nil
}
rollDPoS := cfg.Consensus.RollDPoS
if rollDPoS.EventChanSize <= 0 {
return errors.Wrap(ErrInvalidCfg, "roll-DPoS event chan size should be greater than 0")
}
if rollDPoS.NumDelegates <= 0 {
return errors.Wrap(ErrInvalidCfg, "roll-DPoS event delegate number should be greater than 0")
}
ttl := rollDPoS.AcceptCommitEndorseTTL + rollDPoS.AcceptProposeTTL + rollDPoS.AcceptProposalEndorseTTL
if ttl >= rollDPoS.ProposerInterval {
return errors.Wrap(ErrInvalidCfg, "roll-DPoS ttl sum is larger than proposer interval")
}
return nil
}
// ValidateExplorer validates the explorer configs
func ValidateExplorer(cfg Config) error {
if cfg.Explorer.Enabled && cfg.Explorer.TpsWindow <= 0 {
return errors.Wrap(ErrInvalidCfg, "tps window is not a positive integer when the explorer is enabled")
}
return nil
}
// ValidateNetwork validates the network configs
func ValidateNetwork(cfg Config) error {
if !cfg.Network.PeerDiscovery && cfg.Network.TopologyPath == "" {
return errors.Wrap(ErrInvalidCfg, "either peer discover should be enabled or a topology should be given")
}
return nil
}
// ValidateActPool validates the given config
func ValidateActPool(cfg Config) error {
maxNumActPerPool := cfg.ActPool.MaxNumActsPerPool
maxNumActPerAcct := cfg.ActPool.MaxNumActsPerAcct
if maxNumActPerPool <= 0 || maxNumActPerAcct <= 0 {
return errors.Wrap(
ErrInvalidCfg,
"maximum number of actions per pool or per account cannot be zero or negative",
)
}
if maxNumActPerPool < maxNumActPerAcct {
return errors.Wrap(
ErrInvalidCfg,
"maximum number of actions per pool cannot be less than maximum number of actions per account",
)
}
return nil
}
// DoNotValidate validates the given config
func DoNotValidate(cfg Config) error { return nil }
| 1 | 13,709 | this flag not used | iotexproject-iotex-core | go |
@@ -625,7 +625,9 @@ class Folio extends AbstractAPI implements
'zip' => $profile->personal->addresses[0]->postalCode ?? null,
'phone' => $profile->personal->phone ?? null,
'mobile_phone' => $profile->personal->mobilePhone ?? null,
- 'expiration_date' => $profile->expirationDate ?? null,
+ 'expiration_date' => $this->dateConverter->convertToDisplayDate(
+ "Y-m-d H:i", $profile->expirationDate
+ ) ?? null,
];
}
| 1 | <?php
/**
* FOLIO REST API driver
*
* PHP version 7
*
* Copyright (C) Villanova University 2018.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @category VuFind
* @package ILS_Drivers
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
namespace VuFind\ILS\Driver;
use Exception;
use VuFind\Exception\ILS as ILSException;
use VuFind\I18n\Translator\TranslatorAwareInterface;
use VuFindHttp\HttpServiceAwareInterface as HttpServiceAwareInterface;
/**
* FOLIO REST API driver
*
* @category VuFind
* @package ILS_Drivers
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
class Folio extends AbstractAPI implements
HttpServiceAwareInterface, TranslatorAwareInterface
{
use \VuFindHttp\HttpServiceAwareTrait;
use \VuFind\I18n\Translator\TranslatorAwareTrait;
use \VuFind\Log\LoggerAwareTrait {
logWarning as warning;
logError as error;
}
/**
* Authentication tenant (X-Okapi-Tenant)
*
* @var string
*/
protected $tenant = null;
/**
* Authentication token (X-Okapi-Token)
*
* @var string
*/
protected $token = null;
/**
* Factory function for constructing the SessionContainer.
*
* @var Callable
*/
protected $sessionFactory;
/**
* Session cache
*
* @var \Laminas\Session\Container
*/
protected $sessionCache;
/**
* Constructor
*
* @param \VuFind\Date\Converter $dateConverter Date converter object
* @param Callable $sessionFactory Factory function returning
* SessionContainer object
*/
public function __construct(\VuFind\Date\Converter $dateConverter,
$sessionFactory
) {
$this->dateConverter = $dateConverter;
$this->sessionFactory = $sessionFactory;
}
/**
* Set the configuration for the driver.
*
* @param array $config Configuration array (usually loaded from a VuFind .ini
* file whose name corresponds with the driver class name).
*
* @throws ILSException if base url excluded
* @return void
*/
public function setConfig($config)
{
parent::setConfig($config);
$this->tenant = $this->config['API']['tenant'];
}
/**
* Get the type of FOLIO ID used to match up with VuFind's bib IDs.
*
* @return string
*/
protected function getBibIdType()
{
// Normalize string to tolerate minor variations in config file:
return trim(strtolower($this->config['IDs']['type'] ?? 'instance'));
}
/**
* Function that obscures and logs debug data
*
* @param string $method Request method
* (GET/POST/PUT/DELETE/etc.)
* @param string $path Request URL
* @param array $params Request parameters
* @param \Laminas\Http\Headers $req_headers Headers object
*
* @return void
*/
protected function debugRequest($method, $path, $params, $req_headers)
{
// Only log non-GET requests
if ($method == 'GET') {
return;
}
// remove passwords
$logParams = $params;
if (isset($logParams['password'])) {
unset($logParams['password']);
}
// truncate headers for token obscuring
$logHeaders = $req_headers->toArray();
if (isset($logHeaders['X-Okapi-Token'])) {
$logHeaders['X-Okapi-Token'] = substr(
$logHeaders['X-Okapi-Token'], 0, 30
) . '...';
}
$this->debug(
$method . ' request.' .
' URL: ' . $path . '.' .
' Params: ' . print_r($logParams, true) . '.' .
' Headers: ' . print_r($logHeaders, true)
);
}
/**
* (From AbstractAPI) Allow default corrections to all requests
*
* Add X-Okapi headers and Content-Type to every request
*
* @param \Laminas\Http\Headers $headers the request headers
* @param object $params the parameters object
*
* @return array
*/
public function preRequest(\Laminas\Http\Headers $headers, $params)
{
$headers->addHeaderLine('Accept', 'application/json');
if (!$headers->has('Content-Type')) {
$headers->addHeaderLine('Content-Type', 'application/json');
}
$headers->addHeaderLine('X-Okapi-Tenant', $this->tenant);
if ($this->token != null) {
$headers->addHeaderLine('X-Okapi-Token', $this->token);
}
return [$headers, $params];
}
/**
* Login and receive a new token
*
* @return void
*/
protected function renewTenantToken()
{
$this->token = null;
$auth = [
'username' => $this->config['API']['username'],
'password' => $this->config['API']['password'],
];
$response = $this->makeRequest('POST', '/authn/login', json_encode($auth));
if ($response->getStatusCode() >= 400) {
throw new ILSException($response->getBody());
}
$this->token = $response->getHeaders()->get('X-Okapi-Token')
->getFieldValue();
$this->sessionCache->folio_token = $this->token;
$this->debug(
'Token renewed. Tenant: ' . $auth['username'] .
' Token: ' . substr($this->token, 0, 30) . '...'
);
}
/**
* Check if our token is still valid
*
* Method taken from Stripes JS (loginServices.js:validateUser)
*
* @return void
*/
protected function checkTenantToken()
{
$response = $this->makeRequest('GET', '/users');
if ($response->getStatusCode() >= 400) {
$this->token = null;
$this->renewTenantToken();
}
}
/**
* Initialize the driver.
*
* Check or renew our auth token
*
* @return void
*/
public function init()
{
$factory = $this->sessionFactory;
$this->sessionCache = $factory($this->tenant);
if ($this->sessionCache->folio_token ?? false) {
$this->token = $this->sessionCache->folio_token;
$this->debug(
'Token taken from cache: ' . substr($this->token, 0, 30) . '...'
);
}
if ($this->token == null) {
$this->renewTenantToken();
} else {
$this->checkTenantToken();
}
}
/**
* Given some kind of identifier (instance, holding or item), retrieve the
* associated instance object from FOLIO.
*
* @param string $instanceId Instance ID, if available.
* @param string $holdingId Holding ID, if available.
* @param string $itemId Item ID, if available.
*
* @return object
*/
protected function getInstanceById($instanceId = null, $holdingId = null,
$itemId = null
) {
if ($instanceId == null) {
if ($holdingId == null) {
if ($itemId == null) {
throw new \Exception('No IDs provided to getInstanceObject.');
}
$response = $this->makeRequest(
'GET',
'/item-storage/items/' . $itemId
);
$item = json_decode($response->getBody());
$holdingId = $item->holdingsRecordId;
}
$response = $this->makeRequest(
'GET', '/holdings-storage/holdings/' . $holdingId
);
$holding = json_decode($response->getBody());
$instanceId = $holding->instanceId;
}
$response = $this->makeRequest(
'GET', '/inventory/instances/' . $instanceId
);
return json_decode($response->getBody());
}
/**
* Given an instance object or identifer, or a holding or item identifier,
* determine an appropriate value to use as VuFind's bibliographic ID.
*
* @param string $instanceOrInstanceId Instance object or ID (will be looked up
* using holding or item ID if not provided)
* @param string $holdingId Holding-level id (optional)
* @param string $itemId Item-level id (optional)
*
* @return string Appropriate bib id retrieved from FOLIO identifiers
*/
protected function getBibId($instanceOrInstanceId = null, $holdingId = null,
$itemId = null
) {
$idType = $this->getBibIdType();
// Special case: if we're using instance IDs and we already have one,
// short-circuit the lookup process:
if ($idType === 'instance' && is_string($instanceOrInstanceId)) {
return $instanceOrInstanceId;
}
$instance = is_object($instanceOrInstanceId)
? $instanceOrInstanceId
: $this->getInstanceById($instanceOrInstanceId, $holdingId, $itemId);
switch ($idType) {
case 'hrid':
return $instance->hrid;
case 'instance':
return $instance->id;
}
throw new \Exception('Unsupported ID type: ' . $idType);
}
/**
* Escape a string for use in a CQL query.
*
* @param string $in Input string
*
* @return string
*/
protected function escapeCql($in)
{
return str_replace('"', '\"', str_replace('&', '%26', $in));
}
/**
* Retrieve FOLIO instance using VuFind's chosen bibliographic identifier.
*
* @param string $bibId Bib-level id
*
* @throw
* @return array
*/
protected function getInstanceByBibId($bibId)
{
// Figure out which ID type to use in the CQL query; if the user configured
// instance IDs, use the 'id' field, otherwise pass the setting through
// directly:
$idType = $this->getBibIdType();
$idField = $idType === 'instance' ? 'id' : $idType;
$query = [
'query' => '(' . $idField . '=="' . $this->escapeCql($bibId) . '")'
];
$response = $this->makeRequest('GET', '/instance-storage/instances', $query);
$instances = json_decode($response->getBody());
if (count($instances->instances) == 0) {
throw new ILSException("Item Not Found");
}
return $instances->instances[0];
}
/**
* Get raw object of item from inventory/items/
*
* @param string $itemId Item-level id
*
* @return array
*/
public function getStatus($itemId)
{
return $this->getHolding($itemId);
}
/**
* This method calls getStatus for an array of records or implement a bulk method
*
* @param array $idList Item-level ids
*
* @return array values from getStatus
*/
public function getStatuses($idList)
{
$status = [];
foreach ($idList as $id) {
$status[] = $this->getStatus($id);
}
return $status;
}
/**
* Retrieves renew, hold and cancel settings from the driver ini file.
*
* @param string $function The name of the feature to be checked
* @param array $params Optional feature-specific parameters (array)
*
* @return array An array with key-value pairs.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getConfig($function, $params = null)
{
return $this->config[$function] ?? false;
}
/**
* This method queries the ILS for holding information.
*
* @param string $bibId Bib-level id
* @param array $patron Patron login information from $this->patronLogin
* @param array $options Extra options (not currently used)
*
* @return array An array of associative holding arrays
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getHolding($bibId, array $patron = null, array $options = [])
{
$instance = $this->getInstanceByBibId($bibId);
$query = ['query' => '(instanceId=="' . $instance->id . '")'];
$holdingResponse = $this->makeRequest(
'GET',
'/holdings-storage/holdings',
$query
);
$holdingBody = json_decode($holdingResponse->getBody());
$items = [];
for ($i = 0; $i < count($holdingBody->holdingsRecords); $i++) {
$holding = $holdingBody->holdingsRecords[$i];
$locationName = '';
if (!empty($holding->permanentLocationId)) {
$locationResponse = $this->makeRequest(
'GET',
'/locations/' . $holding->permanentLocationId
);
$location = json_decode($locationResponse->getBody());
$locationName = $location->name;
}
$query = ['query' => '(holdingsRecordId=="' . $holding->id . '")'];
$itemResponse = $this->makeRequest('GET', '/item-storage/items', $query);
$itemBody = json_decode($itemResponse->getBody());
$notesFormatter = function ($note) {
return $note->note ?? '';
};
for ($j = 0; $j < count($itemBody->items); $j++) {
$item = $itemBody->items[$j];
$items[] = [
'id' => $bibId,
'item_id' => $itemBody->items[$j]->id,
'holding_id' => $holding->id,
'number' => count($items) + 1,
'barcode' => $item->barcode ?? '',
'status' => $item->status->name,
'availability' => $item->status->name == 'Available',
'notes' => array_map($notesFormatter, $item->notes ?? []),
'callnumber' => $holding->callNumber ?? '',
'location' => $locationName,
'reserve' => 'TODO',
'addLink' => true
];
}
}
return $items;
}
/**
* Support method for patronLogin(): authenticate the patron with an Okapi
* login attempt. Returns a CQL query for retrieving more information about
* the authenticated user.
*
* @param string $username The patron username
* @param string $password The patron password
*
* @return string
*/
protected function patronLoginWithOkapi($username, $password)
{
$tenant = $this->config['API']['tenant'];
$credentials = compact('tenant', 'username', 'password');
// Get token
$response = $this->makeRequest(
'POST',
'/authn/login',
json_encode($credentials)
);
$debugMsg = 'User logged in. User: ' . $username . '.';
// We've authenticated the user with Okapi, but we only have their
// username; set up a query to retrieve full info below.
$query = 'username == ' . $username;
// Replace admin with user as tenant if configured to do so:
if ($this->config['User']['use_user_token'] ?? false) {
$this->token = $response->getHeaders()->get('X-Okapi-Token')
->getFieldValue();
$debugMsg .= ' Token: ' . substr($this->token, 0, 30) . '...';
}
$this->debug($debugMsg);
return $query;
}
/**
* Support method for patronLogin(): authenticate the patron with a CQL looup.
* Returns the CQL query for retrieving more information about the user.
*
* @param string $username The patron username
* @param string $password The patron password
*
* @return string
*/
protected function getUserWithCql($username, $password)
{
// Construct user query using barcode, username, etc.
$usernameField = $this->config['User']['username_field'] ?? 'username';
$passwordField = $this->config['User']['password_field'] ?? false;
$cql = $this->config['User']['cql']
?? '%%username_field%% == "%%username%%"'
. ($passwordField ? ' and %%password_field%% == "%%password%%"' : '');
$placeholders = [
'%%username_field%%',
'%%password_field%%',
'%%username%%',
'%%password%%',
];
$values = [
$usernameField,
$passwordField,
$this->escapeCql($username),
$this->escapeCql($password),
];
return str_replace($placeholders, $values, $cql);
}
/**
* Given a CQL query, fetch a single user; if we get an unexpected count, treat
* that as an unsuccessful login by returning null.
*
* @param string $query CQL query
*
* @return object
*/
protected function fetchUserWithCql($query)
{
$response = $this->makeRequest('GET', '/users', compact('query'));
$json = json_decode($response->getBody());
return count($json->users) === 1 ? $json->users[0] : null;
}
/**
* Patron Login
*
* This is responsible for authenticating a patron against the catalog.
*
* @param string $username The patron username
* @param string $password The patron password
*
* @return mixed Associative array of patron info on successful login,
* null on unsuccessful login.
*/
public function patronLogin($username, $password)
{
$doOkapiLogin = $this->config['User']['okapi_login'] ?? false;
$usernameField = $this->config['User']['username_field'] ?? 'username';
// If the username field is not the default 'username' we will need to
// do a lookup to find the correct username value for Okapi login. We also
// need to do this lookup if we're skipping Okapi login entirely.
if (!$doOkapiLogin || $usernameField !== 'username') {
$query = $this->getUserWithCql($username, $password);
$profile = $this->fetchUserWithCql($query);
if ($profile === null) {
return null;
}
}
// If we need to do an Okapi login, we have the information we need to do
// it at this point.
if ($doOkapiLogin) {
try {
// If we fetched the profile earlier, we want to use the username
// from there; otherwise, we'll use the passed-in version.
$query = $this->patronLoginWithOkapi(
$profile->username ?? $username,
$password
);
} catch (Exception $e) {
return null;
}
// If we didn't load a profile earlier, we should do so now:
if (!isset($profile)) {
$profile = $this->fetchUserWithCql($query);
if ($profile === null) {
return null;
}
}
}
return [
'id' => $profile->id,
'username' => $username,
'cat_username' => $username,
'cat_password' => $password,
'firstname' => $profile->personal->firstName ?? null,
'lastname' => $profile->personal->lastName ?? null,
'email' => $profile->personal->email ?? null,
];
}
/**
* This method queries the ILS for a patron's current profile information
*
* @param array $patron Patron login information from $this->patronLogin
*
* @return array Profile data in associative array
*/
public function getMyProfile($patron)
{
$query = ['query' => 'id == "' . $patron['id'] . '"'];
$response = $this->makeRequest('GET', '/users', $query);
$users = json_decode($response->getBody());
$profile = $users->users[0];
return [
'id' => $profile->id,
'firstname' => $profile->personal->firstName ?? null,
'lastname' => $profile->personal->lastName ?? null,
'address1' => $profile->personal->addresses[0]->addressLine1 ?? null,
'city' => $profile->personal->addresses[0]->city ?? null,
'country' => $profile->personal->addresses[0]->countryId ?? null,
'zip' => $profile->personal->addresses[0]->postalCode ?? null,
'phone' => $profile->personal->phone ?? null,
'mobile_phone' => $profile->personal->mobilePhone ?? null,
'expiration_date' => $profile->expirationDate ?? null,
];
}
/**
* This method queries the ILS for a patron's current checked out items
*
* Input: Patron array returned by patronLogin method
* Output: Returns an array of associative arrays.
* Each associative array contains these keys:
* duedate - The item's due date (a string).
* dueTime - The item's due time (a string, optional).
* dueStatus - A special status – may be 'due' (for items due very soon)
* or 'overdue' (for overdue items). (optional).
* id - The bibliographic ID of the checked out item.
* source - The search backend from which the record may be retrieved
* (optional - defaults to Solr). Introduced in VuFind 2.4.
* barcode - The barcode of the item (optional).
* renew - The number of times the item has been renewed (optional).
* renewLimit - The maximum number of renewals allowed
* (optional - introduced in VuFind 2.3).
* request - The number of pending requests for the item (optional).
* volume – The volume number of the item (optional).
* publication_year – The publication year of the item (optional).
* renewable – Whether or not an item is renewable
* (required for renewals).
* message – A message regarding the item (optional).
* title - The title of the item (optional – only used if the record
* cannot be found in VuFind's index).
* item_id - this is used to match up renew responses and must match
* the item_id in the renew response.
* institution_name - Display name of the institution that owns the item.
* isbn - An ISBN for use in cover image loading
* (optional – introduced in release 2.3)
* issn - An ISSN for use in cover image loading
* (optional – introduced in release 2.3)
* oclc - An OCLC number for use in cover image loading
* (optional – introduced in release 2.3)
* upc - A UPC for use in cover image loading
* (optional – introduced in release 2.3)
* borrowingLocation - A string describing the location where the item
* was checked out (optional – introduced in release 2.4)
*
* @param array $patron Patron login information from $this->patronLogin
*
* @return array Transactions associative arrays
*/
public function getMyTransactions($patron)
{
$query = ['query' => 'userId==' . $patron['id'] . ' and status.name==Open'];
$response = $this->makeRequest("GET", '/circulation/loans', $query);
$json = json_decode($response->getBody());
if (count($json->loans) == 0) {
return [];
}
$transactions = [];
foreach ($json->loans as $trans) {
$date = date_create($trans->dueDate);
$transactions[] = [
'duedate' => date_format($date, "j M Y"),
'dueTime' => date_format($date, "g:i:s a"),
// TODO: Due Status
// 'dueStatus' => $trans['itemId'],
'id' => $this->getBibId($trans->item->instanceId),
'item_id' => $trans->item->id,
'barcode' => $trans->item->barcode,
'renew' => $trans->renewalCount ?? 0,
'renewable' => true,
'title' => $trans->item->title,
];
}
return $transactions;
}
/**
* Get FOLIO loan IDs for use in renewMyItems.
*
* @param array $transaction An single transaction
* array from getMyTransactions
*
* @return string The FOLIO loan ID for this loan
*/
public function getRenewDetails($transaction)
{
return $transaction['item_id'];
}
/**
* Attempt to renew a list of items for a given patron.
*
* @param array $renewDetails An associative array with
* patron and details
*
* @return array $renewResult result of attempt to renew loans
*/
public function renewMyItems($renewDetails)
{
$renewalResults = ['details' => []];
foreach ($renewDetails['details'] as $loanId) {
$requestbody = [
'itemId' => $loanId,
'userId' => $renewDetails['patron']['id']
];
$response = $this->makeRequest(
'POST', '/circulation/renew-by-id', json_encode($requestbody)
);
if ($response->isSuccess()) {
$json = json_decode($response->getBody());
$renewal = [
'success' => true,
'new_date' => $this->dateConverter->convertToDisplayDate(
"Y-m-d H:i", $json->dueDate
),
'new_time' => $this->dateConverter->convertToDisplayTime(
"Y-m-d H:i", $json->dueDate
),
'item_id' => $json->itemId,
'sysMessage' => $json->action
];
} else {
try {
$json = json_decode($response->getBody());
$sysMessage = $json->errors[0]->message;
} catch (Exception $e) {
$sysMessage = "Renewal Failed";
}
$renewal = [
'success' => false,
'sysMessage' => $sysMessage
];
}
$renewalResults['details'][$loanId] = $renewal;
}
return $renewalResults;
}
/**
* Get Pick Up Locations
*
* This is responsible get a list of valid locations for holds / recall
* retrieval
*
* @param array $patron Patron information returned by $this->patronLogin
*
* @return array An array of associative arrays with locationID and
* locationDisplay keys
*/
public function getPickupLocations($patron)
{
$query = ['query' => 'pickupLocation=true'];
$response = $this->makeRequest('GET', '/service-points', $query);
$json = json_decode($response->getBody());
$locations = [];
foreach ($json->servicepoints as $servicepoint) {
$locations[] = [
'locationID' => $servicepoint->id,
'locationDisplay' => $servicepoint->discoveryDisplayName
];
}
return $locations;
}
/**
* This method queries the ILS for a patron's current holds
*
* Input: Patron array returned by patronLogin method
* Output: Returns an array of associative arrays, one for each hold associated
* with the specified account. Each associative array contains these keys:
* type - A string describing the type of hold – i.e. hold vs. recall
* (optional).
* id - The bibliographic record ID associated with the hold (optional).
* source - The search backend from which the record may be retrieved
* (optional - defaults to Solr). Introduced in VuFind 2.4.
* location - A string describing the pickup location for the held item
* (optional). In VuFind 1.2, this should correspond with a locationID value from
* getPickUpLocations. In VuFind 1.3 and later, it may be either
* a locationID value or a raw ready-to-display string.
* reqnum - A control number for the request (optional).
* expire - The expiration date of the hold (a string).
* create - The creation date of the hold (a string).
* position – The position of the user in the holds queue (optional)
* available – Whether or not the hold is available (true/false) (optional)
* item_id – The item id the request item (optional).
* volume – The volume number of the item (optional)
* publication_year – The publication year of the item (optional)
* title - The title of the item
* (optional – only used if the record cannot be found in VuFind's index).
* isbn - An ISBN for use in cover image loading (optional)
* issn - An ISSN for use in cover image loading (optional)
* oclc - An OCLC number for use in cover image loading (optional)
* upc - A UPC for use in cover image loading (optional)
* cancel_details - The cancel token, or a blank string if cancel is illegal
* for this hold; if omitted, this will be dynamically generated using
* getCancelHoldDetails(). You should only fill this in if it is more efficient
* to calculate the value up front; if it is an expensive calculation, you should
* omit the value entirely and let getCancelHoldDetails() do its job on demand.
* This optional feature was introduced in release 3.1.
*
* @param array $patron Patron login information from $this->patronLogin
*
* @return array Associative array of holds information
*/
public function getMyHolds($patron)
{
$query = [
'query' => '(requesterId == "' . $patron['id'] . '" ' .
'and status == Open*)'
];
$response = $this->makeRequest('GET', '/request-storage/requests', $query);
$json = json_decode($response->getBody());
$holds = [];
foreach ($json->requests as $hold) {
$requestDate = date_create($hold->requestDate);
// Set expire date if it was included in the response
$expireDate = isset($hold->requestExpirationDate)
? date_create($hold->requestExpirationDate) : null;
$holds[] = [
'type' => $hold->requestType,
'create' => date_format($requestDate, "j M Y"),
'expire' => isset($expireDate)
? date_format($expireDate, "j M Y") : "",
'id' => $this->getBibId(null, null, $hold->itemId),
'item_id' => $hold->itemId,
'reqnum' => $hold->id,
'title' => $hold->item->title
];
}
return $holds;
}
/**
* Place Hold
*
* Attempts to place a hold or recall on a particular item and returns
* an array with result details.
*
* @param array $holdDetails An array of item and patron data
*
* @return mixed An array of data on the request including
* whether or not it was successful and a system message (if available)
*/
public function placeHold($holdDetails)
{
$default_request = $this->config['Holds']['default_request'] ?? 'Hold';
try {
$requiredBy = date_create_from_format(
'm-d-Y',
$holdDetails['requiredBy']
);
} catch (Exception $e) {
throw new ILSException('hold_date_invalid');
}
$requestBody = [
'itemId' => $holdDetails['item_id'],
'requestType' => $holdDetails['status'] == 'Available'
? 'Page' : $default_request,
'requesterId' => $holdDetails['patron']['id'],
'requestDate' => date('c'),
'fulfilmentPreference' => 'Hold Shelf',
'requestExpirationDate' => date_format($requiredBy, 'Y-m-d'),
'pickupServicePointId' => $holdDetails['pickUpLocation']
];
$response = $this->makeRequest(
'POST',
'/circulation/requests',
json_encode($requestBody)
);
if ($response->isSuccess()) {
$json = json_decode($response->getBody());
$result = [
'success' => true,
'status' => $json->status
];
} else {
try {
$json = json_decode($response->getBody());
$result = [
'success' => false,
'status' => $json->errors[0]->message
];
} catch (Exception $e) {
throw new ILSException($response->getBody());
}
}
return $result;
}
/**
* Get FOLIO hold IDs for use in cancelHolds.
*
* @param array $hold An single request
* array from getMyHolds
*
* @return string request ID for this request
*/
public function getCancelHoldDetails($hold)
{
return $hold['reqnum'];
}
/**
* Cancel Holds
*
* Attempts to Cancel a hold or recall on a particular item. The
* data in $cancelDetails['details'] is determined by getCancelHoldDetails().
*
* @param array $cancelDetails An array of item and patron data
*
* @return array An array of data on each request including
* whether or not it was successful and a system message (if available)
*/
public function cancelHolds($cancelDetails)
{
$details = $cancelDetails['details'];
$patron = $cancelDetails['patron'];
$count = 0;
$cancelResult = ['items' => []];
foreach ($details as $requestId) {
$response = $this->makeRequest(
'GET', '/circulation/requests/' . $requestId
);
$request_json = json_decode($response->getBody());
// confirm request belongs to signed in patron
if ($request_json->requesterId != $patron['id']) {
throw new ILSException("Invalid Request");
}
// Change status to Closed and add cancellationID
$request_json->status = 'Closed - Cancelled';
$request_json->cancellationReasonId
= $this->config['Holds']['cancellation_reason'];
$cancel_response = $this->makeRequest(
'PUT', '/circulation/requests/' . $requestId,
json_encode($request_json)
);
if ($cancel_response->getStatusCode() == 204) {
$count++;
$cancelResult['items'][$request_json->itemId] = [
'success' => true,
'status' => 'hold_cancel_success'
];
} else {
$cancelResult['items'][$request_json->itemId] = [
'success' => false,
'status' => 'hold_cancel_fail'
];
}
}
$cancelResult['count'] = $count;
return $cancelResult;
}
/**
* Obtain a list of course resources, creating an id => value associative array.
*
* @param string $type Type of resource to retrieve from the API.
* @param string $responseKey Key containing useful values in response (defaults
* to $type if unspecified)
* @param string $valueKey Key containing value to extract from response
* (defaults to 'name')
*
* @return array
*/
protected function getCourseResourceList($type, $responseKey = null,
$valueKey = 'name'
) {
$retVal = [];
$limit = 1000; // how many records to retrieve at once
$offset = 0;
// Results can be paginated, so let's loop until we've gotten everything:
do {
$response = $this->makeRequest(
'GET',
'/coursereserves/' . $type,
compact('offset', 'limit')
);
$json = json_decode($response->getBody());
$total = $json->totalRecords ?? 0;
$preCount = count($retVal);
foreach ($json->{$responseKey ?? $type} ?? [] as $item) {
$retVal[$item->id] = $item->$valueKey ?? '';
}
$postCount = count($retVal);
$offset += $limit;
// Loop has a safety valve: if the count of records doesn't change
// in a full iteration, something has gone wrong, and we should stop
// so we don't loop forever!
} while ($total && $postCount < $total && $preCount != $postCount);
return $retVal;
}
/**
* Get Departments
*
* Obtain a list of departments for use in limiting the reserves list.
*
* @return array An associative array with key = dept. ID, value = dept. name.
*/
public function getDepartments()
{
return $this->getCourseResourceList('departments');
}
/**
* Get Instructors
*
* Obtain a list of instructors for use in limiting the reserves list.
*
* @return array An associative array with key = ID, value = name.
*/
public function getInstructors()
{
$retVal = [];
$ids = array_keys(
$this->getCourseResourceList('courselistings', 'courseListings')
);
foreach ($ids as $id) {
$retVal += $this->getCourseResourceList(
'courselistings/' . $id . '/instructors', 'instructors'
);
}
return $retVal;
}
/**
* Get Courses
*
* Obtain a list of courses for use in limiting the reserves list.
*
* @return array An associative array with key = ID, value = name.
*/
public function getCourses()
{
return $this->getCourseResourceList('courses');
}
/**
* Given a course listing ID, get an array of associated courses.
*
* @param string $courseListingId Course listing ID
*
* @return array
*/
protected function getCourseDetails($courseListingId)
{
$values = empty($courseListingId)
? []
: $this->getCourseResourceList(
'courselistings/' . $courseListingId . '/courses',
'courses',
'departmentId'
);
// Return an array with empty values in it if we can't find any values,
// because we want to loop at least once to build our reserves response.
return empty($values) ? ['' => ''] : $values;
}
/**
* Given a course listing ID, get an array of associated instructors.
*
* @param string $courseListingId Course listing ID
*
* @return array
*/
protected function getInstructorIds($courseListingId)
{
$values = empty($courseListingId)
? []
: $this->getCourseResourceList(
'courselistings/' . $courseListingId . '/instructors', 'instructors'
);
// Return an array with null in it if we can't find any values, because
// we want to loop at least once to build our course reserves response.
return empty($values) ? [null] : array_keys($values);
}
/**
* Find Reserves
*
* Obtain information on course reserves.
*
* @param string $course ID from getCourses (empty string to match all)
* @param string $inst ID from getInstructors (empty string to match all)
* @param string $dept ID from getDepartments (empty string to match all)
*
* @return mixed An array of associative arrays representing reserve items.
*/
public function findReserves($course, $inst, $dept)
{
$retVal = [];
$limit = 1000; // how many records to retrieve at once
$offset = 0;
// Results can be paginated, so let's loop until we've gotten everything:
do {
$response = $this->makeRequest(
'GET',
'/coursereserves/reserves',
compact('offset', 'limit')
);
$json = json_decode($response->getBody());
$total = $json->totalRecords ?? 0;
$preCount = count($retVal);
foreach ($json->reserves ?? [] as $item) {
try {
$bibId = $this->getBibId(null, null, $item->itemId);
} catch (\Exception $e) {
$bibId = null;
}
if ($bibId !== null) {
$courseData = $this->getCourseDetails(
$item->courseListingId ?? null
);
$instructorIds = $this->getInstructorIds(
$item->courseListingId ?? null
);
foreach ($courseData as $courseId => $departmentId) {
foreach ($instructorIds as $instructorId) {
$retVal[] = [
'BIB_ID' => $bibId,
'COURSE_ID' => $courseId == '' ? null : $courseId,
'DEPARTMENT_ID' => $departmentId == ''
? null : $departmentId,
'INSTRUCTOR_ID' => $instructorId,
];
}
}
}
}
$postCount = count($retVal);
$offset += $limit;
// Loop has a safety valve: if the count of records doesn't change
// in a full iteration, something has gone wrong, and we should stop
// so we don't loop forever!
} while ($total && $postCount < $total && $preCount != $postCount);
// If the user has requested a filter, apply it now:
if (!empty($course) || !empty($inst) || !empty($dept)) {
$filter = function ($value) use ($course, $inst, $dept) {
return (empty($course) || $course == $value['COURSE_ID'])
&& (empty($inst) || $inst == $value['INSTRUCTOR_ID'])
&& (empty($dept) || $dept == $value['DEPARTMENT_ID']);
};
return array_filter($retVal, $filter);
}
return $retVal;
}
// @codingStandardsIgnoreStart
/** NOT FINISHED BELOW THIS LINE **/
/**
* Check for request blocks.
*
* @param array $patron The patron array with username and password
*
* @return array|boolean An array of block messages or false if there are no
* blocks
* @author Michael Birkner
*/
public function getRequestBlocks($patron)
{
return false;
}
/**
* This method returns information on recently received issues of a serial.
*
* Input: Bibliographic record ID
* Output: Array of associative arrays, each with a single key:
* issue - String describing the issue
*
* Currently, most drivers do not implement this method, instead always returning
* an empty array. It is only necessary to implement this in more detail if you
* want to populate the “Most Recent Received Issues” section of the record
* holdings tab.
*/
public function getPurchaseHistory($bibID)
{
return [];
}
/**
* This method queries the ILS for a patron's current fines
*
* Input: Patron array returned by patronLogin method
* Output: Returns an array of associative arrays, one for each fine
* associated with the specified account. Each associative array contains
* these keys:
* amount - The total amount of the fine IN PENNIES. Be sure to adjust
* decimal points appropriately (i.e. for a $1.00 fine, amount should be 100).
* checkout - A string representing the date when the item was
* checked out.
* fine - A string describing the reason for the fine
* (i.e. “Overdue”, “Long Overdue”).
* balance - The unpaid portion of the fine IN PENNIES.
* createdate – A string representing the date when the fine was accrued
* (optional)
* duedate - A string representing the date when the item was due.
* id - The bibliographic ID of the record involved in the fine.
* source - The search backend from which the record may be retrieved
* (optional - defaults to Solr). Introduced in VuFind 2.4.
*
*/
public function getMyFines($patron)
{
$query = ['query' => 'userId==' . $patron['id'] . ' and status.name<>Closed'];
$response = $this->makeRequest("GET", '/accounts', $query);
$json = json_decode($response->getBody());
if (count($json->accounts) == 0) {
return [];
}
$fines = [];
foreach ($json->accounts as $fine) {
$date = date_create($fine->metadata->createdDate);
$title = (isset($fine->title) ? $fine->title : null);
$fines[] = [
'id' => $fine->id,
'amount' => $fine->amount * 100,
'balance' => $fine->remaining * 100,
'status' => $fine->paymentStatus->name,
'type' => $fine->feeFineType,
'title' => $title,
'createdate' => date_format($date, "j M Y")
];
}
return $fines;
}
/**
* Get a list of funds that can be used to limit the “new item” search. Note that
* “fund” may be a misnomer – if funds are not an appropriate way to limit your
* new item results, you can return a different set of values from this function.
* For example, you might just make this a wrapper for getDepartments(). The
* important thing is that whatever you return from this function, the IDs can be
* used as a limiter to the getNewItems() function, and the names are appropriate
* for display on the new item search screen. If you do not want or support such
* limits, just return an empty array here and the limit control on the new item
* search screen will disappear.
*
* Output: An associative array with key = fund ID, value = fund name.
*
* IMPORTANT: The return value for this method changed in r2184. If you are using
* VuFind 1.0RC2 or earlier, this function returns a flat array of options
* (no ID-based keys), and empty return values may cause problems. It is
* recommended that you update to newer code before implementing the new item
* feature in your driver.
*/
public function getFunds()
{
return [];
}
/**
* This method retrieves a patron's historic transactions
* (previously checked out items).
*
* :!: The getConfig method must return a non-false value for this feature to be
* enabled. For privacy reasons, the entire feature should be disabled by default
* unless explicitly turned on in the driver's .ini file.
*
* This feature was added in VuFind 5.0.
*
* getConfig may return the following keys if the service supports paging on
* the ILS side:
* max_results - Maximum number of results that can be requested at once.
* Overrides the config.ini Catalog section setting historic_loan_page_size.
* page_size - An array of allowed page sizes
* (number of records per page)
* default_page_size - Default number of records per page
* getConfig may return the following keys if the service supports sorting:
* sort - An associative array where each key is a sort key and its
* value is a translation key
* default_sort - Default sort key
* Input: Patron array returned by patronLogin method and an array of
* optional parameters (keys = 'limit', 'page', 'sort').
* Output: Returns an array of associative arrays containing some or all of
* these keys:
* title - item title
* checkoutDate - date checked out
* dueDate - date due
* id - bibliographic ID
* barcode - item barcode
* returnDate - date returned
* publication_year - publication year
* volume - item volume
* institution_name - owning institution
* borrowingLocation - checkout location
* message - message about the transaction
*
*/
public function getMyTransactionHistory($patron)
{
return[];
}
/**
* This method queries the ILS for new items
*
* Input: getNewItems takes the following parameters:
* page - page number of results to retrieve (counting starts at 1)
* limit - the size of each page of results to retrieve
* daysOld - the maximum age of records to retrieve in days (maximum 30)
* fundID - optional fund ID to use for limiting results (use a value
* returned by getFunds, or exclude for no limit); note that “fund” may be a
* misnomer – if funds are not an appropriate way to limit your new item results,
* you can return a different set of values from getFunds. The important thing is
* that this parameter supports an ID returned by getFunds, whatever that may
* mean.
* Output: An associative array with two keys: 'count' (the number of items
* in the 'results' array) and 'results' (an array of associative arrays, each
* with a single key: 'id', a record ID).
*
* IMPORTANT: The fundID parameter changed behavior in r2184. In VuFind 1.0RC2
* and earlier versions, it receives one of the VALUES returned by getFunds();
* in more recent code, it receives one of the KEYS from getFunds(). See getFunds
* for additional notes.
*/
public function getNewItems($page = 1, $limit, $daysOld = 30, $fundID = null)
{
return [];
}
// @codingStandardsIgnoreEnd
}
| 1 | 29,663 | I don't think `?? null` works here... that's to ensure PHP doesn't throw an "undefined" error about `$profile->expirationDate`, but now the code is assuming that `$profile->expirationDate` will be set. Might be cleaner to do: <pre> $expiration = isset($profile->expirationDate) ? $this->dateConverter->convertToDisplayDate("Y-m-d H:i", $profile->expirationDate) : null; </pre> And then assigning the `$expiration` value in the return array... | vufind-org-vufind | php |
@@ -0,0 +1,8 @@
+import Vue from 'vue'
+import App from './App.vue'
+
+Vue.config.productionTip = false
+
+new Vue({
+ render: h => h(App),
+}).$mount('#app') | 1 | 1 | 17,921 | An ENV should be used? Are you sure that the Vue examples are built in the production mode? | handsontable-handsontable | js |
|
@@ -52,7 +52,7 @@ class NodeResult(
warn (Optional[Any]): The ``warn`` field from the results of the executed dbt node.
skip (Optional[Any]): The ``skip`` field from the results of the executed dbt node.
status (Optional[Union[str,int]]): The status of the executed dbt node (model).
- execution_time (float): The execution duration (in seconds) of the dbt node (model).
+ execution_time (Union[float,int]): The execution duration (in seconds) of the dbt node (model).
thread_id (str): The dbt thread identifier that executed the dbt node (model).
step_timings (List[StepTiming]): The timings for each step in the executed dbt node
(model). | 1 | from collections import namedtuple
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Union
from dagster import check
from dateutil import parser
class StepTiming(namedtuple("_StepTiming", "name started_at completed_at")):
"""The timing information of an executed step for a dbt node (model).
Note that users should not construct instances of this class directly. This class is intended to be
constructed from the JSON output of dbt commands.
Attributes:
name (str): The name of the executed step.
started_at (datetime.datetime): An ISO string timestamp of when the step started executing.
completed_at (datetime.datetime): An ISO string timestamp of when the step completed
execution.
"""
def __new__(cls, name: str, started_at: datetime, completed_at: datetime):
return super().__new__(
cls,
check.str_param(name, "name"),
check.inst_param(started_at, "started_at", datetime),
check.inst_param(completed_at, "completed_at", datetime),
)
@property
def duration(self) -> timedelta:
"""datetime.timedelta: The execution duration of the step."""
return self.completed_at - self.started_at
class NodeResult(
namedtuple(
"_NodeResult",
"node unique_id error status execution_time thread_id step_timings table fail warn skip",
),
):
"""The result of executing a dbt node (model).
Note that users should not construct instances of this class directly. This class is intended to be
constructed from the JSON output of dbt commands.
Attributes:
node (Dict[str, Any]): Details about the executed dbt node (model).
unique_id (Optional[str]): The unique identifier for the executed dbt node.
error (Optional[str]): An error message if an error occurred.
fail (Optional[Any]): The ``fail`` field from the results of the executed dbt node.
warn (Optional[Any]): The ``warn`` field from the results of the executed dbt node.
skip (Optional[Any]): The ``skip`` field from the results of the executed dbt node.
status (Optional[Union[str,int]]): The status of the executed dbt node (model).
execution_time (float): The execution duration (in seconds) of the dbt node (model).
thread_id (str): The dbt thread identifier that executed the dbt node (model).
step_timings (List[StepTiming]): The timings for each step in the executed dbt node
(model).
table (Optional[Dict]): Details about the table/view that is created from executing a
`run_sql <https://docs.getdbt.com/reference/commands/rpc#executing-a-query>`_
command on an dbt RPC server.
"""
def __new__(
cls,
node: Optional[Dict[str, Any]] = None,
unique_id: Optional[str] = None,
error: Optional[str] = None,
status: Optional[Union[str, int]] = None,
execution_time: Optional[float] = None,
thread_id: Optional[str] = None,
step_timings: List[StepTiming] = None,
table: Optional[Dict[str, Any]] = None,
fail: Optional[Any] = None,
warn: Optional[Any] = None,
skip: Optional[Any] = None,
):
step_timings = check.list_param(step_timings, "step_timings", of_type=StepTiming)
return super().__new__(
cls,
check.opt_dict_param(node, "node"),
check.opt_str_param(unique_id, "unique_id"),
check.opt_str_param(error, "error"),
status,
check.opt_float_param(execution_time, "execution_time"),
check.opt_str_param(thread_id, "thread_id"),
step_timings,
check.opt_dict_param(table, "table"),
fail,
warn,
skip,
)
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "NodeResult":
"""Constructs an instance of :class:`NodeResult <dagster_dbt.NodeResult>` from a dictionary.
Args:
d (Dict[str, Any]): A dictionary with key-values to construct a :class:`NodeResult
<dagster_dbt.NodeResult>`.
Returns:
NodeResult: An instance of :class:`NodeResult <dagster_dbt.NodeResult>`.
"""
# When executing from the CLI in 0.19.x, we get unique_id as a top level attribute
if "unique_id" in d:
unique_id = check.str_elem(d, "unique_id")
node = None
# When executing via RPC server or via CLI in 0.18.x or lower, we get unique id within
# "node" schema
else:
node = check.dict_elem(d, "node")
unique_id = check.str_elem(node, "unique_id")
error = check.opt_str_elem(d, "error")
execution_time = check.float_elem(d, "execution_time")
thread_id = check.opt_str_elem(d, "thread_id")
check.list_elem(d, "timing")
step_timings = [
StepTiming(
name=d["name"],
started_at=parser.isoparse(d["started_at"]),
completed_at=parser.isoparse(d["completed_at"]),
)
for d in check.is_list(d["timing"], of_type=Dict)
]
table = check.opt_dict_elem(d, "table")
return cls(
node=node,
unique_id=unique_id,
step_timings=step_timings,
error=error,
execution_time=execution_time,
thread_id=thread_id,
table=table,
)
class DbtResult(namedtuple("_DbtResult", "logs results generated_at elapsed_time")):
"""The results of executing a dbt command.
Note that users should not construct instances of this class directly. This class is intended to be
constructed from the JSON output of dbt commands.
Attributes:
logs (List[Dict[str, Any]]): JSON log output from the dbt process.
results (List[NodeResult]]): Details about each executed dbt node (model) in the run.
generated_at (str): An ISO string timestamp of when the run result was generated by dbt.
elapsed_time (float): The execution duration (in seconds) of the run.
"""
def __new__(
cls,
logs: List[Dict[str, Any]],
results: List[NodeResult],
generated_at: Optional[str] = None,
elapsed_time: Optional[float] = None,
):
return super().__new__(
cls,
check.list_param(logs, "logs", of_type=Dict),
results,
check.opt_str_param(generated_at, "generated_at"),
check.opt_float_param(elapsed_time, "elapsed_time"),
)
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "DbtResult":
"""Constructs an instance of :class:`DbtResult <dagster_dbt.DbtResult>` from a dictionary.
Args:
d (Dict[str, Any]): A dictionary with key-values to construct a :class:`DbtResult
<dagster_dbt.DbtResult>`.
Returns:
DbtResult: An instance of :class:`DbtResult <dagster_dbt.DbtResult>`.
"""
check.list_elem(d, "logs")
logs = check.is_list(d["logs"], of_type=Dict)
check.list_elem(d, "results")
results = [NodeResult.from_dict(d) for d in check.is_list(d["results"], of_type=Dict)]
generated_at = check.opt_str_elem(d, "generated_at")
elapsed_time = check.float_elem(d, "elapsed_time")
return cls(
logs=logs,
results=results,
generated_at=generated_at,
elapsed_time=elapsed_time,
)
def __len__(self) -> int:
return len(self.results)
| 1 | 14,464 | Nit: this should actually always be float since we convert it before we construct the namedtuple. | dagster-io-dagster | py |
@@ -99,7 +99,13 @@ RocksEngine::RocksEngine(GraphSpaceID spaceId,
, dataPath_(folly::stringPrintf("%s/nebula/%d", dataPath.c_str(), spaceId)) {
auto path = folly::stringPrintf("%s/data", dataPath_.c_str());
if (FileUtils::fileType(path.c_str()) == FileType::NOTEXIST) {
- FileUtils::makeDir(path);
+ if (!FileUtils::makeDir(path)) {
+ LOG(FATAL) << "makeDir " << path << " failed";
+ }
+ }
+
+ if (FileUtils::fileType(path.c_str()) != FileType::DIRECTORY) {
+ LOG(FATAL) << path << " is not directory";
}
rocksdb::Options options; | 1 | /* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "base/Base.h"
#include "kvstore/RocksEngine.h"
#include <folly/String.h>
#include "fs/FileUtils.h"
#include "kvstore/KVStore.h"
#include "kvstore/RocksEngineConfig.h"
namespace nebula {
namespace kvstore {
using fs::FileUtils;
using fs::FileType;
namespace {
/***************************************
*
* Implementation of WriteBatch
*
**************************************/
class RocksWriteBatch : public WriteBatch {
private:
rocksdb::WriteBatch batch_;
rocksdb::DB* db_{nullptr};
public:
explicit RocksWriteBatch(rocksdb::DB* db) : batch_(FLAGS_rocksdb_batch_size), db_(db) {}
virtual ~RocksWriteBatch() = default;
ResultCode put(folly::StringPiece key, folly::StringPiece value) override {
if (batch_.Put(toSlice(key), toSlice(value)).ok()) {
return ResultCode::SUCCEEDED;
} else {
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode remove(folly::StringPiece key) override {
if (batch_.Delete(toSlice(key)).ok()) {
return ResultCode::SUCCEEDED;
} else {
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode removePrefix(folly::StringPiece prefix) override {
rocksdb::Slice pre(prefix.begin(), prefix.size());
rocksdb::ReadOptions options;
std::unique_ptr<rocksdb::Iterator> iter(db_->NewIterator(options));
iter->Seek(pre);
while (iter->Valid()) {
if (iter->key().starts_with(pre)) {
if (!batch_.Delete(iter->key()).ok()) {
return ResultCode::ERR_UNKNOWN;
}
} else {
// Done
break;
}
iter->Next();
}
return ResultCode::SUCCEEDED;
}
// Remove all keys in the range [start, end)
ResultCode removeRange(folly::StringPiece start, folly::StringPiece end) override {
if (batch_.DeleteRange(toSlice(start), toSlice(end)).ok()) {
return ResultCode::SUCCEEDED;
} else {
return ResultCode::ERR_UNKNOWN;
}
}
rocksdb::WriteBatch* data() {
return &batch_;
}
};
} // Anonymous namespace
/***************************************
*
* Implementation of WriteBatch
*
**************************************/
RocksEngine::RocksEngine(GraphSpaceID spaceId,
const std::string& dataPath,
std::shared_ptr<rocksdb::MergeOperator> mergeOp,
std::shared_ptr<rocksdb::CompactionFilterFactory> cfFactory)
: KVEngine(spaceId)
, dataPath_(folly::stringPrintf("%s/nebula/%d", dataPath.c_str(), spaceId)) {
auto path = folly::stringPrintf("%s/data", dataPath_.c_str());
if (FileUtils::fileType(path.c_str()) == FileType::NOTEXIST) {
FileUtils::makeDir(path);
}
rocksdb::Options options;
rocksdb::DB* db = nullptr;
rocksdb::Status status = initRocksdbOptions(options);
CHECK(status.ok());
if (mergeOp != nullptr) {
options.merge_operator = mergeOp;
}
if (cfFactory != nullptr) {
options.compaction_filter_factory = cfFactory;
}
status = rocksdb::DB::Open(options, path, &db);
CHECK(status.ok()) << status.ToString();
db_.reset(db);
partsNum_ = allParts().size();
LOG(INFO) << "open rocksdb on " << path;
}
std::unique_ptr<WriteBatch> RocksEngine::startBatchWrite() {
return std::make_unique<RocksWriteBatch>(db_.get());
}
ResultCode RocksEngine::commitBatchWrite(std::unique_ptr<WriteBatch> batch) {
rocksdb::WriteOptions options;
options.disableWAL = FLAGS_rocksdb_disable_wal;
auto* b = static_cast<RocksWriteBatch*>(batch.get());
rocksdb::Status status = db_->Write(options, b->data());
if (status.ok()) {
return ResultCode::SUCCEEDED;
}
return ResultCode::ERR_UNKNOWN;
}
ResultCode RocksEngine::get(const std::string& key, std::string* value) {
rocksdb::ReadOptions options;
rocksdb::Status status = db_->Get(options, rocksdb::Slice(key), value);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else if (status.IsNotFound()) {
VLOG(3) << "Get: " << key << " Not Found";
return ResultCode::ERR_KEY_NOT_FOUND;
} else {
VLOG(3) << "Get Failed: " << key << " " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::multiGet(const std::vector<std::string>& keys,
std::vector<std::string>* values) {
rocksdb::ReadOptions options;
std::vector<rocksdb::Slice> slices;
for (size_t index = 0; index < keys.size(); index++) {
slices.emplace_back(keys[index]);
}
std::vector<rocksdb::Status> status = db_->MultiGet(options, slices, values);
auto code = std::all_of(status.begin(), status.end(),
[](rocksdb::Status s) {
return s.ok();
});
if (code) {
return ResultCode::SUCCEEDED;
} else {
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::range(const std::string& start,
const std::string& end,
std::unique_ptr<KVIterator>* storageIter) {
rocksdb::ReadOptions options;
rocksdb::Iterator* iter = db_->NewIterator(options);
if (iter) {
iter->Seek(rocksdb::Slice(start));
}
storageIter->reset(new RocksRangeIter(iter, start, end));
return ResultCode::SUCCEEDED;
}
ResultCode RocksEngine::prefix(const std::string& prefix,
std::unique_ptr<KVIterator>* storageIter) {
rocksdb::ReadOptions options;
rocksdb::Iterator* iter = db_->NewIterator(options);
if (iter) {
iter->Seek(rocksdb::Slice(prefix));
}
storageIter->reset(new RocksPrefixIter(iter, prefix));
return ResultCode::SUCCEEDED;
}
ResultCode RocksEngine::rangeWithPrefix(const std::string& start,
const std::string& prefix,
std::unique_ptr<KVIterator>* storageIter) {
rocksdb::ReadOptions options;
rocksdb::Iterator* iter = db_->NewIterator(options);
if (iter) {
iter->Seek(rocksdb::Slice(start));
}
storageIter->reset(new RocksPrefixIter(iter, prefix));
return ResultCode::SUCCEEDED;
}
ResultCode RocksEngine::put(std::string key, std::string value) {
rocksdb::WriteOptions options;
options.disableWAL = FLAGS_rocksdb_disable_wal;
rocksdb::Status status = db_->Put(options, key, value);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "Put Failed: " << key << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::multiPut(std::vector<KV> keyValues) {
rocksdb::WriteBatch updates(FLAGS_rocksdb_batch_size);
for (size_t i = 0; i < keyValues.size(); i++) {
updates.Put(keyValues[i].first, keyValues[i].second);
}
rocksdb::WriteOptions options;
options.disableWAL = FLAGS_rocksdb_disable_wal;
rocksdb::Status status = db_->Write(options, &updates);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "MultiPut Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::remove(const std::string& key) {
rocksdb::WriteOptions options;
options.disableWAL = FLAGS_rocksdb_disable_wal;
auto status = db_->Delete(options, key);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "Remove Failed: " << key << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::multiRemove(std::vector<std::string> keys) {
rocksdb::WriteBatch deletes(FLAGS_rocksdb_batch_size);
for (size_t i = 0; i < keys.size(); i++) {
deletes.Delete(keys[i]);
}
rocksdb::WriteOptions options;
options.disableWAL = FLAGS_rocksdb_disable_wal;
rocksdb::Status status = db_->Write(options, &deletes);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "MultiRemove Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::removeRange(const std::string& start,
const std::string& end) {
rocksdb::WriteOptions options;
options.disableWAL = FLAGS_rocksdb_disable_wal;
// TODO(sye) Given the RocksDB version we are using,
// we should avoud using DeleteRange
auto status = db_->DeleteRange(options, db_->DefaultColumnFamily(), start, end);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "RemoveRange Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::removePrefix(const std::string& prefix) {
rocksdb::Slice pre(prefix.data(), prefix.size());
rocksdb::ReadOptions readOptions;
rocksdb::WriteBatch batch;
std::unique_ptr<rocksdb::Iterator> iter(db_->NewIterator(readOptions));
iter->Seek(pre);
while (iter->Valid()) {
if (iter->key().starts_with(pre)) {
auto status = batch.Delete(iter->key());
if (!status.ok()) {
return ResultCode::ERR_UNKNOWN;
}
} else {
// Done
break;
}
iter->Next();
}
rocksdb::WriteOptions writeOptions;
writeOptions.disableWAL = FLAGS_rocksdb_disable_wal;
if (db_->Write(writeOptions, &batch).ok()) {
return ResultCode::SUCCEEDED;
} else {
return ResultCode::ERR_UNKNOWN;
}
}
std::string RocksEngine::partKey(PartitionID partId) {
return NebulaKeyUtils::systemPartKey(partId);
}
void RocksEngine::addPart(PartitionID partId) {
auto ret = put(partKey(partId), "");
if (ret == ResultCode::SUCCEEDED) {
partsNum_++;
CHECK_GE(partsNum_, 0);
}
}
void RocksEngine::removePart(PartitionID partId) {
rocksdb::WriteOptions options;
options.disableWAL = FLAGS_rocksdb_disable_wal;
auto status = db_->Delete(options, partKey(partId));
if (status.ok()) {
partsNum_--;
CHECK_GE(partsNum_, 0);
}
}
std::vector<PartitionID> RocksEngine::allParts() {
std::unique_ptr<KVIterator> iter;
static const std::string prefixStr = NebulaKeyUtils::systemPrefix();
CHECK_EQ(ResultCode::SUCCEEDED, this->prefix(prefixStr, &iter));
std::vector<PartitionID> parts;
while (iter->valid()) {
auto key = iter->key();
CHECK_EQ(key.size(), sizeof(PartitionID) + sizeof(NebulaSystemKeyType));
PartitionID partId = *reinterpret_cast<const PartitionID*>(key.data());
if (!NebulaKeyUtils::isSystemPart(key)) {
VLOG(3) << "Skip: " << std::bitset<32>(partId);
iter->next();
continue;
}
partId = partId >> 8;
parts.emplace_back(partId);
iter->next();
}
return parts;
}
int32_t RocksEngine::totalPartsNum() {
return partsNum_;
}
ResultCode RocksEngine::ingest(const std::vector<std::string>& files) {
rocksdb::IngestExternalFileOptions options;
rocksdb::Status status = db_->IngestExternalFile(files, options);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "Ingest Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::setOption(const std::string& configKey,
const std::string& configValue) {
std::unordered_map<std::string, std::string> configOptions = {
{configKey, configValue}
};
rocksdb::Status status = db_->SetOptions(configOptions);
if (status.ok()) {
LOG(INFO) << "SetOption Succeeded: " << configKey << ":" << configValue;
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "SetOption Failed: " << configKey << ":" << configValue;
return ResultCode::ERR_INVALID_ARGUMENT;
}
}
ResultCode RocksEngine::setDBOption(const std::string& configKey,
const std::string& configValue) {
std::unordered_map<std::string, std::string> configOptions = {
{configKey, configValue}
};
rocksdb::Status status = db_->SetDBOptions(configOptions);
if (status.ok()) {
LOG(INFO) << "SetDBOption Succeeded: " << configKey << ":" << configValue;
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "SetDBOption Failed: " << configKey << ":" << configValue;
return ResultCode::ERR_INVALID_ARGUMENT;
}
}
ResultCode RocksEngine::compact() {
rocksdb::CompactRangeOptions options;
rocksdb::Status status = db_->CompactRange(options, nullptr, nullptr);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "CompactAll Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::flush() {
rocksdb::FlushOptions options;
rocksdb::Status status = db_->Flush(options);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "Flush Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode RocksEngine::createCheckpoint(const std::string& name) {
LOG(INFO) << "Begin checkpoint : " << dataPath_;
/*
* The default checkpoint directory structure is :
* |--FLAGS_data_path
* |----nebula
* |------space1
* |--------data
* |--------wal
* |--------checkpoints
* |----------snapshot1
* |------------data
* |------------wal
* |----------snapshot2
* |----------snapshot3
*
*/
auto checkpointPath = folly::stringPrintf("%s/checkpoints/%s/data",
dataPath_.c_str(), name.c_str());
LOG(INFO) << "Target checkpoint path : " << checkpointPath;
if (fs::FileUtils::exist(checkpointPath)) {
LOG(ERROR) << "The snapshot file already exists: " << checkpointPath;
return ResultCode::ERR_CHECKPOINT_ERROR;
}
auto parent = checkpointPath.substr(0, checkpointPath.rfind('/'));
if (!FileUtils::exist(parent)) {
FileUtils::makeDir(parent);
}
rocksdb::Checkpoint* checkpoint;
rocksdb::Status status = rocksdb::Checkpoint::Create(db_.get(), &checkpoint);
std::unique_ptr<rocksdb::Checkpoint> cp(checkpoint);
if (!status.ok()) {
LOG(ERROR) << "Init checkpoint Failed: " << status.ToString();
return ResultCode::ERR_CHECKPOINT_ERROR;
}
status = cp->CreateCheckpoint(checkpointPath, 0);
if (!status.ok()) {
LOG(ERROR) << "Create checkpoint Failed: " << status.ToString();
return ResultCode::ERR_CHECKPOINT_ERROR;
}
return ResultCode::SUCCEEDED;
}
} // namespace kvstore
} // namespace nebula
| 1 | 28,203 | The result of `FileUtils::fileType` could be saved, instead of calling twice. | vesoft-inc-nebula | cpp |
@@ -71,7 +71,10 @@ abstract class BaseProvider implements MediaProviderInterface
return;
}
- $this->doTransform($media);
+ try {
+ $this->doTransform($media);
+ } catch (\Exception $e) {
+ }
}
/** | 1 | <?php
/*
* This file is part of the Sonata project.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\MediaBundle\Provider;
use Gaufrette\Filesystem;
use Sonata\CoreBundle\Model\Metadata;
use Sonata\MediaBundle\Resizer\ResizerInterface;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\CDN\CDNInterface;
use Sonata\MediaBundle\Generator\GeneratorInterface;
use Sonata\MediaBundle\Thumbnail\ThumbnailInterface;
use Sonata\AdminBundle\Validator\ErrorElement;
abstract class BaseProvider implements MediaProviderInterface
{
/**
* @var array
*/
protected $formats = array();
protected $templates = array();
protected $resizer;
protected $filesystem;
protected $pathGenerator;
protected $cdn;
protected $thumbnail;
/**
* @param string $name
* @param \Gaufrette\Filesystem $filesystem
* @param \Sonata\MediaBundle\CDN\CDNInterface $cdn
* @param \Sonata\MediaBundle\Generator\GeneratorInterface $pathGenerator
* @param \Sonata\MediaBundle\Thumbnail\ThumbnailInterface $thumbnail
*/
public function __construct($name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail)
{
$this->name = $name;
$this->filesystem = $filesystem;
$this->cdn = $cdn;
$this->pathGenerator = $pathGenerator;
$this->thumbnail = $thumbnail;
}
/**
* @param \Sonata\MediaBundle\Model\MediaInterface $media
*
* @return void
*/
abstract protected function doTransform(MediaInterface $media);
/**
* {@inheritdoc}
*/
final public function transform(MediaInterface $media)
{
if (null === $media->getBinaryContent()) {
return;
}
$this->doTransform($media);
}
/**
* {@inheritdoc}
*/
public function addFormat($name, $format)
{
$this->formats[$name] = $format;
}
/**
* {@inheritdoc}
*/
public function getFormat($name)
{
return isset($this->formats[$name]) ? $this->formats[$name] : false;
}
/**
* {@inheritdoc}
*/
public function requireThumbnails()
{
return $this->getResizer() !== null;
}
/**
* {@inheritdoc}
*/
public function generateThumbnails(MediaInterface $media)
{
$this->thumbnail->generate($this, $media);
}
/**
* {@inheritdoc}
*/
public function removeThumbnails(MediaInterface $media)
{
$this->thumbnail->delete($this, $media);
}
/**
* {@inheritdoc}
*/
public function getFormatName(MediaInterface $media, $format)
{
if ($format == 'admin') {
return 'admin';
}
if ($format == 'reference') {
return 'reference';
}
$baseName = $media->getContext().'_';
if (substr($format, 0, strlen($baseName)) == $baseName) {
return $format;
}
return $baseName.$format;
}
/**
* {@inheritdoc}
*/
public function getProviderMetadata()
{
return new Metadata($this->getName(), $this->getName().".description", null, "SonataMediaBundle", array('class' => 'fa fa-file'));
}
/**
* {@inheritdoc}
*/
public function preRemove(MediaInterface $media)
{
}
/**
* {@inheritdoc}
*/
public function postRemove(MediaInterface $media)
{
$path = $this->getReferenceImage($media);
if ($this->getFilesystem()->has($path)) {
$this->getFilesystem()->delete($path);
}
if ($this->requireThumbnails()) {
$this->thumbnail->delete($this, $media);
}
}
/**
* {@inheritdoc}
*/
public function generatePath(MediaInterface $media)
{
return $this->pathGenerator->generatePath($media);
}
/**
* {@inheritdoc}
*/
public function getFormats()
{
return $this->formats;
}
/**
* {@inheritdoc}
*/
public function setName($name)
{
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function setTemplates(array $templates)
{
$this->templates = $templates;
}
/**
*
* @return array
*/
public function getTemplates()
{
return $this->templates;
}
/**
* {@inheritdoc}
*/
public function getTemplate($name)
{
return isset($this->templates[$name]) ? $this->templates[$name] : null;
}
/**
* {@inheritdoc}
*/
public function getResizer()
{
return $this->resizer;
}
/**
* {@inheritdoc}
*/
public function getFilesystem()
{
return $this->filesystem;
}
/**
* {@inheritdoc}
*/
public function getCdn()
{
return $this->cdn;
}
/**
* {@inheritdoc}
*/
public function getCdnPath($relativePath, $isFlushable)
{
return $this->getCdn()->getPath($relativePath, $isFlushable);
}
/**
* {@inheritdoc}
*/
public function setResizer(ResizerInterface $resizer)
{
$this->resizer = $resizer;
}
/**
* {@inheritdoc}
*/
public function prePersist(MediaInterface $media)
{
$media->setCreatedAt(new \Datetime());
$media->setUpdatedAt(new \Datetime());
}
/**
* {@inheritdoc}
*/
public function preUpdate(MediaInterface $media)
{
$media->setUpdatedAt(new \Datetime());
}
/**
* {@inheritdoc}
*/
public function validate(ErrorElement $errorElement, MediaInterface $media)
{
}
}
| 1 | 6,377 | Can you log the exception ? | sonata-project-SonataMediaBundle | php |
@@ -113,6 +113,9 @@ static int http_post(struct flb_out_http *ctx,
ctx->host, ctx->port,
ctx->proxy, 0);
+
+ flb_debug("[http_client] proxy host: %s port: %i", c->proxy.host, c->proxy.port);
+
/* Allow duplicated headers ? */
flb_http_allow_duplicated_headers(c, ctx->allow_dup_headers);
| 1 | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2019-2020 The Fluent Bit Authors
* Copyright (C) 2015-2018 Treasure Data 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 <fluent-bit/flb_output_plugin.h>
#include <fluent-bit/flb_output.h>
#include <fluent-bit/flb_http_client.h>
#include <fluent-bit/flb_pack.h>
#include <fluent-bit/flb_str.h>
#include <fluent-bit/flb_time.h>
#include <fluent-bit/flb_utils.h>
#include <fluent-bit/flb_pack.h>
#include <fluent-bit/flb_sds.h>
#include <fluent-bit/flb_gzip.h>
#include <msgpack.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include "http.h"
#include "http_conf.h"
#include <fluent-bit/flb_callback.h>
static int cb_http_init(struct flb_output_instance *ins,
struct flb_config *config, void *data)
{
struct flb_out_http *ctx = NULL;
(void) data;
ctx = flb_http_conf_create(ins, config);
if (!ctx) {
return -1;
}
/* Set the plugin context */
flb_output_set_context(ins, ctx);
/*
* This plugin instance uses the HTTP client interface, let's register
* it debugging callbacks.
*/
flb_output_set_http_debug_callbacks(ins);
return 0;
}
static int http_post(struct flb_out_http *ctx,
const void *body, size_t body_len,
const char *tag, int tag_len)
{
int ret;
int out_ret = FLB_OK;
int compressed = FLB_FALSE;
size_t b_sent;
void *payload_buf = NULL;
size_t payload_size = 0;
struct flb_upstream *u;
struct flb_upstream_conn *u_conn;
struct flb_http_client *c;
struct mk_list *head;
struct flb_config_map_val *mv;
struct flb_slist_entry *key = NULL;
struct flb_slist_entry *val = NULL;
/* Get upstream context and connection */
u = ctx->u;
u_conn = flb_upstream_conn_get(u);
if (!u_conn) {
flb_plg_error(ctx->ins, "no upstream connections available to %s:%i",
u->tcp_host, u->tcp_port);
return FLB_RETRY;
}
/* Map payload */
payload_buf = (void *) body;
payload_size = body_len;
/* Should we compress the payload ? */
if (ctx->compress_gzip == FLB_TRUE) {
ret = flb_gzip_compress((void *) body, body_len,
&payload_buf, &payload_size);
if (ret == -1) {
flb_plg_error(ctx->ins,
"cannot gzip payload, disabling compression");
}
else {
compressed = FLB_TRUE;
}
}
/* Create HTTP client context */
c = flb_http_client(u_conn, FLB_HTTP_POST, ctx->uri,
payload_buf, payload_size,
ctx->host, ctx->port,
ctx->proxy, 0);
/* Allow duplicated headers ? */
flb_http_allow_duplicated_headers(c, ctx->allow_dup_headers);
/*
* Direct assignment of the callback context to the HTTP client context.
* This needs to be improved through a more clean API.
*/
c->cb_ctx = ctx->ins->callback;
/* Append headers */
if ((ctx->out_format == FLB_PACK_JSON_FORMAT_JSON) ||
(ctx->out_format == FLB_PACK_JSON_FORMAT_STREAM) ||
(ctx->out_format == FLB_PACK_JSON_FORMAT_LINES) ||
(ctx->out_format == FLB_HTTP_OUT_GELF)) {
flb_http_add_header(c,
FLB_HTTP_CONTENT_TYPE,
sizeof(FLB_HTTP_CONTENT_TYPE) - 1,
FLB_HTTP_MIME_JSON,
sizeof(FLB_HTTP_MIME_JSON) - 1);
}
else {
flb_http_add_header(c,
FLB_HTTP_CONTENT_TYPE,
sizeof(FLB_HTTP_CONTENT_TYPE) - 1,
FLB_HTTP_MIME_MSGPACK,
sizeof(FLB_HTTP_MIME_MSGPACK) - 1);
}
if (ctx->header_tag) {
flb_http_add_header(c,
ctx->header_tag,
flb_sds_len(ctx->header_tag),
tag, tag_len);
}
/* Content Encoding: gzip */
if (compressed == FLB_TRUE) {
flb_http_set_content_encoding_gzip(c);
}
/* Basic Auth headers */
if (ctx->http_user && ctx->http_passwd) {
flb_http_basic_auth(c, ctx->http_user, ctx->http_passwd);
}
flb_http_add_header(c, "User-Agent", 10, "Fluent-Bit", 10);
flb_config_map_foreach(head, mv, ctx->headers) {
key = mk_list_entry_first(mv->val.list, struct flb_slist_entry, _head);
val = mk_list_entry_last(mv->val.list, struct flb_slist_entry, _head);
flb_http_add_header(c,
key->str, flb_sds_len(key->str),
val->str, flb_sds_len(val->str));
}
ret = flb_http_do(c, &b_sent);
if (ret == 0) {
/*
* Only allow the following HTTP status:
*
* - 200: OK
* - 201: Created
* - 202: Accepted
* - 203: no authorative resp
* - 204: No Content
* - 205: Reset content
*
*/
if (c->resp.status < 200 || c->resp.status > 205) {
if (c->resp.payload && c->resp.payload_size > 0) {
flb_plg_error(ctx->ins, "%s:%i, HTTP status=%i\n%s",
ctx->host, ctx->port,
c->resp.status, c->resp.payload);
}
else {
flb_plg_error(ctx->ins, "%s:%i, HTTP status=%i",
ctx->host, ctx->port, c->resp.status);
}
out_ret = FLB_RETRY;
}
else {
if (c->resp.payload && c->resp.payload_size > 0) {
flb_plg_info(ctx->ins, "%s:%i, HTTP status=%i\n%s",
ctx->host, ctx->port,
c->resp.status, c->resp.payload);
}
else {
flb_plg_info(ctx->ins, "%s:%i, HTTP status=%i",
ctx->host, ctx->port,
c->resp.status);
}
}
}
else {
flb_plg_error(ctx->ins, "could not flush records to %s:%i (http_do=%i)",
ctx->host, ctx->port, ret);
out_ret = FLB_RETRY;
}
/*
* If the payload buffer is different than incoming records in body, means
* we generated a different payload and must be freed.
*/
if (payload_buf != body) {
flb_free(payload_buf);
}
/* Destroy HTTP client context */
flb_http_client_destroy(c);
/* Release the TCP connection */
flb_upstream_conn_release(u_conn);
return out_ret;
}
static int http_gelf(struct flb_out_http *ctx,
const char *data, uint64_t bytes,
const char *tag, int tag_len)
{
flb_sds_t s;
flb_sds_t tmp = NULL;
msgpack_unpacked result;
size_t off = 0;
size_t size = 0;
msgpack_object root;
msgpack_object map;
msgpack_object *obj;
struct flb_time tm;
int ret;
size = bytes * 1.5;
/* Allocate buffer for our new payload */
s = flb_sds_create_size(size);
if (!s) {
return FLB_RETRY;
}
msgpack_unpacked_init(&result);
while (msgpack_unpack_next(&result, data, bytes, &off) ==
MSGPACK_UNPACK_SUCCESS) {
if (result.data.type != MSGPACK_OBJECT_ARRAY) {
continue;
}
root = result.data;
if (root.via.array.size != 2) {
continue;
}
flb_time_pop_from_msgpack(&tm, &result, &obj);
map = root.via.array.ptr[1];
tmp = flb_msgpack_to_gelf(&s, &map, &tm, &(ctx->gelf_fields));
if (!tmp) {
flb_plg_error(ctx->ins, "error encoding to GELF");
flb_sds_destroy(s);
msgpack_unpacked_destroy(&result);
return FLB_ERROR;
}
/* Append new line */
tmp = flb_sds_cat(s, "\n", 1);
if (!tmp) {
flb_plg_error(ctx->ins, "error concatenating records");
flb_sds_destroy(s);
msgpack_unpacked_destroy(&result);
return FLB_RETRY;
}
s = tmp;
}
ret = http_post(ctx, s, flb_sds_len(s), tag, tag_len);
flb_sds_destroy(s);
msgpack_unpacked_destroy(&result);
return ret;
}
static void cb_http_flush(const void *data, size_t bytes,
const char *tag, int tag_len,
struct flb_input_instance *i_ins,
void *out_context,
struct flb_config *config)
{
int ret = FLB_ERROR;
flb_sds_t json;
struct flb_out_http *ctx = out_context;
(void) i_ins;
if ((ctx->out_format == FLB_PACK_JSON_FORMAT_JSON) ||
(ctx->out_format == FLB_PACK_JSON_FORMAT_STREAM) ||
(ctx->out_format == FLB_PACK_JSON_FORMAT_LINES)) {
json = flb_pack_msgpack_to_json_format(data, bytes,
ctx->out_format,
ctx->json_date_format,
ctx->date_key);
if (json != NULL) {
ret = http_post(ctx, json, flb_sds_len(json), tag, tag_len);
flb_sds_destroy(json);
}
}
else if (ctx->out_format == FLB_HTTP_OUT_GELF) {
ret = http_gelf(ctx, data, bytes, tag, tag_len);
}
else {
ret = http_post(ctx, data, bytes, tag, tag_len);
}
FLB_OUTPUT_RETURN(ret);
}
static int cb_http_exit(void *data, struct flb_config *config)
{
struct flb_out_http *ctx = data;
flb_http_conf_destroy(ctx);
return 0;
}
/* Configuration properties map */
static struct flb_config_map config_map[] = {
{
FLB_CONFIG_MAP_STR, "proxy", NULL,
0, FLB_FALSE, 0,
"Specify an HTTP Proxy. The expected format of this value is http://host:port. "
},
{
FLB_CONFIG_MAP_BOOL, "allow_duplicated_headers", "true",
0, FLB_TRUE, offsetof(struct flb_out_http, allow_dup_headers),
"Specify if duplicated headers are allowed or not"
},
{
FLB_CONFIG_MAP_STR, "http_user", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, http_user),
"Set HTTP auth user"
},
{
FLB_CONFIG_MAP_STR, "http_passwd", "",
0, FLB_TRUE, offsetof(struct flb_out_http, http_passwd),
"Set HTTP auth password"
},
{
FLB_CONFIG_MAP_STR, "header_tag", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, header_tag),
"Set a HTTP header which value is the Tag"
},
{
FLB_CONFIG_MAP_STR, "format", NULL,
0, FLB_FALSE, 0,
"Set desired payload format: json, json_stream, json_lines, gelf or msgpack"
},
{
FLB_CONFIG_MAP_STR, "json_date_format", NULL,
0, FLB_FALSE, 0,
"Specify the format of the date. Supported formats are 'double' and 'iso8601'"
},
{
FLB_CONFIG_MAP_STR, "json_date_key", "date",
0, FLB_TRUE, offsetof(struct flb_out_http, json_date_key),
"Specify the name of the date field in output"
},
{
FLB_CONFIG_MAP_STR, "compress", NULL,
0, FLB_FALSE, 0,
"Set payload compression mechanism. Option available is 'gzip'"
},
{
FLB_CONFIG_MAP_SLIST_1, "header", NULL,
FLB_CONFIG_MAP_MULT, FLB_TRUE, offsetof(struct flb_out_http, headers),
"Add a HTTP header key/value pair. Multiple headers can be set"
},
{
FLB_CONFIG_MAP_STR, "uri", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, uri),
"Specify an optional HTTP URI for the target web server, e.g: /something"
},
/* Gelf Properties */
{
FLB_CONFIG_MAP_STR, "gelf_timestamp_key", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, gelf_fields.timestamp_key),
"Specify the key to use for 'timestamp' in gelf format"
},
{
FLB_CONFIG_MAP_STR, "gelf_host_key", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, gelf_fields.host_key),
"Specify the key to use for the 'host' in gelf format"
},
{
FLB_CONFIG_MAP_STR, "gelf_short_message_key", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, gelf_fields.short_message_key),
"Specify the key to use as the 'short' message in gelf format"
},
{
FLB_CONFIG_MAP_STR, "gelf_full_message_key", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, gelf_fields.full_message_key),
"Specify the key to use for the 'full' message in gelf format"
},
{
FLB_CONFIG_MAP_STR, "gelf_level_key", NULL,
0, FLB_TRUE, offsetof(struct flb_out_http, gelf_fields.level_key),
"Specify the key to use for the 'level' in gelf format"
},
/* EOF */
{0}
};
/* Plugin reference */
struct flb_output_plugin out_http_plugin = {
.name = "http",
.description = "HTTP Output",
.cb_init = cb_http_init,
.cb_pre_run = NULL,
.cb_flush = cb_http_flush,
.cb_exit = cb_http_exit,
.config_map = config_map,
.flags = FLB_OUTPUT_NET | FLB_IO_OPT_TLS,
};
| 1 | 13,035 | since this debug message is inside a plugin code, it should use flb_plg_debug(ctx->ins, "..."), on this case don't need the component prefix since the API will put it there automatically | fluent-fluent-bit | c |
@@ -25,10 +25,10 @@ import com.yahoo.athenz.common.server.util.ResourceUtils;
import com.yahoo.athenz.zts.ZTSConsts;
import com.yahoo.athenz.zts.cert.InstanceCertManager;
import com.yahoo.athenz.zts.store.DataStore;
+import com.yahoo.rdl.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors; | 1 | /*
* Copyright 2020 Verizon Media
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.zts.notification;
import com.yahoo.athenz.auth.util.AthenzUtils;
import com.yahoo.athenz.auth.util.GlobStringsMatcher;
import com.yahoo.athenz.common.server.cert.X509CertRecord;
import com.yahoo.athenz.common.server.dns.HostnameResolver;
import com.yahoo.athenz.common.server.notification.*;
import com.yahoo.athenz.common.server.util.ResourceUtils;
import com.yahoo.athenz.zts.ZTSConsts;
import com.yahoo.athenz.zts.cert.InstanceCertManager;
import com.yahoo.athenz.zts.store.DataStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
import static com.yahoo.athenz.common.ServerCommonConsts.ADMIN_ROLE_NAME;
import static com.yahoo.athenz.common.ServerCommonConsts.USER_DOMAIN_PREFIX;
import static com.yahoo.athenz.common.server.notification.NotificationServiceConstants.*;
public class CertFailedRefreshNotificationTask implements NotificationTask {
private final String serverName;
private final List<String> providers;
private final InstanceCertManager instanceCertManager;
private final NotificationCommon notificationCommon;
private static final Logger LOGGER = LoggerFactory.getLogger(CertFailedRefreshNotificationTask.class);
private final static String DESCRIPTION = "certificate failed refresh notification";
private final static String NOTIFICATION_TYPE = "cert_fail_refresh";
private final HostnameResolver hostnameResolver;
private final CertFailedRefreshNotificationToEmailConverter certFailedRefreshNotificationToEmailConverter;
private final GlobStringsMatcher globStringsMatcher;
public CertFailedRefreshNotificationTask(InstanceCertManager instanceCertManager,
DataStore dataStore,
HostnameResolver hostnameResolver,
String userDomainPrefix,
String serverName,
int httpsPort) {
this.serverName = serverName;
this.providers = getProvidersList();
this.instanceCertManager = instanceCertManager;
DomainRoleMembersFetcher domainRoleMembersFetcher = new DomainRoleMembersFetcher(dataStore, USER_DOMAIN_PREFIX);
this.notificationCommon = new NotificationCommon(domainRoleMembersFetcher, userDomainPrefix);
this.hostnameResolver = hostnameResolver;
final String apiHostName = System.getProperty(ZTSConsts.ZTS_PROP_NOTIFICATION_API_HOSTNAME, serverName);
this.certFailedRefreshNotificationToEmailConverter = new CertFailedRefreshNotificationToEmailConverter(apiHostName, httpsPort);
globStringsMatcher = new GlobStringsMatcher(ZTSConsts.ZTS_PROP_NOTIFICATION_CERT_FAIL_IGNORED_SERVICES_LIST);
}
private List<String> getProvidersList() {
return AthenzUtils.splitCommaSeperatedSystemProperty(ZTSConsts.ZTS_PROP_NOTIFICATION_CERT_FAIL_PROVIDER_LIST);
}
@Override
public List<Notification> getNotifications() {
if (providers == null || providers.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No configured providers");
}
return new ArrayList<>();
}
List<X509CertRecord> unrefreshedCerts = new ArrayList<>();
for (String provider : providers) {
unrefreshedCerts.addAll(instanceCertManager.getUnrefreshedCertsNotifications(serverName, provider));
}
if (unrefreshedCerts.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No unrefreshed certificates available to send notifications");
}
return new ArrayList<>();
}
List<X509CertRecord> unrefreshedCertsValidServices = getRecordsWithValidServices(unrefreshedCerts);
if (unrefreshedCertsValidServices.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No unrefreshed certificates with configured services available to send notifications");
}
return new ArrayList<>();
}
List<X509CertRecord> unrefreshedCertsValidHosts = getRecordsWithValidHosts(unrefreshedCertsValidServices);
if (unrefreshedCertsValidHosts.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No unrefreshed certificates with valid hosts available to send notifications");
}
return new ArrayList<>();
}
Map<String, List<X509CertRecord>> domainToCertRecordsMap = getDomainToCertRecordsMap(unrefreshedCertsValidHosts);
return generateNotificationsForAdmins(domainToCertRecordsMap);
}
private List<X509CertRecord> getRecordsWithValidServices(List<X509CertRecord> unrefreshedCerts) {
return unrefreshedCerts.stream()
.filter(record -> !globStringsMatcher.isMatch(record.getService()))
.collect(Collectors.toList());
}
private List<Notification> generateNotificationsForAdmins(Map<String, List<X509CertRecord>> domainToCertRecordsMap) {
List<Notification> notificationList = new ArrayList<>();
domainToCertRecordsMap.forEach((domain, records) -> {
Map<String, String> details = getNotificationDetails(domain, records);
Notification notification = notificationCommon.createNotification(
ResourceUtils.roleResourceName(domain, ADMIN_ROLE_NAME),
details,
certFailedRefreshNotificationToEmailConverter,
NOTIFICATION_TYPE);
if (notification != null) {
notificationList.add(notification);
}
});
return notificationList;
}
private List<X509CertRecord> getRecordsWithValidHosts(List<X509CertRecord> unrefreshedCerts) {
return unrefreshedCerts.stream()
.filter(record -> hostnameResolver == null || hostnameResolver.isValidHostname(record.getHostName()))
.collect(Collectors.toList());
}
private Map<String, String> getNotificationDetails(String domainName, List<X509CertRecord> certRecords) {
Map<String, String> details = new HashMap<>();
// each domain can have multiple certificates that failed to refresh.
// we're going to collect them into one
// string and separate with | between those. The format will be:
// certificateRecords := <certificate-entry>[|<certificate-entry]*
// certificate-entry := <Service Name>;<Provider>;<InstanceID>;<Last refresh time>;<Expiration time>;<Hostname>;
StringBuilder certDetails = new StringBuilder(256);
for (X509CertRecord certRecord : certRecords) {
if (certDetails.length() != 0) {
certDetails.append('|');
}
String expiryTime = getTimestampAsString(certRecord.getExpiryTime());
String hostName = (certRecord.getHostName() != null) ? certRecord.getHostName() : "";
certDetails.append(AthenzUtils.extractPrincipalServiceName(certRecord.getService())).append(';')
.append(certRecord.getProvider()).append(';')
.append(certRecord.getInstanceId()).append(';')
.append(getTimestampAsString(certRecord.getCurrentTime())).append(';')
.append(expiryTime).append(';')
.append(hostName);
}
details.put(NOTIFICATION_DETAILS_UNREFRESHED_CERTS, certDetails.toString());
details.put(NOTIFICATION_DETAILS_DOMAIN, domainName);
return details;
}
private Map<String, List<X509CertRecord>> getDomainToCertRecordsMap(List<X509CertRecord> unrefreshedRecords) {
Map<String, List<X509CertRecord>> domainToCertRecords = new HashMap<>();
for (X509CertRecord x509CertRecord: unrefreshedRecords) {
String domainName = AthenzUtils.extractPrincipalDomainName(x509CertRecord.getService());
LOGGER.info("processing domain={}, hostName={}", domainName, x509CertRecord.getHostName());
domainToCertRecords.putIfAbsent(domainName, new ArrayList<>());
domainToCertRecords.get(domainName).add(x509CertRecord);
}
return domainToCertRecords;
}
private String getTimestampAsString(Date date) {
return (date != null) ? new Timestamp(date.getTime()).toString() : "";
}
@Override
public String getDescription() {
return DESCRIPTION;
}
public static class CertFailedRefreshNotificationToEmailConverter implements NotificationToEmailConverter {
private static final String EMAIL_TEMPLATE_UNREFRESHED_CERTS = "messages/unrefreshed-certs.html";
private static final String UNREFRESHED_CERTS_SUBJECT = "athenz.notification.email.unrefreshed.certs.subject";
private final NotificationToEmailConverterCommon notificationToEmailConverterCommon;
private String emailUnrefreshedCertsBody;
private final String serverName;
private final int httpsPort;
public CertFailedRefreshNotificationToEmailConverter(final String serverName, int httpsPort) {
notificationToEmailConverterCommon = new NotificationToEmailConverterCommon();
emailUnrefreshedCertsBody = notificationToEmailConverterCommon.readContentFromFile(getClass().getClassLoader(), EMAIL_TEMPLATE_UNREFRESHED_CERTS);
this.serverName = serverName;
this.httpsPort = httpsPort;
}
private String getUnrefreshedCertsBody(Map<String, String> metaDetails) {
if (metaDetails == null) {
return null;
}
String bodyWithDeleteEndpoint = addInstanceDeleteEndpointDetails(metaDetails, emailUnrefreshedCertsBody);
return notificationToEmailConverterCommon.generateBodyFromTemplate(
metaDetails,
bodyWithDeleteEndpoint,
NOTIFICATION_DETAILS_DOMAIN,
NOTIFICATION_DETAILS_UNREFRESHED_CERTS,
6);
}
private String addInstanceDeleteEndpointDetails(Map<String, String> metaDetails, String messageWithoutZtsDeleteEndpoint) {
String ztsApiAddress = serverName + ":" + httpsPort;
String domainPlaceHolder = metaDetails.get(NOTIFICATION_DETAILS_DOMAIN);
String providerPlaceHolder = "<PROVIDER>";
String servicePlaceHolder = "<SERVICE>";
String instanceIdHolder = "<INSTANCE-ID>";
long numberOfRecords = metaDetails.get(NOTIFICATION_DETAILS_UNREFRESHED_CERTS)
.chars()
.filter(ch -> ch == '|')
.count() + 1;
// If there is only one record, fill the real values to make it easier for him
if (numberOfRecords == 1) {
String[] recordDetails = metaDetails.get(NOTIFICATION_DETAILS_UNREFRESHED_CERTS).split(";");
servicePlaceHolder = recordDetails[0];
providerPlaceHolder = recordDetails[1];
instanceIdHolder = recordDetails[2];
}
return MessageFormat.format(messageWithoutZtsDeleteEndpoint,
"{0}", "{1}", "{2}", "{3}", // Skip template arguments that will be filled later
ztsApiAddress,
providerPlaceHolder,
domainPlaceHolder,
servicePlaceHolder,
instanceIdHolder);
}
@Override
public NotificationEmail getNotificationAsEmail(Notification notification) {
String subject = notificationToEmailConverterCommon.getSubject(UNREFRESHED_CERTS_SUBJECT);
String body = getUnrefreshedCertsBody(notification.getDetails());
Set<String> fullyQualifiedEmailAddresses = notificationToEmailConverterCommon.getFullyQualifiedEmailAddresses(notification.getRecipients());
return new NotificationEmail(subject, body, fullyQualifiedEmailAddresses);
}
}
}
| 1 | 5,431 | I also took advantage of the changes to change the Timestamps used in this notification from "java.sql.Timestamp" to "com.yahoo.rdl.Timestamp". | AthenZ-athenz | java |
@@ -23,6 +23,6 @@ import "time"
const (
BrokerPort = 4222
BrokerMaxReconnect = -1
- BrokerReconnectWait = 4 * time.Second
+ BrokerReconnectWait = 1 * time.Second
BrokerTimeout = 5 * time.Second
) | 1 | /*
* Copyright (C) 2017 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package discovery
import "time"
// Broker Constants
const (
BrokerPort = 4222
BrokerMaxReconnect = -1
BrokerReconnectWait = 4 * time.Second
BrokerTimeout = 5 * time.Second
)
| 1 | 13,919 | It would be nice all these tweaks to be configurable from cmd line, with sensible defaults | mysteriumnetwork-node | go |
@@ -147,9 +147,10 @@ class SQLServer(object):
if make_url(connection_string).drivername == 'sqlite+pysqlite':
# FIXME: workaround for locking errors
- return sqlalchemy.create_engine(connection_string,
- encoding='utf8',
- connect_args={'timeout': 600})
+ return sqlalchemy.create_engine(
+ connection_string,
+ encoding='utf8',
+ connect_args={'timeout': 600})
else:
return sqlalchemy.create_engine(connection_string,
encoding='utf8') | 1 | # -------------------------------------------------------------------------
# The CodeChecker Infrastructure
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
# -------------------------------------------------------------------------
"""
Database server handling.
"""
from abc import ABCMeta, abstractmethod
import atexit
import os
import subprocess
import sys
import time
from alembic import command, config
from alembic.util import CommandError
import sqlalchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.engine.url import URL, make_url
from sqlalchemy.sql.elements import quoted_name
from libcodechecker import host_check
from libcodechecker import logger
from libcodechecker import pgpass
from libcodechecker import util
from libcodechecker.logger import LoggerFactory
from libcodechecker.orm_model import CC_META
from libcodechecker.orm_model import CreateSession
from libcodechecker.orm_model import DBVersion
LOG = LoggerFactory.get_new_logger('DB_HANDLER')
class SQLServer(object):
"""
Abstract base class for database server handling. An SQLServer instance is
responsible for the initialization, starting, and stopping the database
server, and also for connection string management.
SQLServer implementations are created via SQLServer.from_cmdline_args().
How to add a new database server implementation:
1, Derive from SQLServer and implement the abstract methods
2, Add/modify some command line options in CodeChecker.py
3, Modify SQLServer.from_cmdline_args() in order to create an
instance of the new server type if needed
"""
__metaclass__ = ABCMeta
def __init__(self, migration_root):
"""
Sets self.migration_root. migration_root should be the path to the
alembic migration scripts.
"""
self.migration_root = migration_root
def _create_or_update_schema(self, use_migration=True):
"""
Creates or updates the database schema. The database server should be
started before this method is called.
If use_migration is True, this method runs an alembic upgrade to HEAD.
In the False case, there is no migration support and only SQLAlchemy
meta data is used for schema creation.
On error sys.exit(1) is called.
"""
try:
db_uri = self.get_connection_string()
engine = SQLServer.create_engine(db_uri)
LOG.debug('Update/create database schema')
if use_migration:
LOG.debug('Creating new database session')
session = CreateSession(engine)
connection = session.connection()
cfg = config.Config()
cfg.set_main_option("script_location", self.migration_root)
cfg.attributes["connection"] = connection
command.upgrade(cfg, "head")
session.commit()
else:
CC_META.create_all(engine)
engine.dispose()
LOG.debug('Update/create database schema done')
return True
except sqlalchemy.exc.SQLAlchemyError as alch_err:
LOG.error(str(alch_err))
sys.exit(1)
except CommandError as cerr:
LOG.error("Database schema and CodeChecker is incompatible."
"Please update CodeChecker.")
LOG.debug(str(cerr))
sys.exit(1)
@abstractmethod
def start(self, db_version_info, wait_for_start=True, init=False):
"""
Starts the database server and initializes the database server.
On wait_for_start == True, this method returns when the server is up
and ready for connections. Otherwise it only starts the server and
returns immediately.
On init == True, this it also initializes the database data and schema
if needed.
On error sys.exit(1) should be called.
"""
pass
@abstractmethod
def stop(self):
"""
Terminates the database server.
On error sys.exit(1) should be called.
"""
pass
@abstractmethod
def get_connection_string(self):
"""
Returns the connection string for SQLAlchemy.
DO NOT LOG THE CONNECTION STRING BECAUSE IT MAY CONTAIN THE PASSWORD
FOR THE DATABASE!
"""
pass
@staticmethod
def create_engine(connection_string):
"""
Creates a new SQLAlchemy engine.
"""
if make_url(connection_string).drivername == 'sqlite+pysqlite':
# FIXME: workaround for locking errors
return sqlalchemy.create_engine(connection_string,
encoding='utf8',
connect_args={'timeout': 600})
else:
return sqlalchemy.create_engine(connection_string,
encoding='utf8')
@staticmethod
def from_cmdline_args(args, migration_root, env=None):
"""
Normally only this method is called form outside of this module in
order to instance the proper server implementation.
Parameters:
args: the command line arguments from CodeChecker.py
migration_root: path to the database migration scripts
env: a run environment dictionary.
"""
if not host_check.check_sql_driver(args.postgresql):
LOG.error("The selected SQL driver is not available.")
sys.exit(1)
if args.postgresql:
LOG.debug("Using PostgreSQLServer")
if 'workspace' in args:
data_url = os.path.join(args.workspace, 'pgsql_data')
else:
# TODO: This will be refactored eventually so that
# CodeChecker is no longer bringing up a postgres database...
# It is an external dependency, it is an external
# responbitility. Until then, use the default folder now
# for the new commands who no longer define workspace.
if 'dbdatadir' in args:
workspace = args.dbdatadir
else:
workspace = util.get_default_workspace()
data_url = os.path.join(workspace, 'pgsql_data')
return PostgreSQLServer(data_url,
migration_root,
args.dbaddress,
args.dbport,
args.dbusername,
args.dbname,
run_env=env)
else:
LOG.debug("Using SQLiteDatabase")
if 'workspace' in args:
data_file = os.path.join(args.workspace, 'codechecker.sqlite')
else:
data_file = args.sqlite
data_file = os.path.abspath(data_file)
return SQLiteDatabase(data_file, migration_root, run_env=env)
def check_db_version(self, db_version_info, session=None):
"""
Checks the database version and prints an error message on database
version mismatch.
- On mismatching or on missing version a sys.exit(1) is called.
- On missing DBVersion table, it returns False
- On compatible DB version, it returns True
Parameters:
db_version_info (db_version.DBVersionInfo): required database
version.
session: an open database session or None. If session is None, a
new session is created.
"""
try:
dispose_engine = False
if session is None:
engine = SQLServer.create_engine(self.get_connection_string())
dispose_engine = True
session = CreateSession(engine)
else:
engine = session.get_bind()
if not engine.has_table(quoted_name(DBVersion.__tablename__,
True)):
LOG.debug("Missing DBVersion table!")
return False
version = session.query(DBVersion).first()
if version is None:
# Version is not populated yet
LOG.error('No version information found in the database.')
sys.exit(1)
elif not db_version_info.is_compatible(version.major,
version.minor):
LOG.error('Version mismatch. Expected database version: ' +
str(db_version_info))
version_from_db = 'v' + str(version.major) + '.' + str(
version.minor)
LOG.error('Version from the database is: ' + version_from_db)
LOG.error('Please update your database.')
sys.exit(1)
LOG.debug("Database version is compatible.")
return True
finally:
session.commit()
if dispose_engine:
engine.dispose()
def _add_version(self, db_version_info, session=None):
"""
Fills the DBVersion table.
"""
engine = None
if session is None:
engine = SQLServer.create_engine(self.get_connection_string())
session = CreateSession(engine)
expected = db_version_info.get_expected_version()
LOG.debug('Adding DB version: ' + str(expected))
session.add(DBVersion(expected[0], expected[1]))
session.commit()
if engine:
engine.dispose()
LOG.debug('Adding DB version done!')
class PostgreSQLServer(SQLServer):
"""
Handler for PostgreSQL.
"""
def __init__(self, data_url, migration_root, host, port, user, database,
password=None, run_env=None):
super(PostgreSQLServer, self).__init__(migration_root)
self.path = data_url
self.host = host
self.port = port
self.user = user
self.database = database
self.password = password
self.run_env = run_env
self.workspace = os.path.abspath(os.path.join(data_url, ".."))
self.proc = None
def _is_database_data_exist(self):
"""Check the PostgreSQL instance existence in a given path."""
LOG.debug('Checking for database at ' + self.path)
return os.path.exists(self.path) and \
os.path.exists(os.path.join(self.path, 'PG_VERSION')) and \
os.path.exists(os.path.join(self.path, 'base'))
def _initialize_database_data(self):
"""Initialize a PostgreSQL instance with initdb. """
LOG.debug('Initializing database at ' + self.path)
init_db = ['initdb', '-U', self.user, '-D', self.path, '-E SQL_ASCII']
err, code = util.call_command(init_db, self.run_env)
# logger -> print error
return code == 0
def _get_connection_string(self, database):
"""
Helper method for getting the connection string for the given database.
database -- The user can force the database name in the returning
connection string. However the password, if any, provided e.g. in a
.pgpass file will be queried based on the database name which is given
as a command line argument, even if it has a default value. The reason
is that sometimes a connection with a common database name is needed,
(e.g. 'postgres'), which requires less user permission.
"""
port = str(self.port)
driver = host_check.get_postgresql_driver_name()
password = self.password
if driver == 'pg8000' and not password:
pfilepath = os.environ.get('PGPASSFILE')
if pfilepath:
password = pgpass.get_password_from_file(pfilepath,
self.host,
port,
self.database,
self.user)
extra_args = {'client_encoding': 'utf8'}
return str(URL('postgresql+' + driver,
username=self.user,
password=password,
host=self.host,
port=port,
database=database,
query=extra_args))
def _wait_or_die(self):
"""
Wait for database if the database process was stared
with a different client. No polling is possible.
"""
LOG.debug('Waiting for PostgreSQL')
tries_count = 0
max_try = 20
timeout = 5
while not self._is_running() and tries_count < max_try:
tries_count += 1
time.sleep(timeout)
if tries_count >= max_try:
LOG.error('Failed to start database.')
sys.exit(1)
def _create_database(self):
try:
LOG.debug('Creating new database if not exists.')
db_uri = self._get_connection_string('postgres')
engine = SQLServer.create_engine(db_uri)
text = \
"SELECT 1 FROM pg_database WHERE datname='%s'" % self.database
if not bool(engine.execute(text).scalar()):
conn = engine.connect()
# From sqlalchemy documentation:
# The psycopg2 and pg8000 dialects also offer the special level
# AUTOCOMMIT.
conn = conn.execution_options(isolation_level="AUTOCOMMIT")
conn.execute('CREATE DATABASE "%s"' % self.database)
conn.close()
LOG.debug('Database created: ' + self.database)
LOG.debug('Database already exists: ' + self.database)
except sqlalchemy.exc.SQLAlchemyError as alch_err:
LOG.error('Failed to create database!')
LOG.error(str(alch_err))
sys.exit(1)
def _is_running(self):
"""Is there PostgreSQL instance running on a given host and port."""
LOG.debug('Checking if database is running at ' +
self.host + ':' + str(self.port))
check_db = ['psql', '-U', self.user, '-c', 'SELECT version();',
'-p', str(self.port), '-h', self.host, '-d', 'postgres']
err, code = util.call_command(check_db, self.run_env)
return code == 0
def start(self, db_version_info, wait_for_start=True, init=False):
"""
Start a PostgreSQL instance with given path, host and port.
Return with process instance.
"""
LOG.debug('Starting/connecting to database.')
if not self._is_running():
if not util.is_localhost(self.host):
LOG.info('Database is not running yet.')
sys.exit(1)
if not self._is_database_data_exist():
if not init:
# The database does not exists.
LOG.error('Database data is missing!')
LOG.error('Please check your configuration!')
sys.exit(1)
elif not self._initialize_database_data():
# The database does not exist and cannot create.
LOG.error('Database data is missing and '
'the initialization of a new failed!')
LOG.error('Please check your configuration!')
sys.exit(1)
LOG.info('Starting database')
LOG.debug('Starting database at ' + self.host + ':' + str(
self.port) + ' ' + self.path)
db_logfile = os.path.join(self.workspace, 'postgresql.log') \
if LoggerFactory.get_log_level() == logger.DEBUG \
else os.devnull
self._db_log = open(db_logfile, 'wb')
start_db = ['postgres', '-i',
'-D', self.path,
'-p', str(self.port),
'-h', self.host]
self.proc = subprocess.Popen(start_db,
bufsize=-1,
env=self.run_env,
stdout=self._db_log,
stderr=subprocess.STDOUT)
add_version = False
if init:
self._wait_or_die()
self._create_database()
add_version = not self.check_db_version(db_version_info)
self._create_or_update_schema(use_migration=False)
elif wait_for_start:
self._wait_or_die()
add_version = not self.check_db_version(db_version_info)
if add_version:
self._add_version(db_version_info)
atexit.register(self.stop)
LOG.debug('Done')
def stop(self):
if self.proc:
LOG.debug('Terminating database')
self.proc.terminate()
self._db_log.close()
def get_connection_string(self):
return self._get_connection_string(self.database)
class SQLiteDatabase(SQLServer):
"""
Handler for SQLite.
"""
def __init__(self, data_file, migration_root, run_env=None):
super(SQLiteDatabase, self).__init__(migration_root)
self.dbpath = data_file
self.run_env = run_env
def _set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
event.listen(Engine, 'connect', _set_sqlite_pragma)
def start(self, db_version_info, wait_for_start=True, init=False):
if init:
add_version = not self.check_db_version(db_version_info)
self._create_or_update_schema(use_migration=False)
if add_version:
self._add_version(db_version_info)
if not os.path.exists(self.dbpath):
# The database does not exists
LOG.error('Database (%s) is missing!' % self.dbpath)
sys.exit(1)
def stop(self):
pass
def get_connection_string(self):
return str(URL('sqlite+pysqlite', None, None, None, None, self.dbpath))
| 1 | 6,923 | Why do we need this `check_same_thead` to be false? I feel a bit uncomfortable about this. | Ericsson-codechecker | c |
@@ -318,6 +318,13 @@ module.exports = BaseTest.extend({
// Should have been multiplied by 100 in the constructor.
TestCase.assertEqual(object.intCol, 100);
+
+ // Should be able to create object by passing in constructor.
+ object = realm.create(CustomObject, {intCol: 2});
+ TestCase.assertTrue(object instanceof CustomObject);
+ TestCase.assertTrue(Object.getPrototypeOf(object) == CustomObject.prototype);
+ TestCase.assertEqual(customCreated, 2);
+ TestCase.assertEqual(object.intCol, 200);
});
TestCase.assertThrows(function() { | 1 | ////////////////////////////////////////////////////////////////////////////
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
'use strict';
var Realm = require('realm');
var BaseTest = require('./base-test');
var TestCase = require('./asserts');
var schemas = require('./schemas');
var util = require('./util');
module.exports = BaseTest.extend({
testRealmConstructor: function() {
var realm = new Realm({schema: []});
TestCase.assertTrue(realm instanceof Realm);
},
testRealmConstructorPath: function() {
TestCase.assertThrows(function() {
new Realm('/invalidpath');
}, 'Realm cannot be created with an invalid path');
TestCase.assertThrows(function() {
new Realm(util.realmPathForFile('test1.realm'), 'invalidArgument');
}, 'Realm constructor can only have 0 or 1 argument(s)');
var defaultRealm = new Realm({schema: []});
TestCase.assertEqual(defaultRealm.path, Realm.defaultPath);
var defaultRealm2 = new Realm();
TestCase.assertEqual(defaultRealm2.path, Realm.defaultPath);
var testPath = util.realmPathForFile('test1.realm');
var realm = new Realm({schema: [], path: testPath});
//TestCase.assertTrue(realm instanceof Realm);
TestCase.assertEqual(realm.path, testPath);
var testPath2 = util.realmPathForFile('test2.realm');
var realm2 = new Realm({schema: [], path: testPath2});
//TestCase.assertTrue(realm2 instanceof Realm);
TestCase.assertEqual(realm2.path, testPath2);
},
testRealmConstructorSchemaVersion: function() {
var defaultRealm = new Realm({schema: []});
TestCase.assertEqual(defaultRealm.schemaVersion, 0);
TestCase.assertThrows(function() {
new Realm({schemaVersion: 1});
}, "Realm already opened at a different schema version");
TestCase.assertEqual(new Realm().schemaVersion, 0);
TestCase.assertEqual(new Realm({schemaVersion: 0}).schemaVersion, 0);
var testPath = util.realmPathForFile('test1.realm');
var realm = new Realm({path: testPath, schema: [], schemaVersion: 1});
TestCase.assertEqual(realm.schemaVersion, 1);
// FIXME - enable once Realm exposes a schema object
//TestCase.assertEqual(realm.schema.length, 0);
realm.close();
// FIXME - enable once realm initialization supports schema comparison
// TestCase.assertThrows(function() {
// realm = new Realm({path: testPath, schema: [schemas.TestObject], schemaVersion: 1});
// }, "schema changes require updating the schema version");
realm = new Realm({path: testPath, schema: [schemas.TestObject], schemaVersion: 2});
realm.write(function() {
realm.create('TestObject', {doubleCol: 1});
});
TestCase.assertEqual(realm.objects('TestObject')[0].doubleCol, 1)
},
testRealmConstructorSchemaValidation: function() {
TestCase.assertThrows(function() {
new Realm({schema: schemas.AllTypes});
}, 'The schema should be an array');
TestCase.assertThrows(function() {
new Realm({schema: ['SomeType']});
}, 'The schema should be an array of objects');
TestCase.assertThrows(function() {
new Realm({schema: [{}]});
}, 'The schema should be an array of ObjectSchema objects');
TestCase.assertThrows(function() {
new Realm({schema: [{name: 'SomeObject'}]});
}, 'The schema should be an array of ObjectSchema objects');
TestCase.assertThrows(function() {
new Realm({schema: [{properties: {intCol: Realm.Types.INT}}]});
}, 'The schema should be an array of ObjectSchema objects');
},
testDefaultPath: function() {
var defaultRealm = new Realm({schema: []});
TestCase.assertEqual(defaultRealm.path, Realm.defaultPath);
var newPath = util.realmPathForFile('default2.realm');
Realm.defaultPath = newPath;
defaultRealm = new Realm({schema: []});
TestCase.assertEqual(defaultRealm.path, newPath, "should use updated default realm path");
TestCase.assertEqual(Realm.defaultPath, newPath, "defaultPath should have been updated");
},
testRealmCreate: function() {
var realm = new Realm({schema: [schemas.IntPrimary, schemas.AllTypes, schemas.TestObject]});
TestCase.assertThrows(function() {
realm.create('TestObject', {doubleCol: 1});
}, 'can only create inside a write transaction');
realm.write(function() {
realm.create('TestObject', {doubleCol: 1});
realm.create('TestObject', {doubleCol: 2});
});
var objects = realm.objects('TestObject');
TestCase.assertEqual(objects.length, 2, 'wrong object count');
TestCase.assertEqual(objects[0].doubleCol, 1, 'wrong object property value');
TestCase.assertEqual(objects[1].doubleCol, 2, 'wrong object property value');
// test int primary object
realm.write(function() {
var obj0 = realm.create('IntPrimaryObject', {
primaryCol: 0,
valueCol: 'val0',
});
TestCase.assertThrows(function() {
realm.create('IntPrimaryObject', {
primaryCol: 0,
valueCol: 'val0',
});
}, 'cannot create object with conflicting primary key');
realm.create('IntPrimaryObject', {
primaryCol: 1,
valueCol: 'val1',
}, true);
var objects = realm.objects('IntPrimaryObject');
TestCase.assertEqual(objects.length, 2);
realm.create('IntPrimaryObject', {
primaryCol: 0,
valueCol: 'newVal0',
}, true);
TestCase.assertEqual(obj0.valueCol, 'newVal0');
TestCase.assertEqual(objects.length, 2);
realm.create('IntPrimaryObject', {primaryCol: 0}, true);
TestCase.assertEqual(obj0.valueCol, 'newVal0');
});
// test upsert with all type and string primary object
realm.write(function() {
var values = {
primaryCol: '0',
boolCol: true,
intCol: 1,
floatCol: 1.1,
doubleCol: 1.11,
stringCol: '1',
dateCol: new Date(1),
dataCol: new ArrayBuffer(1),
objectCol: {doubleCol: 1},
arrayCol: [],
};
var obj0 = realm.create('AllTypesObject', values);
TestCase.assertThrows(function() {
realm.create('AllTypesObject', values);
}, 'cannot create object with conflicting primary key');
var obj1 = realm.create('AllTypesObject', {
primaryCol: '1',
boolCol: false,
intCol: 2,
floatCol: 2.2,
doubleCol: 2.22,
stringCol: '2',
dateCol: new Date(2),
dataCol: new ArrayBuffer(2),
objectCol: {doubleCol: 0},
arrayCol: [{doubleCol: 2}],
}, true);
var objects = realm.objects('AllTypesObject');
TestCase.assertEqual(objects.length, 2);
realm.create('AllTypesObject', {
primaryCol: '0',
boolCol: false,
intCol: 2,
floatCol: 2.2,
doubleCol: 2.22,
stringCol: '2',
dateCol: new Date(2),
dataCol: new ArrayBuffer(2),
objectCol: null,
arrayCol: [{doubleCol: 2}],
}, true);
TestCase.assertEqual(objects.length, 2);
TestCase.assertEqual(obj0.stringCol, '2');
TestCase.assertEqual(obj0.boolCol, false);
TestCase.assertEqual(obj0.intCol, 2);
TestCase.assertEqualWithTolerance(obj0.floatCol, 2.2, 0.000001);
TestCase.assertEqualWithTolerance(obj0.doubleCol, 2.22, 0.000001);
TestCase.assertEqual(obj0.dateCol.getTime(), 2);
TestCase.assertEqual(obj0.dataCol.byteLength, 2);
TestCase.assertEqual(obj0.objectCol, null);
TestCase.assertEqual(obj0.arrayCol.length, 1);
realm.create('AllTypesObject', {primaryCol: '0'}, true);
realm.create('AllTypesObject', {primaryCol: '1'}, true);
TestCase.assertEqual(obj0.stringCol, '2');
TestCase.assertEqual(obj0.objectCol, null);
TestCase.assertEqual(obj1.objectCol.doubleCol, 0);
realm.create('AllTypesObject', {
primaryCol: '0',
stringCol: '3',
objectCol: {doubleCol: 0},
}, true);
TestCase.assertEqual(obj0.stringCol, '3');
TestCase.assertEqual(obj0.boolCol, false);
TestCase.assertEqual(obj0.intCol, 2);
TestCase.assertEqualWithTolerance(obj0.floatCol, 2.2, 0.000001);
TestCase.assertEqualWithTolerance(obj0.doubleCol, 2.22, 0.000001);
TestCase.assertEqual(obj0.dateCol.getTime(), 2);
TestCase.assertEqual(obj0.dataCol.byteLength, 2);
TestCase.assertEqual(obj0.objectCol.doubleCol, 0);
TestCase.assertEqual(obj0.arrayCol.length, 1);
realm.create('AllTypesObject', {primaryCol: '0', objectCol: undefined}, true);
realm.create('AllTypesObject', {primaryCol: '1', objectCol: null}, true);
TestCase.assertEqual(obj0.objectCol, null);
TestCase.assertEqual(obj1.objectCol, null);
});
},
testRealmCreateWithDefaults: function() {
var realm = new Realm({schema: [schemas.DefaultValues, schemas.TestObject]});
realm.write(function() {
var obj = realm.create('DefaultValuesObject', {});
var properties = schemas.DefaultValues.properties;
TestCase.assertEqual(obj.boolCol, properties.boolCol.default);
TestCase.assertEqual(obj.intCol, properties.intCol.default);
TestCase.assertEqualWithTolerance(obj.floatCol, properties.floatCol.default, 0.000001);
TestCase.assertEqualWithTolerance(obj.doubleCol, properties.doubleCol.default, 0.000001);
TestCase.assertEqual(obj.stringCol, properties.stringCol.default);
TestCase.assertEqual(obj.dateCol.getTime(), properties.dateCol.default.getTime());
TestCase.assertEqual(obj.dataCol.byteLength, properties.dataCol.default.byteLength);
TestCase.assertEqual(obj.objectCol.doubleCol, properties.objectCol.default.doubleCol);
TestCase.assertEqual(obj.nullObjectCol, null);
TestCase.assertEqual(obj.arrayCol.length, properties.arrayCol.default.length);
TestCase.assertEqual(obj.arrayCol[0].doubleCol, properties.arrayCol.default[0].doubleCol);
});
},
testRealmCreateWithConstructor: function() {
var customCreated = 0;
function CustomObject() {
customCreated++;
this.intCol *= 100;
}
CustomObject.schema = {
name: 'CustomObject',
properties: {
intCol: 'int'
}
}
function InvalidObject() {
return {};
}
TestCase.assertThrows(function() {
new Realm({schema: [InvalidObject]});
});
InvalidObject.schema = {
name: 'InvalidObject',
properties: {
intCol: 'int'
}
}
var realm = new Realm({schema: [CustomObject, InvalidObject]});
realm.write(function() {
var object = realm.create('CustomObject', {intCol: 1});
TestCase.assertTrue(object instanceof CustomObject);
TestCase.assertTrue(Object.getPrototypeOf(object) == CustomObject.prototype);
TestCase.assertEqual(customCreated, 1);
// Should have been multiplied by 100 in the constructor.
TestCase.assertEqual(object.intCol, 100);
});
TestCase.assertThrows(function() {
realm.write(function() {
realm.create('InvalidObject', {intCol: 1});
});
});
},
testRealmDelete: function() {
var realm = new Realm({schema: [schemas.TestObject]});
realm.write(function() {
for (var i = 0; i < 10; i++) {
realm.create('TestObject', {doubleCol: i});
}
});
var objects = realm.objects('TestObject');
TestCase.assertThrows(function() {
realm.delete(objects[0]);
}, 'can only delete in a write transaction');
realm.write(function() {
TestCase.assertThrows(function() {
realm.delete();
});
realm.delete(objects[0]);
TestCase.assertEqual(objects.length, 9, 'wrong object count');
TestCase.assertEqual(objects[0].doubleCol, 9, "wrong property value");
TestCase.assertEqual(objects[1].doubleCol, 1, "wrong property value");
realm.delete([objects[0], objects[1]]);
TestCase.assertEqual(objects.length, 7, 'wrong object count');
TestCase.assertEqual(objects[0].doubleCol, 7, "wrong property value");
TestCase.assertEqual(objects[1].doubleCol, 8, "wrong property value");
var threeObjects = realm.objects('TestObject').filtered("doubleCol < 5");
TestCase.assertEqual(threeObjects.length, 3, "wrong results count");
realm.delete(threeObjects);
TestCase.assertEqual(objects.length, 4, 'wrong object count');
TestCase.assertEqual(threeObjects.length, 0, 'threeObject should have been deleted');
});
},
testDeleteAll: function() {
var realm = new Realm({schema: [schemas.TestObject, schemas.IntPrimary]});
realm.write(function() {
realm.create('TestObject', {doubleCol: 1});
realm.create('TestObject', {doubleCol: 2});
realm.create('IntPrimaryObject', {primaryCol: 2, valueCol: 'value'});
});
TestCase.assertEqual(realm.objects('TestObject').length, 2);
TestCase.assertEqual(realm.objects('IntPrimaryObject').length, 1);
TestCase.assertThrows(function() {
realm.deleteAll();
}, 'can only deleteAll in a write transaction');
realm.write(function() {
realm.deleteAll();
});
TestCase.assertEqual(realm.objects('TestObject').length, 0);
TestCase.assertEqual(realm.objects('IntPrimaryObject').length, 0);
},
testRealmObjects: function() {
var realm = new Realm({schema: [schemas.PersonObject, schemas.DefaultValues, schemas.TestObject]});
realm.write(function() {
realm.create('PersonObject', {name: 'Ari', age: 10});
realm.create('PersonObject', {name: 'Tim', age: 11});
realm.create('PersonObject', {name: 'Bjarne', age: 12});
realm.create('PersonObject', {name: 'Alex', age: 12, married: true});
});
TestCase.assertThrows(function() {
realm.objects();
});
TestCase.assertThrows(function() {
realm.objects([]);
});
TestCase.assertThrows(function() {
realm.objects('InvalidClass');
});
TestCase.assertThrows(function() {
realm.objects('PersonObject', 'truepredicate');
});
},
testNotifications: function() {
var realm = new Realm({schema: []});
var notificationCount = 0;
var notificationName;
realm.addListener('change', function(realm, name) {
notificationCount++;
notificationName = name;
});
TestCase.assertEqual(notificationCount, 0);
realm.write(function() {});
TestCase.assertEqual(notificationCount, 1);
TestCase.assertEqual(notificationName, 'change');
var secondNotificationCount = 0;
function secondNotification(realm, name) {
secondNotificationCount++;
}
// The listener should only be added once.
realm.addListener('change', secondNotification);
realm.addListener('change', secondNotification);
realm.write(function() {});
TestCase.assertEqual(notificationCount, 2);
TestCase.assertEqual(secondNotificationCount, 1);
realm.removeListener('change', secondNotification);
realm.write(function() {});
TestCase.assertEqual(notificationCount, 3);
TestCase.assertEqual(secondNotificationCount, 1);
realm.removeAllListeners();
realm.write(function() {});
TestCase.assertEqual(notificationCount, 3);
TestCase.assertEqual(secondNotificationCount, 1);
TestCase.assertThrows(function() {
realm.addListener('invalid', function() {});
});
realm.addListener('change', function() {
throw new Error('error');
});
TestCase.assertThrows(function() {
realm.write(function() {});
});
},
});
| 1 | 15,094 | We should probably test with constructors which aren't in the schema, and functions which aren't constructors. | realm-realm-js | js |
@@ -201,6 +201,19 @@ CudaHostPinnedSpace::CudaHostPinnedSpace() {}
// <editor-fold desc="allocate()"> {{{1
void *CudaSpace::allocate(const size_t arg_alloc_size) const {
+ return allocate("[unlabeled]", arg_alloc_size);
+}
+void *CudaSpace::allocate(const char *
+#if defined(KOKKOS_ENABLE_PROFILING)
+ arg_label
+#endif
+ ,
+ const size_t arg_alloc_size,
+ const size_t
+#if defined(KOKKOS_ENABLE_PROFILING)
+ arg_logical_size
+#endif
+ ) const {
void *ptr = nullptr;
auto error_code = cudaMalloc(&ptr, arg_alloc_size); | 1 | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// 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. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <Kokkos_Macros.hpp>
#ifdef KOKKOS_ENABLE_CUDA
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <algorithm>
#include <atomic>
#include <Kokkos_Core.hpp>
#include <Kokkos_Cuda.hpp>
#include <Kokkos_CudaSpace.hpp>
//#include <Cuda/Kokkos_Cuda_BlockSize_Deduction.hpp>
#include <impl/Kokkos_Error.hpp>
#include <impl/Kokkos_MemorySpace.hpp>
#if defined(KOKKOS_ENABLE_PROFILING)
#include <impl/Kokkos_Tools.hpp>
#endif
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
namespace Kokkos {
namespace Impl {
namespace {
static std::atomic<int> num_uvm_allocations(0);
cudaStream_t get_deep_copy_stream() {
static cudaStream_t s = 0;
if (s == 0) {
cudaStreamCreate(&s);
}
return s;
}
} // namespace
DeepCopy<CudaSpace, CudaSpace, Cuda>::DeepCopy(void *dst, const void *src,
size_t n) {
CUDA_SAFE_CALL(cudaMemcpy(dst, src, n, cudaMemcpyDefault));
}
DeepCopy<HostSpace, CudaSpace, Cuda>::DeepCopy(void *dst, const void *src,
size_t n) {
CUDA_SAFE_CALL(cudaMemcpy(dst, src, n, cudaMemcpyDefault));
}
DeepCopy<CudaSpace, HostSpace, Cuda>::DeepCopy(void *dst, const void *src,
size_t n) {
CUDA_SAFE_CALL(cudaMemcpy(dst, src, n, cudaMemcpyDefault));
}
DeepCopy<CudaSpace, CudaSpace, Cuda>::DeepCopy(const Cuda &instance, void *dst,
const void *src, size_t n) {
CUDA_SAFE_CALL(
cudaMemcpyAsync(dst, src, n, cudaMemcpyDefault, instance.cuda_stream()));
}
DeepCopy<HostSpace, CudaSpace, Cuda>::DeepCopy(const Cuda &instance, void *dst,
const void *src, size_t n) {
CUDA_SAFE_CALL(
cudaMemcpyAsync(dst, src, n, cudaMemcpyDefault, instance.cuda_stream()));
}
DeepCopy<CudaSpace, HostSpace, Cuda>::DeepCopy(const Cuda &instance, void *dst,
const void *src, size_t n) {
CUDA_SAFE_CALL(
cudaMemcpyAsync(dst, src, n, cudaMemcpyDefault, instance.cuda_stream()));
}
void DeepCopyAsyncCuda(void *dst, const void *src, size_t n) {
cudaStream_t s = get_deep_copy_stream();
CUDA_SAFE_CALL(cudaMemcpyAsync(dst, src, n, cudaMemcpyDefault, s));
cudaStreamSynchronize(s);
}
} // namespace Impl
} // namespace Kokkos
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
namespace Kokkos {
void CudaSpace::access_error() {
const std::string msg(
"Kokkos::CudaSpace::access_error attempt to execute Cuda function from "
"non-Cuda space");
Kokkos::Impl::throw_runtime_exception(msg);
}
void CudaSpace::access_error(const void *const) {
const std::string msg(
"Kokkos::CudaSpace::access_error attempt to execute Cuda function from "
"non-Cuda space");
Kokkos::Impl::throw_runtime_exception(msg);
}
/*--------------------------------------------------------------------------*/
bool CudaUVMSpace::available() {
#if defined(CUDA_VERSION) && !defined(__APPLE__)
enum { UVM_available = true };
#else
enum { UVM_available = false };
#endif
return UVM_available;
}
/*--------------------------------------------------------------------------*/
int CudaUVMSpace::number_of_allocations() {
return Kokkos::Impl::num_uvm_allocations.load();
}
#ifdef KOKKOS_IMPL_DEBUG_CUDA_PIN_UVM_TO_HOST
// The purpose of the following variable is to allow a state-based choice
// for pinning UVM allocations to the CPU. For now this is considered
// an experimental debugging capability - with the potential to work around
// some CUDA issues.
bool CudaUVMSpace::kokkos_impl_cuda_pin_uvm_to_host_v = false;
bool CudaUVMSpace::cuda_pin_uvm_to_host() {
return CudaUVMSpace::kokkos_impl_cuda_pin_uvm_to_host_v;
}
void CudaUVMSpace::cuda_set_pin_uvm_to_host(bool val) {
CudaUVMSpace::kokkos_impl_cuda_pin_uvm_to_host_v = val;
}
#endif
} // namespace Kokkos
#ifdef KOKKOS_IMPL_DEBUG_CUDA_PIN_UVM_TO_HOST
bool kokkos_impl_cuda_pin_uvm_to_host() {
return Kokkos::CudaUVMSpace::cuda_pin_uvm_to_host();
}
void kokkos_impl_cuda_set_pin_uvm_to_host(bool val) {
Kokkos::CudaUVMSpace::cuda_set_pin_uvm_to_host(val);
}
#endif
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
namespace Kokkos {
CudaSpace::CudaSpace() : m_device(Kokkos::Cuda().cuda_device()) {}
CudaUVMSpace::CudaUVMSpace() : m_device(Kokkos::Cuda().cuda_device()) {}
CudaHostPinnedSpace::CudaHostPinnedSpace() {}
//==============================================================================
// <editor-fold desc="allocate()"> {{{1
void *CudaSpace::allocate(const size_t arg_alloc_size) const {
void *ptr = nullptr;
auto error_code = cudaMalloc(&ptr, arg_alloc_size);
if (error_code != cudaSuccess) { // TODO tag as unlikely branch
cudaGetLastError(); // This is the only way to clear the last error, which
// we should do here since we're turning it into an
// exception here
throw Experimental::CudaRawMemoryAllocationFailure(
arg_alloc_size, error_code,
Experimental::RawMemoryAllocationFailure::AllocationMechanism::
CudaMalloc);
}
return ptr;
}
void *CudaUVMSpace::allocate(const size_t arg_alloc_size) const {
void *ptr = nullptr;
Cuda::impl_static_fence();
if (arg_alloc_size > 0) {
Kokkos::Impl::num_uvm_allocations++;
auto error_code =
cudaMallocManaged(&ptr, arg_alloc_size, cudaMemAttachGlobal);
#ifdef KOKKOS_IMPL_DEBUG_CUDA_PIN_UVM_TO_HOST
if (Kokkos::CudaUVMSpace::cuda_pin_uvm_to_host())
cudaMemAdvise(ptr, arg_alloc_size, cudaMemAdviseSetPreferredLocation,
cudaCpuDeviceId);
#endif
if (error_code != cudaSuccess) { // TODO tag as unlikely branch
cudaGetLastError(); // This is the only way to clear the last error,
// which we should do here since we're turning it
// into an exception here
throw Experimental::CudaRawMemoryAllocationFailure(
arg_alloc_size, error_code,
Experimental::RawMemoryAllocationFailure::AllocationMechanism::
CudaMallocManaged);
}
}
Cuda::impl_static_fence();
return ptr;
}
void *CudaHostPinnedSpace::allocate(const size_t arg_alloc_size) const {
void *ptr = nullptr;
auto error_code = cudaHostAlloc(&ptr, arg_alloc_size, cudaHostAllocDefault);
if (error_code != cudaSuccess) { // TODO tag as unlikely branch
cudaGetLastError(); // This is the only way to clear the last error, which
// we should do here since we're turning it into an
// exception here
throw Experimental::CudaRawMemoryAllocationFailure(
arg_alloc_size, error_code,
Experimental::RawMemoryAllocationFailure::AllocationMechanism::
CudaHostAlloc);
}
return ptr;
}
// </editor-fold> end allocate() }}}1
//==============================================================================
void CudaSpace::deallocate(void *const arg_alloc_ptr,
const size_t /* arg_alloc_size */) const {
try {
CUDA_SAFE_CALL(cudaFree(arg_alloc_ptr));
} catch (...) {
}
}
void CudaUVMSpace::deallocate(void *const arg_alloc_ptr,
const size_t /* arg_alloc_size */) const {
Cuda::impl_static_fence();
try {
if (arg_alloc_ptr != nullptr) {
Kokkos::Impl::num_uvm_allocations--;
CUDA_SAFE_CALL(cudaFree(arg_alloc_ptr));
}
} catch (...) {
}
Cuda::impl_static_fence();
}
void CudaHostPinnedSpace::deallocate(void *const arg_alloc_ptr,
const size_t /* arg_alloc_size */) const {
try {
CUDA_SAFE_CALL(cudaFreeHost(arg_alloc_ptr));
} catch (...) {
}
}
} // namespace Kokkos
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
#ifdef KOKKOS_DEBUG
SharedAllocationRecord<void, void>
SharedAllocationRecord<Kokkos::CudaSpace, void>::s_root_record;
SharedAllocationRecord<void, void>
SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::s_root_record;
SharedAllocationRecord<void, void>
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::s_root_record;
#endif
::cudaTextureObject_t
SharedAllocationRecord<Kokkos::CudaSpace, void>::attach_texture_object(
const unsigned sizeof_alias, void *const alloc_ptr,
size_t const alloc_size) {
enum { TEXTURE_BOUND_1D = 1u << 27 };
if ((alloc_ptr == 0) || (sizeof_alias * TEXTURE_BOUND_1D <= alloc_size)) {
std::ostringstream msg;
msg << "Kokkos::CudaSpace ERROR: Cannot attach texture object to"
<< " alloc_ptr(" << alloc_ptr << ")"
<< " alloc_size(" << alloc_size << ")"
<< " max_size(" << (sizeof_alias * TEXTURE_BOUND_1D) << ")";
std::cerr << msg.str() << std::endl;
std::cerr.flush();
Kokkos::Impl::throw_runtime_exception(msg.str());
}
::cudaTextureObject_t tex_obj;
struct cudaResourceDesc resDesc;
struct cudaTextureDesc texDesc;
memset(&resDesc, 0, sizeof(resDesc));
memset(&texDesc, 0, sizeof(texDesc));
resDesc.resType = cudaResourceTypeLinear;
resDesc.res.linear.desc =
(sizeof_alias == 4
? cudaCreateChannelDesc<int>()
: (sizeof_alias == 8
? cudaCreateChannelDesc< ::int2>()
:
/* sizeof_alias == 16 */ cudaCreateChannelDesc< ::int4>()));
resDesc.res.linear.sizeInBytes = alloc_size;
resDesc.res.linear.devPtr = alloc_ptr;
CUDA_SAFE_CALL(
cudaCreateTextureObject(&tex_obj, &resDesc, &texDesc, nullptr));
return tex_obj;
}
//==============================================================================
// <editor-fold desc="SharedAllocationRecord::get_label()"> {{{1
std::string SharedAllocationRecord<Kokkos::CudaSpace, void>::get_label() const {
SharedAllocationHeader header;
Kokkos::Impl::DeepCopy<Kokkos::HostSpace, Kokkos::CudaSpace>(
&header, RecordBase::head(), sizeof(SharedAllocationHeader));
return std::string(header.m_label);
}
std::string SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::get_label()
const {
return std::string(RecordBase::head()->m_label);
}
std::string
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::get_label() const {
return std::string(RecordBase::head()->m_label);
}
// </editor-fold> end SharedAllocationRecord::get_label() }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="SharedAllocationRecord allocate()"> {{{1
SharedAllocationRecord<Kokkos::CudaSpace, void>
*SharedAllocationRecord<Kokkos::CudaSpace, void>::allocate(
const Kokkos::CudaSpace &arg_space, const std::string &arg_label,
const size_t arg_alloc_size) {
return new SharedAllocationRecord(arg_space, arg_label, arg_alloc_size);
}
SharedAllocationRecord<Kokkos::CudaUVMSpace, void>
*SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::allocate(
const Kokkos::CudaUVMSpace &arg_space, const std::string &arg_label,
const size_t arg_alloc_size) {
return new SharedAllocationRecord(arg_space, arg_label, arg_alloc_size);
}
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>
*SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::allocate(
const Kokkos::CudaHostPinnedSpace &arg_space,
const std::string &arg_label, const size_t arg_alloc_size) {
return new SharedAllocationRecord(arg_space, arg_label, arg_alloc_size);
}
// </editor-fold> end SharedAllocationRecord allocate() }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="SharedAllocationRecord deallocate"> {{{1
void SharedAllocationRecord<Kokkos::CudaSpace, void>::deallocate(
SharedAllocationRecord<void, void> *arg_rec) {
delete static_cast<SharedAllocationRecord *>(arg_rec);
}
void SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::deallocate(
SharedAllocationRecord<void, void> *arg_rec) {
delete static_cast<SharedAllocationRecord *>(arg_rec);
}
void SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::deallocate(
SharedAllocationRecord<void, void> *arg_rec) {
delete static_cast<SharedAllocationRecord *>(arg_rec);
}
// </editor-fold> end SharedAllocationRecord deallocate }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="SharedAllocationRecord destructors"> {{{1
SharedAllocationRecord<Kokkos::CudaSpace, void>::~SharedAllocationRecord() {
#if defined(KOKKOS_ENABLE_PROFILING)
if (Kokkos::Profiling::profileLibraryLoaded()) {
SharedAllocationHeader header;
Kokkos::Impl::DeepCopy<CudaSpace, HostSpace>(
&header, RecordBase::m_alloc_ptr, sizeof(SharedAllocationHeader));
Kokkos::Profiling::deallocateData(
Kokkos::Profiling::make_space_handle(Kokkos::CudaSpace::name()),
header.m_label, data(), size());
}
#endif
m_space.deallocate(SharedAllocationRecord<void, void>::m_alloc_ptr,
SharedAllocationRecord<void, void>::m_alloc_size);
}
SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::~SharedAllocationRecord() {
#if defined(KOKKOS_ENABLE_PROFILING)
if (Kokkos::Profiling::profileLibraryLoaded()) {
Cuda::impl_static_fence(); // Make sure I can access the label ...
Kokkos::Profiling::deallocateData(
Kokkos::Profiling::make_space_handle(Kokkos::CudaUVMSpace::name()),
RecordBase::m_alloc_ptr->m_label, data(), size());
}
#endif
m_space.deallocate(SharedAllocationRecord<void, void>::m_alloc_ptr,
SharedAllocationRecord<void, void>::m_alloc_size);
}
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace,
void>::~SharedAllocationRecord() {
#if defined(KOKKOS_ENABLE_PROFILING)
if (Kokkos::Profiling::profileLibraryLoaded()) {
Kokkos::Profiling::deallocateData(Kokkos::Profiling::make_space_handle(
Kokkos::CudaHostPinnedSpace::name()),
RecordBase::m_alloc_ptr->m_label, data(),
size());
}
#endif
m_space.deallocate(SharedAllocationRecord<void, void>::m_alloc_ptr,
SharedAllocationRecord<void, void>::m_alloc_size);
}
// </editor-fold> end SharedAllocationRecord destructors }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="SharedAllocationRecord constructors"> {{{1
SharedAllocationRecord<Kokkos::CudaSpace, void>::SharedAllocationRecord(
const Kokkos::CudaSpace &arg_space, const std::string &arg_label,
const size_t arg_alloc_size,
const SharedAllocationRecord<void, void>::function_type arg_dealloc)
// Pass through allocated [ SharedAllocationHeader , user_memory ]
// Pass through deallocation function
: SharedAllocationRecord<void, void>(
#ifdef KOKKOS_DEBUG
&SharedAllocationRecord<Kokkos::CudaSpace, void>::s_root_record,
#endif
Impl::checked_allocation_with_header(arg_space, arg_label,
arg_alloc_size),
sizeof(SharedAllocationHeader) + arg_alloc_size, arg_dealloc),
m_tex_obj(0),
m_space(arg_space) {
#if defined(KOKKOS_ENABLE_PROFILING)
if (Kokkos::Profiling::profileLibraryLoaded()) {
Kokkos::Profiling::allocateData(
Kokkos::Profiling::make_space_handle(arg_space.name()), arg_label,
data(), arg_alloc_size);
}
#endif
SharedAllocationHeader header;
// Fill in the Header information
header.m_record = static_cast<SharedAllocationRecord<void, void> *>(this);
strncpy(header.m_label, arg_label.c_str(),
SharedAllocationHeader::maximum_label_length);
// Set last element zero, in case c_str is too long
header.m_label[SharedAllocationHeader::maximum_label_length - 1] = (char)0;
// Copy to device memory
Kokkos::Impl::DeepCopy<CudaSpace, HostSpace>(RecordBase::m_alloc_ptr, &header,
sizeof(SharedAllocationHeader));
}
SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::SharedAllocationRecord(
const Kokkos::CudaUVMSpace &arg_space, const std::string &arg_label,
const size_t arg_alloc_size,
const SharedAllocationRecord<void, void>::function_type arg_dealloc)
// Pass through allocated [ SharedAllocationHeader , user_memory ]
// Pass through deallocation function
: SharedAllocationRecord<void, void>(
#ifdef KOKKOS_DEBUG
&SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::s_root_record,
#endif
Impl::checked_allocation_with_header(arg_space, arg_label,
arg_alloc_size),
sizeof(SharedAllocationHeader) + arg_alloc_size, arg_dealloc),
m_tex_obj(0),
m_space(arg_space) {
#if defined(KOKKOS_ENABLE_PROFILING)
if (Kokkos::Profiling::profileLibraryLoaded()) {
Kokkos::Profiling::allocateData(
Kokkos::Profiling::make_space_handle(arg_space.name()), arg_label,
data(), arg_alloc_size);
}
#endif
// Fill in the Header information, directly accessible via UVM
RecordBase::m_alloc_ptr->m_record = this;
strncpy(RecordBase::m_alloc_ptr->m_label, arg_label.c_str(),
SharedAllocationHeader::maximum_label_length);
// Set last element zero, in case c_str is too long
RecordBase::m_alloc_ptr
->m_label[SharedAllocationHeader::maximum_label_length - 1] = (char)0;
}
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::
SharedAllocationRecord(
const Kokkos::CudaHostPinnedSpace &arg_space,
const std::string &arg_label, const size_t arg_alloc_size,
const SharedAllocationRecord<void, void>::function_type arg_dealloc)
// Pass through allocated [ SharedAllocationHeader , user_memory ]
// Pass through deallocation function
: SharedAllocationRecord<void, void>(
#ifdef KOKKOS_DEBUG
&SharedAllocationRecord<Kokkos::CudaHostPinnedSpace,
void>::s_root_record,
#endif
Impl::checked_allocation_with_header(arg_space, arg_label,
arg_alloc_size),
sizeof(SharedAllocationHeader) + arg_alloc_size, arg_dealloc),
m_space(arg_space) {
#if defined(KOKKOS_ENABLE_PROFILING)
if (Kokkos::Profiling::profileLibraryLoaded()) {
Kokkos::Profiling::allocateData(
Kokkos::Profiling::make_space_handle(arg_space.name()), arg_label,
data(), arg_alloc_size);
}
#endif
// Fill in the Header information, directly accessible on the host
RecordBase::m_alloc_ptr->m_record = this;
strncpy(RecordBase::m_alloc_ptr->m_label, arg_label.c_str(),
SharedAllocationHeader::maximum_label_length);
// Set last element zero, in case c_str is too long
RecordBase::m_alloc_ptr
->m_label[SharedAllocationHeader::maximum_label_length - 1] = (char)0;
}
// </editor-fold> end SharedAllocationRecord constructors }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="SharedAllocationRecored::(re|de|)allocate_tracked"> {{{1
void *SharedAllocationRecord<Kokkos::CudaSpace, void>::allocate_tracked(
const Kokkos::CudaSpace &arg_space, const std::string &arg_alloc_label,
const size_t arg_alloc_size) {
if (!arg_alloc_size) return (void *)0;
SharedAllocationRecord *const r =
allocate(arg_space, arg_alloc_label, arg_alloc_size);
RecordBase::increment(r);
return r->data();
}
void SharedAllocationRecord<Kokkos::CudaSpace, void>::deallocate_tracked(
void *const arg_alloc_ptr) {
if (arg_alloc_ptr != 0) {
SharedAllocationRecord *const r = get_record(arg_alloc_ptr);
RecordBase::decrement(r);
}
}
void *SharedAllocationRecord<Kokkos::CudaSpace, void>::reallocate_tracked(
void *const arg_alloc_ptr, const size_t arg_alloc_size) {
SharedAllocationRecord *const r_old = get_record(arg_alloc_ptr);
SharedAllocationRecord *const r_new =
allocate(r_old->m_space, r_old->get_label(), arg_alloc_size);
Kokkos::Impl::DeepCopy<CudaSpace, CudaSpace>(
r_new->data(), r_old->data(), std::min(r_old->size(), r_new->size()));
RecordBase::increment(r_new);
RecordBase::decrement(r_old);
return r_new->data();
}
void *SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::allocate_tracked(
const Kokkos::CudaUVMSpace &arg_space, const std::string &arg_alloc_label,
const size_t arg_alloc_size) {
if (!arg_alloc_size) return (void *)0;
SharedAllocationRecord *const r =
allocate(arg_space, arg_alloc_label, arg_alloc_size);
RecordBase::increment(r);
return r->data();
}
void SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::deallocate_tracked(
void *const arg_alloc_ptr) {
if (arg_alloc_ptr != 0) {
SharedAllocationRecord *const r = get_record(arg_alloc_ptr);
RecordBase::decrement(r);
}
}
void *SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::reallocate_tracked(
void *const arg_alloc_ptr, const size_t arg_alloc_size) {
SharedAllocationRecord *const r_old = get_record(arg_alloc_ptr);
SharedAllocationRecord *const r_new =
allocate(r_old->m_space, r_old->get_label(), arg_alloc_size);
Kokkos::Impl::DeepCopy<CudaUVMSpace, CudaUVMSpace>(
r_new->data(), r_old->data(), std::min(r_old->size(), r_new->size()));
RecordBase::increment(r_new);
RecordBase::decrement(r_old);
return r_new->data();
}
void *
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::allocate_tracked(
const Kokkos::CudaHostPinnedSpace &arg_space,
const std::string &arg_alloc_label, const size_t arg_alloc_size) {
if (!arg_alloc_size) return (void *)0;
SharedAllocationRecord *const r =
allocate(arg_space, arg_alloc_label, arg_alloc_size);
RecordBase::increment(r);
return r->data();
}
void SharedAllocationRecord<Kokkos::CudaHostPinnedSpace,
void>::deallocate_tracked(void *const
arg_alloc_ptr) {
if (arg_alloc_ptr != 0) {
SharedAllocationRecord *const r = get_record(arg_alloc_ptr);
RecordBase::decrement(r);
}
}
void *
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::reallocate_tracked(
void *const arg_alloc_ptr, const size_t arg_alloc_size) {
SharedAllocationRecord *const r_old = get_record(arg_alloc_ptr);
SharedAllocationRecord *const r_new =
allocate(r_old->m_space, r_old->get_label(), arg_alloc_size);
Kokkos::Impl::DeepCopy<CudaHostPinnedSpace, CudaHostPinnedSpace>(
r_new->data(), r_old->data(), std::min(r_old->size(), r_new->size()));
RecordBase::increment(r_new);
RecordBase::decrement(r_old);
return r_new->data();
}
// </editor-fold> end SharedAllocationRecored::(re|de|)allocate_tracked }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="SharedAllocationRecord::get_record()"> {{{1
SharedAllocationRecord<Kokkos::CudaSpace, void> *
SharedAllocationRecord<Kokkos::CudaSpace, void>::get_record(void *alloc_ptr) {
using RecordCuda = SharedAllocationRecord<Kokkos::CudaSpace, void>;
using Header = SharedAllocationHeader;
// Copy the header from the allocation
Header head;
Header const *const head_cuda =
alloc_ptr ? Header::get_header(alloc_ptr) : (Header *)0;
if (alloc_ptr) {
Kokkos::Impl::DeepCopy<HostSpace, CudaSpace>(
&head, head_cuda, sizeof(SharedAllocationHeader));
}
RecordCuda *const record =
alloc_ptr ? static_cast<RecordCuda *>(head.m_record) : (RecordCuda *)0;
if (!alloc_ptr || record->m_alloc_ptr != head_cuda) {
Kokkos::Impl::throw_runtime_exception(
std::string("Kokkos::Impl::SharedAllocationRecord< Kokkos::CudaSpace , "
"void >::get_record ERROR"));
}
return record;
}
SharedAllocationRecord<Kokkos::CudaUVMSpace, void> *SharedAllocationRecord<
Kokkos::CudaUVMSpace, void>::get_record(void *alloc_ptr) {
using Header = SharedAllocationHeader;
using RecordCuda = SharedAllocationRecord<Kokkos::CudaUVMSpace, void>;
Header *const h =
alloc_ptr ? reinterpret_cast<Header *>(alloc_ptr) - 1 : (Header *)0;
if (!alloc_ptr || h->m_record->m_alloc_ptr != h) {
Kokkos::Impl::throw_runtime_exception(
std::string("Kokkos::Impl::SharedAllocationRecord< "
"Kokkos::CudaUVMSpace , void >::get_record ERROR"));
}
return static_cast<RecordCuda *>(h->m_record);
}
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>
*SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::get_record(
void *alloc_ptr) {
using Header = SharedAllocationHeader;
using RecordCuda = SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>;
Header *const h =
alloc_ptr ? reinterpret_cast<Header *>(alloc_ptr) - 1 : (Header *)0;
if (!alloc_ptr || h->m_record->m_alloc_ptr != h) {
Kokkos::Impl::throw_runtime_exception(
std::string("Kokkos::Impl::SharedAllocationRecord< "
"Kokkos::CudaHostPinnedSpace , void >::get_record ERROR"));
}
return static_cast<RecordCuda *>(h->m_record);
}
// </editor-fold> end SharedAllocationRecord::get_record() }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="SharedAllocationRecord::print_records()"> {{{1
// Iterate records to print orphaned memory ...
void SharedAllocationRecord<Kokkos::CudaSpace, void>::print_records(
std::ostream &s, const Kokkos::CudaSpace &, bool detail) {
(void)s;
(void)detail;
#ifdef KOKKOS_DEBUG
SharedAllocationRecord<void, void> *r = &s_root_record;
char buffer[256];
SharedAllocationHeader head;
if (detail) {
do {
if (r->m_alloc_ptr) {
Kokkos::Impl::DeepCopy<HostSpace, CudaSpace>(
&head, r->m_alloc_ptr, sizeof(SharedAllocationHeader));
} else {
head.m_label[0] = 0;
}
// Formatting dependent on sizeof(uintptr_t)
const char *format_string;
if (sizeof(uintptr_t) == sizeof(unsigned long)) {
format_string =
"Cuda addr( 0x%.12lx ) list( 0x%.12lx 0x%.12lx ) extent[ 0x%.12lx "
"+ %.8ld ] count(%d) dealloc(0x%.12lx) %s\n";
} else if (sizeof(uintptr_t) == sizeof(unsigned long long)) {
format_string =
"Cuda addr( 0x%.12llx ) list( 0x%.12llx 0x%.12llx ) extent[ "
"0x%.12llx + %.8ld ] count(%d) dealloc(0x%.12llx) %s\n";
}
snprintf(buffer, 256, format_string, reinterpret_cast<uintptr_t>(r),
reinterpret_cast<uintptr_t>(r->m_prev),
reinterpret_cast<uintptr_t>(r->m_next),
reinterpret_cast<uintptr_t>(r->m_alloc_ptr), r->m_alloc_size,
r->m_count, reinterpret_cast<uintptr_t>(r->m_dealloc),
head.m_label);
s << buffer;
r = r->m_next;
} while (r != &s_root_record);
} else {
do {
if (r->m_alloc_ptr) {
Kokkos::Impl::DeepCopy<HostSpace, CudaSpace>(
&head, r->m_alloc_ptr, sizeof(SharedAllocationHeader));
// Formatting dependent on sizeof(uintptr_t)
const char *format_string;
if (sizeof(uintptr_t) == sizeof(unsigned long)) {
format_string = "Cuda [ 0x%.12lx + %ld ] %s\n";
} else if (sizeof(uintptr_t) == sizeof(unsigned long long)) {
format_string = "Cuda [ 0x%.12llx + %ld ] %s\n";
}
snprintf(buffer, 256, format_string,
reinterpret_cast<uintptr_t>(r->data()), r->size(),
head.m_label);
} else {
snprintf(buffer, 256, "Cuda [ 0 + 0 ]\n");
}
s << buffer;
r = r->m_next;
} while (r != &s_root_record);
}
#else
Kokkos::Impl::throw_runtime_exception(
"SharedAllocationHeader<CudaSpace>::print_records only works with "
"KOKKOS_DEBUG enabled");
#endif
}
void SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::print_records(
std::ostream &s, const Kokkos::CudaUVMSpace &, bool detail) {
(void)s;
(void)detail;
#ifdef KOKKOS_DEBUG
SharedAllocationRecord<void, void>::print_host_accessible_records(
s, "CudaUVM", &s_root_record, detail);
#else
Kokkos::Impl::throw_runtime_exception(
"SharedAllocationHeader<CudaSpace>::print_records only works with "
"KOKKOS_DEBUG enabled");
#endif
}
void SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::print_records(
std::ostream &s, const Kokkos::CudaHostPinnedSpace &, bool detail) {
(void)s;
(void)detail;
#ifdef KOKKOS_DEBUG
SharedAllocationRecord<void, void>::print_host_accessible_records(
s, "CudaHostPinned", &s_root_record, detail);
#else
Kokkos::Impl::throw_runtime_exception(
"SharedAllocationHeader<CudaSpace>::print_records only works with "
"KOKKOS_DEBUG enabled");
#endif
}
// </editor-fold> end SharedAllocationRecord::print_records() }}}1
//==============================================================================
void *cuda_resize_scratch_space(std::int64_t bytes, bool force_shrink) {
static void *ptr = nullptr;
static std::int64_t current_size = 0;
if (current_size == 0) {
current_size = bytes;
ptr = Kokkos::kokkos_malloc<Kokkos::CudaSpace>("CudaSpace::ScratchMemory",
current_size);
}
if (bytes > current_size) {
current_size = bytes;
Kokkos::kokkos_free<Kokkos::CudaSpace>(ptr);
ptr = Kokkos::kokkos_malloc<Kokkos::CudaSpace>("CudaSpace::ScratchMemory",
current_size);
}
if ((bytes < current_size) && (force_shrink)) {
current_size = bytes;
Kokkos::kokkos_free<Kokkos::CudaSpace>(ptr);
ptr = Kokkos::kokkos_malloc<Kokkos::CudaSpace>("CudaSpace::ScratchMemory",
current_size);
}
return ptr;
}
void cuda_prefetch_pointer(const Cuda &space, const void *ptr, size_t bytes,
bool to_device) {
if ((ptr == nullptr) || (bytes == 0)) return;
cudaPointerAttributes attr;
CUDA_SAFE_CALL(cudaPointerGetAttributes(&attr, ptr));
// I measured this and it turns out prefetching towards the host slows
// DualView syncs down. Probably because the latency is not too bad in the
// first place for the pull down. If we want to change that provde
// cudaCpuDeviceId as the device if to_device is false
#if CUDA_VERSION < 10000
bool is_managed = attr.isManaged;
#else
bool is_managed = attr.type == cudaMemoryTypeManaged;
#endif
if (to_device && is_managed &&
space.cuda_device_prop().concurrentManagedAccess) {
CUDA_SAFE_CALL(cudaMemPrefetchAsync(ptr, bytes, space.cuda_device(),
space.cuda_stream()));
}
}
} // namespace Impl
} // namespace Kokkos
#else
void KOKKOS_CORE_SRC_CUDA_CUDASPACE_PREVENT_LINK_ERROR() {}
#endif // KOKKOS_ENABLE_CUDA
| 1 | 23,457 | this call doesn't work doesn't? I mean there doesn't seem to be an 2 argument allocate overload. Maybe arg_logical_size should just be defaulted to the arg_alloc_size thing. Or we should just report out physical allocation size instead of logical. | kokkos-kokkos | cpp |
@@ -32,7 +32,7 @@ module Beaker
'puppetbin' => '/opt/puppet/bin/puppet',
'puppetbindir' => '/opt/puppet/bin',
'puppetsbindir' => '/opt/puppet/sbin',
- 'privatebindir' => '/opt/puppetlabs/puppet/bin',
+ 'privatebindir' => '/opt/puppet/bin',
'puppetvardir' => '/var/opt/lib/pe-puppet',
'hieradatadir' => '/var/lib/hiera',
'hieraconf' => '/etc/puppetlabs/puppet/hiera.yaml', | 1 | module Beaker
module DSL
module InstallUtils
#
# This module contains default values for pe paths and directorys per-platform
#
module PEDefaults
#Here be the pathing and default values for PE installs
#
PE_DEFAULTS = {
'mac' => {
'puppetserver-confdir' => '/etc/puppetlabs/puppetserver/conf.d',
'puppetservice' => 'pe-httpd',
'puppetpath' => '/etc/puppetlabs/puppet',
'puppetconfdir' => '/etc/puppetlabs/puppet',
'puppetcodedir' => '/etc/puppetlabs/puppet',
'puppetbin' => '/opt/puppet/bin/puppet',
'puppetbindir' => '/opt/puppet/bin',
'puppetsbindir' => '/opt/puppet/sbin',
'puppetvardir' => '/var/opt/lib/pe-puppet',
'hieradatadir' => '/var/lib/hiera',
'hieraconf' => '/etc/puppetlabs/puppet/hiera.yaml',
'distmoduledir' => '/etc/puppetlabs/puppet/modules',
'sitemoduledir' => '/opt/puppet/share/puppet/modules',
},
'unix' => {
'puppetserver-confdir' => '/etc/puppetlabs/puppetserver/conf.d',
'puppetservice' => 'pe-httpd',
'puppetpath' => '/etc/puppetlabs/puppet',
'puppetconfdir' => '/etc/puppetlabs/puppet',
'puppetbin' => '/opt/puppet/bin/puppet',
'puppetbindir' => '/opt/puppet/bin',
'puppetsbindir' => '/opt/puppet/sbin',
'privatebindir' => '/opt/puppetlabs/puppet/bin',
'puppetvardir' => '/var/opt/lib/pe-puppet',
'hieradatadir' => '/var/lib/hiera',
'hieraconf' => '/etc/puppetlabs/puppet/hiera.yaml',
'distmoduledir' => '/etc/puppetlabs/puppet/modules',
'sitemoduledir' => '/opt/puppet/share/puppet/modules',
},
'windows' => { #cygwin windows
'puppetservice' => 'pe-httpd',
'puppetpath' => '`cygpath -smF 35`/PuppetLabs/puppet/etc',
'puppetconfdir' => '`cygpath -smF 35`/PuppetLabs/puppet/etc',
'puppetcodedir' => '`cygpath -smF 35`/PuppetLabs/puppet/etc',
'hieraconf' => '`cygpath -smF 35`/Puppetlabs/puppet/etc/hiera.yaml',
'puppetvardir' => '`cygpath -smF 35`/PuppetLabs/puppet/var',
'distmoduledir' => '`cygpath -smF 35`/PuppetLabs/puppet/etc/modules',
'sitemoduledir' => 'C:/usr/share/puppet/modules',
#let's just add both potential bin dirs to the path
'puppetbindir' => '/cygdrive/c/Program Files (x86)/Puppet Labs/Puppet Enterprise/bin:/cygdrive/c/Program Files/Puppet Labs/Puppet Enterprise/bin',
'privatebindir' => '/cygdrive/c/Program Files (x86)/Puppet Labs/Puppet Enterprise/sys/ruby/bin:/cygdrive/c/Program Files/Puppet Labs/Puppet Enterprise/sys/ruby/bin',
},
'pswindows' => { #windows windows
'puppetservice' => 'pe-httpd',
'puppetpath' => 'C:\\ProgramData\\PuppetLabs\\puppet\\etc',
'puppetconfdir' => 'C:\\ProgramData\\PuppetLabs\\puppet\\etc',
'puppetcodedir' => 'C:\\ProgramData\\PuppetLabs\\puppet\\etc',
'hieraconf' => 'C:\\ProgramData\\PuppetLabs\\puppet\\etc\\hiera.yaml',
'distmoduledir' => 'C:\\ProgramData\\PuppetLabs\\puppet\\etc\\modules',
'sitemoduledir' => 'C:\\usr\\share\\puppet\\modules',
'puppetvardir' => 'C:\\ProgramData\\PuppetLabs\\puppet\\var',
'puppetbindir' => '"C:\\Program Files (x86)\\PuppetLabs\\Puppet Enterprise\\bin";"C:\\Program Files\\PuppetLabs\\Puppet Enterprise\\bin"'
},
}
# Add the appropriate pe defaults to the host object so that they can be accessed using host[option], set host[:type] = pe
# @param [Host] host A single host to act upon
# @param [String] platform The platform type of this host, one of windows, pswindows, mac & unix
def add_platform_pe_defaults(host, platform)
PE_DEFAULTS[platform].each_pair do |key, val|
host[key] = val
end
# add the type and group here for backwards compatability
if host['platform'] =~ /windows/
host['group'] = 'Administrators'
else
host['group'] = 'pe-puppet'
end
host['type'] = 'pe'
# newer pe requires a different puppetservice name, set it here on the master
if host['roles'].include?('master')
if host['pe_ver'] and (not version_is_less(host['pe_ver'], '3.4'))
host['puppetservice'] = 'pe-puppetserver'
end
end
end
# Add the appropriate pe defaults to an array of hosts
# @param [Host, Array<Host>, String, Symbol] hosts One or more hosts to act upon,
# or a role (String or Symbol) that identifies one or more hosts.
def add_pe_defaults_on(hosts)
block_on hosts do | host |
case host.class.to_s.downcase
when /aix|freebsd|unix/
platform = 'unix'
when /mac/
platform = 'mac'
when /pswindows/
platform = 'pswindows'
else
platform = 'windows'
end
add_platform_pe_defaults(host, platform)
end
end
# Remove the appropriate pe defaults from the host object so that they can no longer be accessed using host[option], set host[:type] = nil
# @param [Host] host A single host to act upon
# @param [String] platform The platform type of this host, one of windows, freebsd, mac & unix
def remove_platform_pe_defaults(host, platform)
PE_DEFAULTS[platform].each_pair do |key, val|
host.delete(key)
end
host['group'] = nil
host['type'] = nil
end
# Remove the appropriate pe defaults from an array of hosts
# @param [Host, Array<Host>, String, Symbol] hosts One or more hosts to act upon,
# or a role (String or Symbol) that identifies one or more hosts.
def remove_pe_defaults_on(hosts)
block_on hosts do | host |
case host.class.to_s.downcase
when /aix|unix/
platform = 'unix'
when /freebsd/
platform = 'freebsd'
when /mac/
platform = 'mac'
when /pswindows/
platform = 'pswindows'
else
platform = 'windows'
end
remove_platform_pe_defaults(host, platform)
end
end
end
end
end
end
| 1 | 10,552 | This winds up flipping the desired values. Looks like I gave you a bum steer @kevpl | voxpupuli-beaker | rb |
@@ -106,13 +106,9 @@ func main() {
}
func initLogger(cfg config.Config) {
- addr, err := cfg.BlockchainAddress()
- if err != nil {
- glog.Fatalln("Failed to get producer address from pub/kri key: ", err)
- return
- }
+ addr := cfg.ProducerAddress()
if err := log.InitGlobal(cfg.Log, zap.Fields(
- zap.String("addr", addr.String()),
+ zap.String("iotexAddress", addr.String()),
zap.String("networkAddress", fmt.Sprintf("%s:%d", cfg.Network.Host, cfg.Network.Port)),
)); err != nil {
glog.Println("Cannot config global logger, use default one: ", err) | 1 | // Copyright (c) 2018 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
// Usage:
// make build
// ./bin/server -config-file=./config.yaml
//
package main
import (
"context"
"flag"
"fmt"
glog "log"
"os"
"os/signal"
"syscall"
"github.com/iotexproject/iotex-core/blockchain/genesis"
_ "net/http/pprof"
_ "go.uber.org/automaxprocs"
"go.uber.org/zap"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/pkg/probe"
"github.com/iotexproject/iotex-core/server/itx"
)
func init() {
flag.Usage = func() {
_, _ = fmt.Fprintf(os.Stderr,
"usage: server -config-path=[string]\n")
flag.PrintDefaults()
os.Exit(2)
}
flag.Parse()
}
func main() {
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
signal.Notify(stop, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
stopped := make(chan struct{})
livenessCtx, livenessCancel := context.WithCancel(context.Background())
genesisCfg, err := genesis.New()
if err != nil {
glog.Fatalln("Failed to new genesis config.", zap.Error(err))
}
cfg, err := config.New()
if err != nil {
glog.Fatalln("Failed to new config.", zap.Error(err))
}
initLogger(cfg)
cfg.Genesis = genesisCfg
log.S().Infof("Config in use: %+v", cfg)
// liveness start
probeSvr := probe.New(cfg.System.HTTPProbePort)
if err := probeSvr.Start(ctx); err != nil {
log.L().Fatal("Failed to start probe server.", zap.Error(err))
}
go func() {
<-stop
// start stopping
cancel()
<-stopped
// liveness end
if err := probeSvr.Stop(livenessCtx); err != nil {
log.L().Error("Error when stopping probe server.", zap.Error(err))
}
livenessCancel()
}()
// create and start the node
svr, err := itx.NewServer(cfg)
if err != nil {
log.L().Fatal("Failed to create server.", zap.Error(err))
}
cfgsub, err := config.NewSub()
if err != nil {
log.L().Fatal("Failed to new sub chain config.", zap.Error(err))
}
if cfgsub.Chain.ID != 0 {
if err := svr.NewSubChainService(cfgsub); err != nil {
log.L().Fatal("Failed to new sub chain.", zap.Error(err))
}
}
itx.StartServer(ctx, svr, probeSvr, cfg)
close(stopped)
<-livenessCtx.Done()
}
func initLogger(cfg config.Config) {
addr, err := cfg.BlockchainAddress()
if err != nil {
glog.Fatalln("Failed to get producer address from pub/kri key: ", err)
return
}
if err := log.InitGlobal(cfg.Log, zap.Fields(
zap.String("addr", addr.String()),
zap.String("networkAddress", fmt.Sprintf("%s:%d", cfg.Network.Host, cfg.Network.Port)),
)); err != nil {
glog.Println("Cannot config global logger, use default one: ", err)
}
}
| 1 | 15,809 | nit: let's call our address ioAddr from now on | iotexproject-iotex-core | go |
@@ -12845,7 +12845,9 @@ bool CoreChecks::PreCallValidateGetBufferDeviceAddressEXT(VkDevice device, const
void CoreChecks::PreCallRecordGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties *pPhysicalDeviceProperties) {
- if (enabled.gpu_validation && enabled.gpu_validation_reserve_binding_slot) {
+ // There is an implicit layer that can cause this call to return 0 for maxBoundDescriptorSets - Ignore such calls
+ if (enabled.gpu_validation && enabled.gpu_validation_reserve_binding_slot &&
+ pPhysicalDeviceProperties->limits.maxBoundDescriptorSets > 0) {
if (pPhysicalDeviceProperties->limits.maxBoundDescriptorSets > 1) {
pPhysicalDeviceProperties->limits.maxBoundDescriptorSets -= 1;
} else { | 1 | /* Copyright (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
* Copyright (C) 2015-2019 Google 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.
*
* Author: Cody Northrop <cnorthrop@google.com>
* Author: Michael Lentine <mlentine@google.com>
* Author: Tobin Ehlis <tobine@google.com>
* Author: Chia-I Wu <olv@google.com>
* Author: Chris Forbes <chrisf@ijw.co.nz>
* Author: Mark Lobodzinski <mark@lunarg.com>
* Author: Ian Elliott <ianelliott@google.com>
* Author: Dave Houlton <daveh@lunarg.com>
* Author: Dustin Graves <dustin@lunarg.com>
* Author: Jeremy Hayes <jeremy@lunarg.com>
* Author: Jon Ashburn <jon@lunarg.com>
* Author: Karl Schultz <karl@lunarg.com>
* Author: Mark Young <marky@lunarg.com>
* Author: Mike Schuchardt <mikes@lunarg.com>
* Author: Mike Weiblen <mikew@lunarg.com>
* Author: Tony Barbour <tony@LunarG.com>
* Author: John Zulauf <jzulauf@lunarg.com>
* Author: Shannon McPherson <shannon@lunarg.com>
*/
// Allow use of STL min and max functions in Windows
#define NOMINMAX
#include <algorithm>
#include <array>
#include <assert.h>
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <valarray>
#include "vk_loader_platform.h"
#include "vk_dispatch_table_helper.h"
#include "vk_enum_string_helper.h"
#include "chassis.h"
#include "convert_to_renderpass2.h"
#include "core_validation.h"
#include "buffer_validation.h"
#include "shader_validation.h"
#include "vk_layer_utils.h"
// These functions are defined *outside* the core_validation namespace as their type
// is also defined outside that namespace
size_t PipelineLayoutCompatDef::hash() const {
hash_util::HashCombiner hc;
// The set number is integral to the CompatDef's distinctiveness
hc << set << push_constant_ranges.get();
const auto &descriptor_set_layouts = *set_layouts_id.get();
for (uint32_t i = 0; i <= set; i++) {
hc << descriptor_set_layouts[i].get();
}
return hc.Value();
}
bool PipelineLayoutCompatDef::operator==(const PipelineLayoutCompatDef &other) const {
if ((set != other.set) || (push_constant_ranges != other.push_constant_ranges)) {
return false;
}
if (set_layouts_id == other.set_layouts_id) {
// if it's the same set_layouts_id, then *any* subset will match
return true;
}
// They aren't exactly the same PipelineLayoutSetLayouts, so we need to check if the required subsets match
const auto &descriptor_set_layouts = *set_layouts_id.get();
assert(set < descriptor_set_layouts.size());
const auto &other_ds_layouts = *other.set_layouts_id.get();
assert(set < other_ds_layouts.size());
for (uint32_t i = 0; i <= set; i++) {
if (descriptor_set_layouts[i] != other_ds_layouts[i]) {
return false;
}
}
return true;
}
using std::max;
using std::string;
using std::stringstream;
using std::unique_ptr;
using std::unordered_map;
using std::unordered_set;
using std::vector;
// WSI Image Objects bypass usual Image Object creation methods. A special Memory
// Object value will be used to identify them internally.
static const VkDeviceMemory MEMTRACKER_SWAP_CHAIN_IMAGE_KEY = (VkDeviceMemory)(-1);
// 2nd special memory handle used to flag object as unbound from memory
static const VkDeviceMemory MEMORY_UNBOUND = VkDeviceMemory(~((uint64_t)(0)) - 1);
// Return buffer state ptr for specified buffer or else NULL
BUFFER_STATE *CoreChecks::GetBufferState(VkBuffer buffer) {
auto buff_it = bufferMap.find(buffer);
if (buff_it == bufferMap.end()) {
return nullptr;
}
return buff_it->second.get();
}
// Return IMAGE_VIEW_STATE ptr for specified imageView or else NULL
IMAGE_VIEW_STATE *CoreChecks::GetImageViewState(VkImageView image_view) {
auto iv_it = imageViewMap.find(image_view);
if (iv_it == imageViewMap.end()) {
return nullptr;
}
return iv_it->second.get();
}
// Get the global map of pending releases
GlobalQFOTransferBarrierMap<VkImageMemoryBarrier> &CoreChecks::GetGlobalQFOReleaseBarrierMap(
const QFOTransferBarrier<VkImageMemoryBarrier>::Tag &type_tag) {
return qfo_release_image_barrier_map;
}
GlobalQFOTransferBarrierMap<VkBufferMemoryBarrier> &CoreChecks::GetGlobalQFOReleaseBarrierMap(
const QFOTransferBarrier<VkBufferMemoryBarrier>::Tag &type_tag) {
return qfo_release_buffer_barrier_map;
}
// Get the image viewstate for a given framebuffer attachment
IMAGE_VIEW_STATE *CoreChecks::GetAttachmentImageViewState(FRAMEBUFFER_STATE *framebuffer, uint32_t index) {
assert(framebuffer && (index < framebuffer->createInfo.attachmentCount));
const VkImageView &image_view = framebuffer->createInfo.pAttachments[index];
return GetImageViewState(image_view);
}
// Return sampler node ptr for specified sampler or else NULL
SAMPLER_STATE *CoreChecks::GetSamplerState(VkSampler sampler) {
auto sampler_it = samplerMap.find(sampler);
if (sampler_it == samplerMap.end()) {
return nullptr;
}
return sampler_it->second.get();
}
// Return image state ptr for specified image or else NULL
IMAGE_STATE *CoreChecks::GetImageState(VkImage image) {
auto img_it = imageMap.find(image);
if (img_it == imageMap.end()) {
return nullptr;
}
return img_it->second.get();
}
// Return swapchain node for specified swapchain or else NULL
SWAPCHAIN_NODE *CoreChecks::GetSwapchainState(VkSwapchainKHR swapchain) {
auto swp_it = swapchainMap.find(swapchain);
if (swp_it == swapchainMap.end()) {
return nullptr;
}
return swp_it->second.get();
}
// Return buffer node ptr for specified buffer or else NULL
BUFFER_VIEW_STATE *CoreChecks::GetBufferViewState(VkBufferView buffer_view) {
auto bv_it = bufferViewMap.find(buffer_view);
if (bv_it == bufferViewMap.end()) {
return nullptr;
}
return bv_it->second.get();
}
FENCE_STATE *CoreChecks::GetFenceState(VkFence fence) {
auto it = fenceMap.find(fence);
if (it == fenceMap.end()) {
return nullptr;
}
return it->second.get();
}
EVENT_STATE *CoreChecks::GetEventState(VkEvent event) {
auto it = eventMap.find(event);
if (it == eventMap.end()) {
return nullptr;
}
return &it->second;
}
QUERY_POOL_STATE *CoreChecks::GetQueryPoolState(VkQueryPool query_pool) {
auto it = queryPoolMap.find(query_pool);
if (it == queryPoolMap.end()) {
return nullptr;
}
return it->second.get();
}
QUEUE_STATE *CoreChecks::GetQueueState(VkQueue queue) {
auto it = queueMap.find(queue);
if (it == queueMap.end()) {
return nullptr;
}
return &it->second;
}
SEMAPHORE_STATE *CoreChecks::GetSemaphoreState(VkSemaphore semaphore) {
auto it = semaphoreMap.find(semaphore);
if (it == semaphoreMap.end()) {
return nullptr;
}
return it->second.get();
}
COMMAND_POOL_STATE *CoreChecks::GetCommandPoolState(VkCommandPool pool) {
auto it = commandPoolMap.find(pool);
if (it == commandPoolMap.end()) {
return nullptr;
}
return it->second.get();
}
PHYSICAL_DEVICE_STATE *CoreChecks::GetPhysicalDeviceState(VkPhysicalDevice phys) {
auto *phys_dev_map = ((physical_device_map.size() > 0) ? &physical_device_map : &instance_state->physical_device_map);
auto it = phys_dev_map->find(phys);
if (it == phys_dev_map->end()) {
return nullptr;
}
return &it->second;
}
PHYSICAL_DEVICE_STATE *CoreChecks::GetPhysicalDeviceState() { return physical_device_state; }
SURFACE_STATE *CoreChecks::GetSurfaceState(VkSurfaceKHR surface) {
auto *surf_map = ((surface_map.size() > 0) ? &surface_map : &instance_state->surface_map);
auto it = surf_map->find(surface);
if (it == surf_map->end()) {
return nullptr;
}
return it->second.get();
}
// Return ptr to memory binding for given handle of specified type
BINDABLE *CoreChecks::GetObjectMemBinding(uint64_t handle, VulkanObjectType type) {
switch (type) {
case kVulkanObjectTypeImage:
return GetImageState(VkImage(handle));
case kVulkanObjectTypeBuffer:
return GetBufferState(VkBuffer(handle));
default:
break;
}
return nullptr;
}
ImageSubresourceLayoutMap::InitialLayoutState::InitialLayoutState(const CMD_BUFFER_STATE &cb_state,
const IMAGE_VIEW_STATE *view_state)
: image_view(VK_NULL_HANDLE), aspect_mask(0), label(cb_state.debug_label) {
if (view_state) {
image_view = view_state->image_view;
aspect_mask = view_state->create_info.subresourceRange.aspectMask;
}
}
std::string FormatDebugLabel(const char *prefix, const LoggingLabel &label) {
if (label.Empty()) return std::string();
std::string out;
string_sprintf(&out, "%sVkDebugUtilsLabel(name='%s' color=[%g, %g %g, %g])", prefix, label.name.c_str(), label.color[0],
label.color[1], label.color[2], label.color[3]);
return out;
}
// the ImageLayoutMap implementation bakes in the number of valid aspects -- we have to choose the correct one at construction time
template <uint32_t kThreshold>
static std::unique_ptr<ImageSubresourceLayoutMap> LayoutMapFactoryByAspect(const IMAGE_STATE &image_state) {
ImageSubresourceLayoutMap *map = nullptr;
switch (image_state.full_range.aspectMask) {
case VK_IMAGE_ASPECT_COLOR_BIT:
map = new ImageSubresourceLayoutMapImpl<ColorAspectTraits, kThreshold>(image_state);
break;
case VK_IMAGE_ASPECT_DEPTH_BIT:
map = new ImageSubresourceLayoutMapImpl<DepthAspectTraits, kThreshold>(image_state);
break;
case VK_IMAGE_ASPECT_STENCIL_BIT:
map = new ImageSubresourceLayoutMapImpl<StencilAspectTraits, kThreshold>(image_state);
break;
case VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT:
map = new ImageSubresourceLayoutMapImpl<DepthStencilAspectTraits, kThreshold>(image_state);
break;
case VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT:
map = new ImageSubresourceLayoutMapImpl<Multiplane2AspectTraits, kThreshold>(image_state);
break;
case VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT | VK_IMAGE_ASPECT_PLANE_2_BIT:
map = new ImageSubresourceLayoutMapImpl<Multiplane3AspectTraits, kThreshold>(image_state);
break;
}
assert(map); // We shouldn't be able to get here null unless the traits cases are incomplete
return std::unique_ptr<ImageSubresourceLayoutMap>(map);
}
static std::unique_ptr<ImageSubresourceLayoutMap> LayoutMapFactory(const IMAGE_STATE &image_state) {
std::unique_ptr<ImageSubresourceLayoutMap> map;
const uint32_t kAlwaysDenseLimit = 16; // About a cacheline on deskop architectures
if (image_state.full_range.layerCount <= kAlwaysDenseLimit) {
// Create a dense row map
map = LayoutMapFactoryByAspect<0>(image_state);
} else {
// Create an initially sparse row map
map = LayoutMapFactoryByAspect<kAlwaysDenseLimit>(image_state);
}
return map;
}
// The const variant only need the image as it is the key for the map
const ImageSubresourceLayoutMap *GetImageSubresourceLayoutMap(const CMD_BUFFER_STATE *cb_state, VkImage image) {
auto it = cb_state->image_layout_map.find(image);
if (it == cb_state->image_layout_map.cend()) {
return nullptr;
}
return it->second.get();
}
// The non-const variant only needs the image state, as the factory requires it to construct a new entry
ImageSubresourceLayoutMap *GetImageSubresourceLayoutMap(CMD_BUFFER_STATE *cb_state, const IMAGE_STATE &image_state) {
auto it = cb_state->image_layout_map.find(image_state.image);
if (it == cb_state->image_layout_map.end()) {
// Empty slot... fill it in.
auto insert_pair = cb_state->image_layout_map.insert(std::make_pair(image_state.image, LayoutMapFactory(image_state)));
assert(insert_pair.second);
ImageSubresourceLayoutMap *new_map = insert_pair.first->second.get();
assert(new_map);
return new_map;
}
return it->second.get();
}
// Return ptr to info in map container containing mem, or NULL if not found
// Calls to this function should be wrapped in mutex
DEVICE_MEMORY_STATE *CoreChecks::GetDevMemState(const VkDeviceMemory mem) {
auto mem_it = memObjMap.find(mem);
if (mem_it == memObjMap.end()) {
return NULL;
}
return mem_it->second.get();
}
void CoreChecks::AddMemObjInfo(void *object, const VkDeviceMemory mem, const VkMemoryAllocateInfo *pAllocateInfo) {
assert(object != NULL);
auto *mem_info = new DEVICE_MEMORY_STATE(object, mem, pAllocateInfo);
memObjMap[mem] = unique_ptr<DEVICE_MEMORY_STATE>(mem_info);
auto dedicated = lvl_find_in_chain<VkMemoryDedicatedAllocateInfoKHR>(pAllocateInfo->pNext);
if (dedicated) {
mem_info->is_dedicated = true;
mem_info->dedicated_buffer = dedicated->buffer;
mem_info->dedicated_image = dedicated->image;
}
auto export_info = lvl_find_in_chain<VkExportMemoryAllocateInfo>(pAllocateInfo->pNext);
if (export_info) {
mem_info->is_export = true;
mem_info->export_handle_type_flags = export_info->handleTypes;
}
}
// Create binding link between given sampler and command buffer node
void CoreChecks::AddCommandBufferBindingSampler(CMD_BUFFER_STATE *cb_node, SAMPLER_STATE *sampler_state) {
auto inserted = cb_node->object_bindings.insert({HandleToUint64(sampler_state->sampler), kVulkanObjectTypeSampler});
if (inserted.second) {
// Only need to complete the cross-reference if this is a new item
sampler_state->cb_bindings.insert(cb_node);
}
}
// Create binding link between given image node and command buffer node
void CoreChecks::AddCommandBufferBindingImage(CMD_BUFFER_STATE *cb_node, IMAGE_STATE *image_state) {
// Skip validation if this image was created through WSI
if (image_state->binding.mem != MEMTRACKER_SWAP_CHAIN_IMAGE_KEY) {
// First update cb binding for image
auto image_inserted = cb_node->object_bindings.insert({HandleToUint64(image_state->image), kVulkanObjectTypeImage});
if (image_inserted.second) {
// Only need to continue if this is a new item (the rest of the work would have be done previous)
image_state->cb_bindings.insert(cb_node);
// Now update CB binding in MemObj mini CB list
for (auto mem_binding : image_state->GetBoundMemory()) {
DEVICE_MEMORY_STATE *pMemInfo = GetDevMemState(mem_binding);
if (pMemInfo) {
// Now update CBInfo's Mem reference list
auto mem_inserted = cb_node->memObjs.insert(mem_binding);
if (mem_inserted.second) {
// Only need to complete the cross-reference if this is a new item
pMemInfo->cb_bindings.insert(cb_node);
}
}
}
}
}
}
// Create binding link between given image view node and its image with command buffer node
void CoreChecks::AddCommandBufferBindingImageView(CMD_BUFFER_STATE *cb_node, IMAGE_VIEW_STATE *view_state) {
// First add bindings for imageView
auto inserted = cb_node->object_bindings.insert({HandleToUint64(view_state->image_view), kVulkanObjectTypeImageView});
if (inserted.second) {
// Only need to continue if this is a new item
view_state->cb_bindings.insert(cb_node);
auto image_state = GetImageState(view_state->create_info.image);
// Add bindings for image within imageView
if (image_state) {
AddCommandBufferBindingImage(cb_node, image_state);
}
}
}
// Create binding link between given buffer node and command buffer node
void CoreChecks::AddCommandBufferBindingBuffer(CMD_BUFFER_STATE *cb_node, BUFFER_STATE *buffer_state) {
// First update cb binding for buffer
auto buffer_inserted = cb_node->object_bindings.insert({HandleToUint64(buffer_state->buffer), kVulkanObjectTypeBuffer});
if (buffer_inserted.second) {
// Only need to continue if this is a new item
buffer_state->cb_bindings.insert(cb_node);
// Now update CB binding in MemObj mini CB list
for (auto mem_binding : buffer_state->GetBoundMemory()) {
DEVICE_MEMORY_STATE *pMemInfo = GetDevMemState(mem_binding);
if (pMemInfo) {
// Now update CBInfo's Mem reference list
auto inserted = cb_node->memObjs.insert(mem_binding);
if (inserted.second) {
// Only need to complete the cross-reference if this is a new item
pMemInfo->cb_bindings.insert(cb_node);
}
}
}
}
}
// Create binding link between given buffer view node and its buffer with command buffer node
void CoreChecks::AddCommandBufferBindingBufferView(CMD_BUFFER_STATE *cb_node, BUFFER_VIEW_STATE *view_state) {
// First add bindings for bufferView
auto inserted = cb_node->object_bindings.insert({HandleToUint64(view_state->buffer_view), kVulkanObjectTypeBufferView});
if (inserted.second) {
// Only need to complete the cross-reference if this is a new item
view_state->cb_bindings.insert(cb_node);
auto buffer_state = GetBufferState(view_state->create_info.buffer);
// Add bindings for buffer within bufferView
if (buffer_state) {
AddCommandBufferBindingBuffer(cb_node, buffer_state);
}
}
}
// For every mem obj bound to particular CB, free bindings related to that CB
void CoreChecks::ClearCmdBufAndMemReferences(CMD_BUFFER_STATE *cb_node) {
if (cb_node) {
if (cb_node->memObjs.size() > 0) {
for (auto mem : cb_node->memObjs) {
DEVICE_MEMORY_STATE *pInfo = GetDevMemState(mem);
if (pInfo) {
pInfo->cb_bindings.erase(cb_node);
}
}
cb_node->memObjs.clear();
}
}
}
// Clear a single object binding from given memory object
void CoreChecks::ClearMemoryObjectBinding(uint64_t handle, VulkanObjectType type, VkDeviceMemory mem) {
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem);
// This obj is bound to a memory object. Remove the reference to this object in that memory object's list
if (mem_info) {
mem_info->obj_bindings.erase({handle, type});
}
}
// ClearMemoryObjectBindings clears the binding of objects to memory
// For the given object it pulls the memory bindings and makes sure that the bindings
// no longer refer to the object being cleared. This occurs when objects are destroyed.
void CoreChecks::ClearMemoryObjectBindings(uint64_t handle, VulkanObjectType type) {
BINDABLE *mem_binding = GetObjectMemBinding(handle, type);
if (mem_binding) {
if (!mem_binding->sparse) {
ClearMemoryObjectBinding(handle, type, mem_binding->binding.mem);
} else { // Sparse, clear all bindings
for (auto &sparse_mem_binding : mem_binding->sparse_bindings) {
ClearMemoryObjectBinding(handle, type, sparse_mem_binding.mem);
}
}
}
}
// For given mem object, verify that it is not null or UNBOUND, if it is, report error. Return skip value.
bool CoreChecks::VerifyBoundMemoryIsValid(VkDeviceMemory mem, uint64_t handle, const char *api_name, const char *type_name,
const char *error_code) {
bool result = false;
if (VK_NULL_HANDLE == mem) {
result = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, handle, error_code,
"%s: Vk%s object %s used with no memory bound. Memory should be bound by calling vkBind%sMemory().",
api_name, type_name, report_data->FormatHandle(handle).c_str(), type_name);
} else if (MEMORY_UNBOUND == mem) {
result =
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, handle, error_code,
"%s: Vk%s object %s used with no memory bound and previously bound memory was freed. Memory must not be freed "
"prior to this operation.",
api_name, type_name, report_data->FormatHandle(handle).c_str());
}
return result;
}
// Check to see if memory was ever bound to this image
bool CoreChecks::ValidateMemoryIsBoundToImage(const IMAGE_STATE *image_state, const char *api_name, const char *error_code) {
bool result = false;
if (0 == (static_cast<uint32_t>(image_state->createInfo.flags) & VK_IMAGE_CREATE_SPARSE_BINDING_BIT)) {
result =
VerifyBoundMemoryIsValid(image_state->binding.mem, HandleToUint64(image_state->image), api_name, "Image", error_code);
}
return result;
}
// Check to see if memory was bound to this buffer
bool CoreChecks::ValidateMemoryIsBoundToBuffer(const BUFFER_STATE *buffer_state, const char *api_name, const char *error_code) {
bool result = false;
if (0 == (static_cast<uint32_t>(buffer_state->createInfo.flags) & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)) {
result = VerifyBoundMemoryIsValid(buffer_state->binding.mem, HandleToUint64(buffer_state->buffer), api_name, "Buffer",
error_code);
}
return result;
}
// SetMemBinding is used to establish immutable, non-sparse binding between a single image/buffer object and memory object.
// Corresponding valid usage checks are in ValidateSetMemBinding().
void CoreChecks::SetMemBinding(VkDeviceMemory mem, BINDABLE *mem_binding, VkDeviceSize memory_offset, uint64_t handle,
VulkanObjectType type) {
assert(mem_binding);
mem_binding->binding.mem = mem;
mem_binding->UpdateBoundMemorySet(); // force recreation of cached set
mem_binding->binding.offset = memory_offset;
mem_binding->binding.size = mem_binding->requirements.size;
if (mem != VK_NULL_HANDLE) {
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem);
if (mem_info) {
mem_info->obj_bindings.insert({handle, type});
// For image objects, make sure default memory state is correctly set
// TODO : What's the best/correct way to handle this?
if (kVulkanObjectTypeImage == type) {
auto const image_state = reinterpret_cast<const IMAGE_STATE *>(mem_binding);
if (image_state) {
VkImageCreateInfo ici = image_state->createInfo;
if (ici.usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
// TODO:: More memory state transition stuff.
}
}
}
}
}
}
// Valid usage checks for a call to SetMemBinding().
// For NULL mem case, output warning
// Make sure given object is in global object map
// IF a previous binding existed, output validation error
// Otherwise, add reference from objectInfo to memoryInfo
// Add reference off of objInfo
// TODO: We may need to refactor or pass in multiple valid usage statements to handle multiple valid usage conditions.
bool CoreChecks::ValidateSetMemBinding(VkDeviceMemory mem, uint64_t handle, VulkanObjectType type, const char *apiName) {
bool skip = false;
// It's an error to bind an object to NULL memory
if (mem != VK_NULL_HANDLE) {
BINDABLE *mem_binding = GetObjectMemBinding(handle, type);
assert(mem_binding);
if (mem_binding->sparse) {
const char *error_code = "VUID-vkBindImageMemory-image-01045";
const char *handle_type = "IMAGE";
if (type == kVulkanObjectTypeBuffer) {
error_code = "VUID-vkBindBufferMemory-buffer-01030";
handle_type = "BUFFER";
} else {
assert(type == kVulkanObjectTypeImage);
}
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), error_code,
"In %s, attempting to bind memory (%s) to object (%s) which was created with sparse memory flags "
"(VK_%s_CREATE_SPARSE_*_BIT).",
apiName, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(handle).c_str(), handle_type);
}
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem);
if (mem_info) {
DEVICE_MEMORY_STATE *prev_binding = GetDevMemState(mem_binding->binding.mem);
if (prev_binding) {
const char *error_code = "VUID-vkBindImageMemory-image-01044";
if (type == kVulkanObjectTypeBuffer) {
error_code = "VUID-vkBindBufferMemory-buffer-01029";
} else {
assert(type == kVulkanObjectTypeImage);
}
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), error_code,
"In %s, attempting to bind memory (%s) to object (%s) which has already been bound to mem object %s.",
apiName, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(handle).c_str(),
report_data->FormatHandle(prev_binding->mem).c_str());
} else if (mem_binding->binding.mem == MEMORY_UNBOUND) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), kVUID_Core_MemTrack_RebindObject,
"In %s, attempting to bind memory (%s) to object (%s) which was previous bound to memory that has "
"since been freed. Memory bindings are immutable in "
"Vulkan so this attempt to bind to new memory is not allowed.",
apiName, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(handle).c_str());
}
}
}
return skip;
}
// For NULL mem case, clear any previous binding Else...
// Make sure given object is in its object map
// IF a previous binding existed, update binding
// Add reference from objectInfo to memoryInfo
// Add reference off of object's binding info
// Return VK_TRUE if addition is successful, VK_FALSE otherwise
bool CoreChecks::SetSparseMemBinding(MEM_BINDING binding, uint64_t handle, VulkanObjectType type) {
bool skip = VK_FALSE;
// Handle NULL case separately, just clear previous binding & decrement reference
if (binding.mem == VK_NULL_HANDLE) {
// TODO : This should cause the range of the resource to be unbound according to spec
} else {
BINDABLE *mem_binding = GetObjectMemBinding(handle, type);
assert(mem_binding);
if (mem_binding) { // Invalid handles are reported by object tracker, but Get returns NULL for them, so avoid SEGV here
assert(mem_binding->sparse);
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(binding.mem);
if (mem_info) {
mem_info->obj_bindings.insert({handle, type});
// Need to set mem binding for this object
mem_binding->sparse_bindings.insert(binding);
mem_binding->UpdateBoundMemorySet();
}
}
}
return skip;
}
bool CoreChecks::ValidateDeviceQueueFamily(uint32_t queue_family, const char *cmd_name, const char *parameter_name,
const char *error_code, bool optional = false) {
bool skip = false;
if (!optional && queue_family == VK_QUEUE_FAMILY_IGNORED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
error_code,
"%s: %s is VK_QUEUE_FAMILY_IGNORED, but it is required to provide a valid queue family index value.",
cmd_name, parameter_name);
} else if (queue_family_index_map.find(queue_family) == queue_family_index_map.end()) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), error_code,
"%s: %s (= %" PRIu32
") is not one of the queue families given via VkDeviceQueueCreateInfo structures when the device was created.",
cmd_name, parameter_name, queue_family);
}
return skip;
}
bool CoreChecks::ValidateQueueFamilies(uint32_t queue_family_count, const uint32_t *queue_families, const char *cmd_name,
const char *array_parameter_name, const char *unique_error_code,
const char *valid_error_code, bool optional = false) {
bool skip = false;
if (queue_families) {
std::unordered_set<uint32_t> set;
for (uint32_t i = 0; i < queue_family_count; ++i) {
std::string parameter_name = std::string(array_parameter_name) + "[" + std::to_string(i) + "]";
if (set.count(queue_families[i])) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), unique_error_code, "%s: %s (=%" PRIu32 ") is not unique within %s array.",
cmd_name, parameter_name.c_str(), queue_families[i], array_parameter_name);
} else {
set.insert(queue_families[i]);
skip |= ValidateDeviceQueueFamily(queue_families[i], cmd_name, parameter_name.c_str(), valid_error_code, optional);
}
}
}
return skip;
}
// Check object status for selected flag state
bool CoreChecks::ValidateStatus(CMD_BUFFER_STATE *pNode, CBStatusFlags status_mask, VkFlags msg_flags, const char *fail_msg,
const char *msg_code) {
if (!(pNode->status & status_mask)) {
return log_msg(report_data, msg_flags, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pNode->commandBuffer),
msg_code, "command buffer object %s: %s..", report_data->FormatHandle(pNode->commandBuffer).c_str(),
fail_msg);
}
return false;
}
// Retrieve pipeline node ptr for given pipeline object
PIPELINE_STATE *CoreChecks::GetPipelineState(VkPipeline pipeline) {
auto it = pipelineMap.find(pipeline);
if (it == pipelineMap.end()) {
return nullptr;
}
return it->second.get();
}
RENDER_PASS_STATE *CoreChecks::GetRenderPassState(VkRenderPass renderpass) {
auto it = renderPassMap.find(renderpass);
if (it == renderPassMap.end()) {
return nullptr;
}
return it->second.get();
}
std::shared_ptr<RENDER_PASS_STATE> CoreChecks::GetRenderPassStateSharedPtr(VkRenderPass renderpass) {
auto it = renderPassMap.find(renderpass);
if (it == renderPassMap.end()) {
return nullptr;
}
return it->second;
}
FRAMEBUFFER_STATE *CoreChecks::GetFramebufferState(VkFramebuffer framebuffer) {
auto it = frameBufferMap.find(framebuffer);
if (it == frameBufferMap.end()) {
return nullptr;
}
return it->second.get();
}
std::shared_ptr<cvdescriptorset::DescriptorSetLayout const> const GetDescriptorSetLayout(CoreChecks const *dev_data,
VkDescriptorSetLayout dsLayout) {
auto it = dev_data->descriptorSetLayoutMap.find(dsLayout);
if (it == dev_data->descriptorSetLayoutMap.end()) {
return nullptr;
}
return it->second;
}
PIPELINE_LAYOUT_STATE const *CoreChecks::GetPipelineLayout(VkPipelineLayout pipeLayout) {
auto it = pipelineLayoutMap.find(pipeLayout);
if (it == pipelineLayoutMap.end()) {
return nullptr;
}
return it->second.get();
}
SHADER_MODULE_STATE const *CoreChecks::GetShaderModuleState(VkShaderModule module) {
auto it = shaderModuleMap.find(module);
if (it == shaderModuleMap.end()) {
return nullptr;
}
return it->second.get();
}
const TEMPLATE_STATE *CoreChecks::GetDescriptorTemplateState(VkDescriptorUpdateTemplateKHR descriptor_update_template) {
const auto it = desc_template_map.find(descriptor_update_template);
if (it == desc_template_map.cend()) {
return nullptr;
}
return it->second.get();
}
// Return true if for a given PSO, the given state enum is dynamic, else return false
static bool IsDynamic(const PIPELINE_STATE *pPipeline, const VkDynamicState state) {
if (pPipeline && pPipeline->graphicsPipelineCI.pDynamicState) {
for (uint32_t i = 0; i < pPipeline->graphicsPipelineCI.pDynamicState->dynamicStateCount; i++) {
if (state == pPipeline->graphicsPipelineCI.pDynamicState->pDynamicStates[i]) return true;
}
}
return false;
}
// Validate state stored as flags at time of draw call
bool CoreChecks::ValidateDrawStateFlags(CMD_BUFFER_STATE *pCB, const PIPELINE_STATE *pPipe, bool indexed, const char *msg_code) {
bool result = false;
if (pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_LIST ||
pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP) {
result |= ValidateStatus(pCB, CBSTATUS_LINE_WIDTH_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Dynamic line width state not set for this command buffer", msg_code);
}
if (pPipe->graphicsPipelineCI.pRasterizationState &&
(pPipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE)) {
result |= ValidateStatus(pCB, CBSTATUS_DEPTH_BIAS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Dynamic depth bias state not set for this command buffer", msg_code);
}
if (pPipe->blendConstantsEnabled) {
result |= ValidateStatus(pCB, CBSTATUS_BLEND_CONSTANTS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Dynamic blend constants state not set for this command buffer", msg_code);
}
if (pPipe->graphicsPipelineCI.pDepthStencilState &&
(pPipe->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE)) {
result |= ValidateStatus(pCB, CBSTATUS_DEPTH_BOUNDS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Dynamic depth bounds state not set for this command buffer", msg_code);
}
if (pPipe->graphicsPipelineCI.pDepthStencilState &&
(pPipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable == VK_TRUE)) {
result |= ValidateStatus(pCB, CBSTATUS_STENCIL_READ_MASK_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Dynamic stencil read mask state not set for this command buffer", msg_code);
result |= ValidateStatus(pCB, CBSTATUS_STENCIL_WRITE_MASK_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Dynamic stencil write mask state not set for this command buffer", msg_code);
result |= ValidateStatus(pCB, CBSTATUS_STENCIL_REFERENCE_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Dynamic stencil reference state not set for this command buffer", msg_code);
}
if (indexed) {
result |= ValidateStatus(pCB, CBSTATUS_INDEX_BUFFER_BOUND, VK_DEBUG_REPORT_ERROR_BIT_EXT,
"Index buffer object not bound to this command buffer when Indexed Draw attempted", msg_code);
}
return result;
}
bool CoreChecks::LogInvalidAttachmentMessage(const char *type1_string, const RENDER_PASS_STATE *rp1_state, const char *type2_string,
const RENDER_PASS_STATE *rp2_state, uint32_t primary_attach, uint32_t secondary_attach,
const char *msg, const char *caller, const char *error_code) {
return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(rp1_state->renderPass), error_code,
"%s: RenderPasses incompatible between %s w/ renderPass %s and %s w/ renderPass %s Attachment %u is not "
"compatible with %u: %s.",
caller, type1_string, report_data->FormatHandle(rp1_state->renderPass).c_str(), type2_string,
report_data->FormatHandle(rp2_state->renderPass).c_str(), primary_attach, secondary_attach, msg);
}
bool CoreChecks::ValidateAttachmentCompatibility(const char *type1_string, const RENDER_PASS_STATE *rp1_state,
const char *type2_string, const RENDER_PASS_STATE *rp2_state,
uint32_t primary_attach, uint32_t secondary_attach, const char *caller,
const char *error_code) {
bool skip = false;
const auto &primaryPassCI = rp1_state->createInfo;
const auto &secondaryPassCI = rp2_state->createInfo;
if (primaryPassCI.attachmentCount <= primary_attach) {
primary_attach = VK_ATTACHMENT_UNUSED;
}
if (secondaryPassCI.attachmentCount <= secondary_attach) {
secondary_attach = VK_ATTACHMENT_UNUSED;
}
if (primary_attach == VK_ATTACHMENT_UNUSED && secondary_attach == VK_ATTACHMENT_UNUSED) {
return skip;
}
if (primary_attach == VK_ATTACHMENT_UNUSED) {
skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach,
"The first is unused while the second is not.", caller, error_code);
return skip;
}
if (secondary_attach == VK_ATTACHMENT_UNUSED) {
skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach,
"The second is unused while the first is not.", caller, error_code);
return skip;
}
if (primaryPassCI.pAttachments[primary_attach].format != secondaryPassCI.pAttachments[secondary_attach].format) {
skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach,
"They have different formats.", caller, error_code);
}
if (primaryPassCI.pAttachments[primary_attach].samples != secondaryPassCI.pAttachments[secondary_attach].samples) {
skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach,
"They have different samples.", caller, error_code);
}
if (primaryPassCI.pAttachments[primary_attach].flags != secondaryPassCI.pAttachments[secondary_attach].flags) {
skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach,
"They have different flags.", caller, error_code);
}
return skip;
}
bool CoreChecks::ValidateSubpassCompatibility(const char *type1_string, const RENDER_PASS_STATE *rp1_state,
const char *type2_string, const RENDER_PASS_STATE *rp2_state, const int subpass,
const char *caller, const char *error_code) {
bool skip = false;
const auto &primary_desc = rp1_state->createInfo.pSubpasses[subpass];
const auto &secondary_desc = rp2_state->createInfo.pSubpasses[subpass];
uint32_t maxInputAttachmentCount = std::max(primary_desc.inputAttachmentCount, secondary_desc.inputAttachmentCount);
for (uint32_t i = 0; i < maxInputAttachmentCount; ++i) {
uint32_t primary_input_attach = VK_ATTACHMENT_UNUSED, secondary_input_attach = VK_ATTACHMENT_UNUSED;
if (i < primary_desc.inputAttachmentCount) {
primary_input_attach = primary_desc.pInputAttachments[i].attachment;
}
if (i < secondary_desc.inputAttachmentCount) {
secondary_input_attach = secondary_desc.pInputAttachments[i].attachment;
}
skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_input_attach,
secondary_input_attach, caller, error_code);
}
uint32_t maxColorAttachmentCount = std::max(primary_desc.colorAttachmentCount, secondary_desc.colorAttachmentCount);
for (uint32_t i = 0; i < maxColorAttachmentCount; ++i) {
uint32_t primary_color_attach = VK_ATTACHMENT_UNUSED, secondary_color_attach = VK_ATTACHMENT_UNUSED;
if (i < primary_desc.colorAttachmentCount) {
primary_color_attach = primary_desc.pColorAttachments[i].attachment;
}
if (i < secondary_desc.colorAttachmentCount) {
secondary_color_attach = secondary_desc.pColorAttachments[i].attachment;
}
skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_color_attach,
secondary_color_attach, caller, error_code);
if (rp1_state->createInfo.subpassCount > 1) {
uint32_t primary_resolve_attach = VK_ATTACHMENT_UNUSED, secondary_resolve_attach = VK_ATTACHMENT_UNUSED;
if (i < primary_desc.colorAttachmentCount && primary_desc.pResolveAttachments) {
primary_resolve_attach = primary_desc.pResolveAttachments[i].attachment;
}
if (i < secondary_desc.colorAttachmentCount && secondary_desc.pResolveAttachments) {
secondary_resolve_attach = secondary_desc.pResolveAttachments[i].attachment;
}
skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_resolve_attach,
secondary_resolve_attach, caller, error_code);
}
}
uint32_t primary_depthstencil_attach = VK_ATTACHMENT_UNUSED, secondary_depthstencil_attach = VK_ATTACHMENT_UNUSED;
if (primary_desc.pDepthStencilAttachment) {
primary_depthstencil_attach = primary_desc.pDepthStencilAttachment[0].attachment;
}
if (secondary_desc.pDepthStencilAttachment) {
secondary_depthstencil_attach = secondary_desc.pDepthStencilAttachment[0].attachment;
}
skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_depthstencil_attach,
secondary_depthstencil_attach, caller, error_code);
return skip;
}
// Verify that given renderPass CreateInfo for primary and secondary command buffers are compatible.
// This function deals directly with the CreateInfo, there are overloaded versions below that can take the renderPass handle and
// will then feed into this function
bool CoreChecks::ValidateRenderPassCompatibility(const char *type1_string, const RENDER_PASS_STATE *rp1_state,
const char *type2_string, const RENDER_PASS_STATE *rp2_state, const char *caller,
const char *error_code) {
bool skip = false;
if (rp1_state->createInfo.subpassCount != rp2_state->createInfo.subpassCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(rp1_state->renderPass), error_code,
"%s: RenderPasses incompatible between %s w/ renderPass %s with a subpassCount of %u and %s w/ renderPass "
"%s with a subpassCount of %u.",
caller, type1_string, report_data->FormatHandle(rp1_state->renderPass).c_str(),
rp1_state->createInfo.subpassCount, type2_string, report_data->FormatHandle(rp2_state->renderPass).c_str(),
rp2_state->createInfo.subpassCount);
} else {
for (uint32_t i = 0; i < rp1_state->createInfo.subpassCount; ++i) {
skip |= ValidateSubpassCompatibility(type1_string, rp1_state, type2_string, rp2_state, i, caller, error_code);
}
}
return skip;
}
// Return Set node ptr for specified set or else NULL
cvdescriptorset::DescriptorSet *CoreChecks::GetSetNode(VkDescriptorSet set) {
auto set_it = setMap.find(set);
if (set_it == setMap.end()) {
return NULL;
}
return set_it->second.get();
}
// For given pipeline, return number of MSAA samples, or one if MSAA disabled
static VkSampleCountFlagBits GetNumSamples(PIPELINE_STATE const *pipe) {
if (pipe->graphicsPipelineCI.pMultisampleState != NULL &&
VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO == pipe->graphicsPipelineCI.pMultisampleState->sType) {
return pipe->graphicsPipelineCI.pMultisampleState->rasterizationSamples;
}
return VK_SAMPLE_COUNT_1_BIT;
}
static void ListBits(std::ostream &s, uint32_t bits) {
for (int i = 0; i < 32 && bits; i++) {
if (bits & (1 << i)) {
s << i;
bits &= ~(1 << i);
if (bits) {
s << ",";
}
}
}
}
// Validate draw-time state related to the PSO
bool CoreChecks::ValidatePipelineDrawtimeState(LAST_BOUND_STATE const &state, const CMD_BUFFER_STATE *pCB, CMD_TYPE cmd_type,
PIPELINE_STATE const *pPipeline, const char *caller) {
bool skip = false;
// Verify vertex binding
if (pPipeline->vertex_binding_descriptions_.size() > 0) {
for (size_t i = 0; i < pPipeline->vertex_binding_descriptions_.size(); i++) {
const auto vertex_binding = pPipeline->vertex_binding_descriptions_[i].binding;
if ((pCB->current_draw_data.vertex_buffer_bindings.size() < (vertex_binding + 1)) ||
(pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer == VK_NULL_HANDLE)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_VtxIndexOutOfBounds,
"The Pipeline State Object (%s) expects that this Command Buffer's vertex binding Index %u should be set via "
"vkCmdBindVertexBuffers. This is because VkVertexInputBindingDescription struct at "
"index " PRINTF_SIZE_T_SPECIFIER " of pVertexBindingDescriptions has a binding value of %u.",
report_data->FormatHandle(state.pipeline_state->pipeline).c_str(), vertex_binding, i, vertex_binding);
}
}
// Verify vertex attribute address alignment
for (size_t i = 0; i < pPipeline->vertex_attribute_descriptions_.size(); i++) {
const auto &attribute_description = pPipeline->vertex_attribute_descriptions_[i];
const auto vertex_binding = attribute_description.binding;
const auto attribute_offset = attribute_description.offset;
const auto attribute_format = attribute_description.format;
const auto &vertex_binding_map_it = pPipeline->vertex_binding_to_index_map_.find(vertex_binding);
if ((vertex_binding_map_it != pPipeline->vertex_binding_to_index_map_.cend()) &&
(vertex_binding < pCB->current_draw_data.vertex_buffer_bindings.size()) &&
(pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer != VK_NULL_HANDLE)) {
const auto vertex_buffer_stride = pPipeline->vertex_binding_descriptions_[vertex_binding_map_it->second].stride;
const auto vertex_buffer_offset = pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].offset;
const auto buffer_state = GetBufferState(pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer);
// Use only memory binding offset as base memory should be properly aligned by the driver
const auto buffer_binding_address = buffer_state->binding.offset + vertex_buffer_offset;
// Use 1 as vertex/instance index to use buffer stride as well
const auto attrib_address = buffer_binding_address + vertex_buffer_stride + attribute_offset;
uint32_t vtx_attrib_req_alignment = FormatElementSize(attribute_format);
if (FormatElementIsTexel(attribute_format)) {
vtx_attrib_req_alignment /= FormatChannelCount(attribute_format);
}
if (SafeModulo(attrib_address, vtx_attrib_req_alignment) != 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
HandleToUint64(pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer),
kVUID_Core_DrawState_InvalidVtxAttributeAlignment,
"Invalid attribAddress alignment for vertex attribute " PRINTF_SIZE_T_SPECIFIER
" from pipeline (%s) and vertex buffer (%s).",
i, report_data->FormatHandle(state.pipeline_state->pipeline).c_str(),
report_data->FormatHandle(pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer).c_str());
}
}
}
} else {
if ((!pCB->current_draw_data.vertex_buffer_bindings.empty()) && (!pCB->vertex_buffer_used)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_VtxIndexOutOfBounds,
"Vertex buffers are bound to command buffer (%s) but no vertex buffers are attached to this Pipeline "
"State Object (%s).",
report_data->FormatHandle(pCB->commandBuffer).c_str(),
report_data->FormatHandle(state.pipeline_state->pipeline).c_str());
}
}
// If Viewport or scissors are dynamic, verify that dynamic count matches PSO count.
// Skip check if rasterization is disabled or there is no viewport.
if ((!pPipeline->graphicsPipelineCI.pRasterizationState ||
(pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) &&
pPipeline->graphicsPipelineCI.pViewportState) {
bool dynViewport = IsDynamic(pPipeline, VK_DYNAMIC_STATE_VIEWPORT);
bool dynScissor = IsDynamic(pPipeline, VK_DYNAMIC_STATE_SCISSOR);
if (dynViewport) {
const auto requiredViewportsMask = (1 << pPipeline->graphicsPipelineCI.pViewportState->viewportCount) - 1;
const auto missingViewportMask = ~pCB->viewportMask & requiredViewportsMask;
if (missingViewportMask) {
std::stringstream ss;
ss << "Dynamic viewport(s) ";
ListBits(ss, missingViewportMask);
ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetViewport().";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_ViewportScissorMismatch, "%s", ss.str().c_str());
}
}
if (dynScissor) {
const auto requiredScissorMask = (1 << pPipeline->graphicsPipelineCI.pViewportState->scissorCount) - 1;
const auto missingScissorMask = ~pCB->scissorMask & requiredScissorMask;
if (missingScissorMask) {
std::stringstream ss;
ss << "Dynamic scissor(s) ";
ListBits(ss, missingScissorMask);
ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetScissor().";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_ViewportScissorMismatch, "%s", ss.str().c_str());
}
}
}
// Verify that any MSAA request in PSO matches sample# in bound FB
// Skip the check if rasterization is disabled.
if (!pPipeline->graphicsPipelineCI.pRasterizationState ||
(pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) {
VkSampleCountFlagBits pso_num_samples = GetNumSamples(pPipeline);
if (pCB->activeRenderPass) {
const auto render_pass_info = pCB->activeRenderPass->createInfo.ptr();
const VkSubpassDescription2KHR *subpass_desc = &render_pass_info->pSubpasses[pCB->activeSubpass];
uint32_t i;
unsigned subpass_num_samples = 0;
for (i = 0; i < subpass_desc->colorAttachmentCount; i++) {
const auto attachment = subpass_desc->pColorAttachments[i].attachment;
if (attachment != VK_ATTACHMENT_UNUSED)
subpass_num_samples |= (unsigned)render_pass_info->pAttachments[attachment].samples;
}
if (subpass_desc->pDepthStencilAttachment &&
subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
const auto attachment = subpass_desc->pDepthStencilAttachment->attachment;
subpass_num_samples |= (unsigned)render_pass_info->pAttachments[attachment].samples;
}
if (!(device_extensions.vk_amd_mixed_attachment_samples || device_extensions.vk_nv_framebuffer_mixed_samples) &&
((subpass_num_samples & static_cast<unsigned>(pso_num_samples)) != subpass_num_samples)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_NumSamplesMismatch,
"Num samples mismatch! At draw-time in Pipeline (%s) with %u samples while current RenderPass (%s) w/ "
"%u samples!",
report_data->FormatHandle(pPipeline->pipeline).c_str(), pso_num_samples,
report_data->FormatHandle(pCB->activeRenderPass->renderPass).c_str(), subpass_num_samples);
}
} else {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_NoActiveRenderpass,
"No active render pass found at draw-time in Pipeline (%s)!",
report_data->FormatHandle(pPipeline->pipeline).c_str());
}
}
// Verify that PSO creation renderPass is compatible with active renderPass
if (pCB->activeRenderPass) {
// TODO: Move all of the error codes common across different Draws into a LUT accessed by cmd_type
// TODO: AMD extension codes are included here, but actual function entrypoints are not yet intercepted
// Error codes for renderpass and subpass mismatches
auto rp_error = "VUID-vkCmdDraw-renderPass-02684", sp_error = "VUID-vkCmdDraw-subpass-02685";
switch (cmd_type) {
case CMD_DRAWINDEXED:
rp_error = "VUID-vkCmdDrawIndexed-renderPass-02684";
sp_error = "VUID-vkCmdDrawIndexed-subpass-02685";
break;
case CMD_DRAWINDIRECT:
rp_error = "VUID-vkCmdDrawIndirect-renderPass-02684";
sp_error = "VUID-vkCmdDrawIndirect-subpass-02685";
break;
case CMD_DRAWINDIRECTCOUNTKHR:
rp_error = "VUID-vkCmdDrawIndirectCountKHR-renderPass-02684";
sp_error = "VUID-vkCmdDrawIndirectCountKHR-subpass-02685";
break;
case CMD_DRAWINDEXEDINDIRECT:
rp_error = "VUID-vkCmdDrawIndexedIndirect-renderPass-02684";
sp_error = "VUID-vkCmdDrawIndexedIndirect-subpass-02685";
break;
case CMD_DRAWINDEXEDINDIRECTCOUNTKHR:
rp_error = "VUID-vkCmdDrawIndexedIndirectCountKHR-renderPass-02684";
sp_error = "VUID-vkCmdDrawIndexedIndirectCountKHR-subpass-02685";
break;
case CMD_DRAWMESHTASKSNV:
rp_error = "VUID-vkCmdDrawMeshTasksNV-renderPass-02684";
sp_error = "VUID-vkCmdDrawMeshTasksNV-subpass-02685";
break;
case CMD_DRAWMESHTASKSINDIRECTNV:
rp_error = "VUID-vkCmdDrawMeshTasksIndirectNV-renderPass-02684";
sp_error = "VUID-vkCmdDrawMeshTasksIndirectNV-subpass-02685";
break;
case CMD_DRAWMESHTASKSINDIRECTCOUNTNV:
rp_error = "VUID-vkCmdDrawMeshTasksIndirectCountNV-renderPass-02684";
sp_error = "VUID-vkCmdDrawMeshTasksIndirectCountNV-subpass-02685";
break;
default:
assert(CMD_DRAW == cmd_type);
break;
}
if (pCB->activeRenderPass->renderPass != pPipeline->rp_state->renderPass) {
// renderPass that PSO was created with must be compatible with active renderPass that PSO is being used with
skip |= ValidateRenderPassCompatibility("active render pass", pCB->activeRenderPass, "pipeline state object",
pPipeline->rp_state.get(), caller, rp_error);
}
if (pPipeline->graphicsPipelineCI.subpass != pCB->activeSubpass) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pPipeline->pipeline), sp_error, "Pipeline was built for subpass %u but used in subpass %u.",
pPipeline->graphicsPipelineCI.subpass, pCB->activeSubpass);
}
}
return skip;
}
// For given cvdescriptorset::DescriptorSet, verify that its Set is compatible w/ the setLayout corresponding to
// pipelineLayout[layoutIndex]
static bool VerifySetLayoutCompatibility(const cvdescriptorset::DescriptorSet *descriptor_set,
PIPELINE_LAYOUT_STATE const *pipeline_layout, const uint32_t layoutIndex,
string &errorMsg) {
auto num_sets = pipeline_layout->set_layouts.size();
if (layoutIndex >= num_sets) {
stringstream errorStr;
errorStr << "VkPipelineLayout (" << pipeline_layout->layout << ") only contains " << num_sets
<< " setLayouts corresponding to sets 0-" << num_sets - 1 << ", but you're attempting to bind set to index "
<< layoutIndex;
errorMsg = errorStr.str();
return false;
}
if (descriptor_set->IsPushDescriptor()) return true;
auto layout_node = pipeline_layout->set_layouts[layoutIndex];
return descriptor_set->IsCompatible(layout_node.get(), &errorMsg);
}
// Validate overall state at the time of a draw call
bool CoreChecks::ValidateCmdBufDrawState(CMD_BUFFER_STATE *cb_node, CMD_TYPE cmd_type, const bool indexed,
const VkPipelineBindPoint bind_point, const char *function, const char *pipe_err_code,
const char *state_err_code) {
bool result = false;
auto const &state = cb_node->lastBound[bind_point];
PIPELINE_STATE *pPipe = state.pipeline_state;
if (nullptr == pPipe) {
return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_node->commandBuffer), pipe_err_code,
"Must not call %s on this command buffer while there is no %s pipeline bound.", function,
bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS ? "Graphics" : "Compute");
}
// First check flag states
if (VK_PIPELINE_BIND_POINT_GRAPHICS == bind_point) result = ValidateDrawStateFlags(cb_node, pPipe, indexed, state_err_code);
// Now complete other state checks
string errorString;
auto const &pipeline_layout = pPipe->pipeline_layout;
for (const auto &set_binding_pair : pPipe->active_slots) {
uint32_t setIndex = set_binding_pair.first;
// If valid set is not bound throw an error
if ((state.boundDescriptorSets.size() <= setIndex) || (!state.boundDescriptorSets[setIndex])) {
result |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_DescriptorSetNotBound,
"VkPipeline %s uses set #%u but that set is not bound.",
report_data->FormatHandle(pPipe->pipeline).c_str(), setIndex);
} else if (!VerifySetLayoutCompatibility(state.boundDescriptorSets[setIndex], &pipeline_layout, setIndex, errorString)) {
// Set is bound but not compatible w/ overlapping pipeline_layout from PSO
VkDescriptorSet setHandle = state.boundDescriptorSets[setIndex]->GetSet();
result |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
HandleToUint64(setHandle), kVUID_Core_DrawState_PipelineLayoutsIncompatible,
"VkDescriptorSet (%s) bound as set #%u is not compatible with overlapping VkPipelineLayout %s due to: %s",
report_data->FormatHandle(setHandle).c_str(), setIndex,
report_data->FormatHandle(pipeline_layout.layout).c_str(), errorString.c_str());
} else { // Valid set is bound and layout compatible, validate that it's updated
// Pull the set node
cvdescriptorset::DescriptorSet *descriptor_set = state.boundDescriptorSets[setIndex];
// Validate the draw-time state for this descriptor set
std::string err_str;
if (!descriptor_set->IsPushDescriptor()) {
// For the "bindless" style resource usage with many descriptors, need to optimize command <-> descriptor
// binding validation. Take the requested binding set and prefilter it to eliminate redundant validation checks.
// Here, the currently bound pipeline determines whether an image validation check is redundant...
// for images are the "req" portion of the binding_req is indirectly (but tightly) coupled to the pipeline.
const cvdescriptorset::PrefilterBindRequestMap reduced_map(*descriptor_set, set_binding_pair.second, cb_node,
pPipe);
const auto &binding_req_map = reduced_map.Map();
if (!descriptor_set->ValidateDrawState(binding_req_map, state.dynamicOffsets[setIndex], cb_node, function,
&err_str)) {
auto set = descriptor_set->GetSet();
result |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
HandleToUint64(set), kVUID_Core_DrawState_DescriptorSetNotUpdated,
"Descriptor set %s bound as set #%u encountered the following validation error at %s time: %s",
report_data->FormatHandle(set).c_str(), setIndex, function, err_str.c_str());
}
}
}
}
// Check general pipeline state that needs to be validated at drawtime
if (VK_PIPELINE_BIND_POINT_GRAPHICS == bind_point)
result |= ValidatePipelineDrawtimeState(state, cb_node, cmd_type, pPipe, function);
return result;
}
void CoreChecks::UpdateDrawState(CMD_BUFFER_STATE *cb_state, const VkPipelineBindPoint bind_point) {
auto const &state = cb_state->lastBound[bind_point];
PIPELINE_STATE *pPipe = state.pipeline_state;
if (VK_NULL_HANDLE != state.pipeline_layout) {
for (const auto &set_binding_pair : pPipe->active_slots) {
uint32_t setIndex = set_binding_pair.first;
// Pull the set node
cvdescriptorset::DescriptorSet *descriptor_set = state.boundDescriptorSets[setIndex];
if (!descriptor_set->IsPushDescriptor()) {
// For the "bindless" style resource usage with many descriptors, need to optimize command <-> descriptor binding
const cvdescriptorset::PrefilterBindRequestMap reduced_map(*descriptor_set, set_binding_pair.second, cb_state);
const auto &binding_req_map = reduced_map.Map();
// Bind this set and its active descriptor resources to the command buffer
descriptor_set->UpdateDrawState(this, cb_state, binding_req_map);
// For given active slots record updated images & buffers
descriptor_set->GetStorageUpdates(binding_req_map, &cb_state->updateBuffers, &cb_state->updateImages);
}
}
}
if (!pPipe->vertex_binding_descriptions_.empty()) {
cb_state->vertex_buffer_used = true;
}
}
bool CoreChecks::ValidatePipelineLocked(std::vector<std::unique_ptr<PIPELINE_STATE>> const &pPipelines, int pipelineIndex) {
bool skip = false;
PIPELINE_STATE *pPipeline = pPipelines[pipelineIndex].get();
// If create derivative bit is set, check that we've specified a base
// pipeline correctly, and that the base pipeline was created to allow
// derivatives.
if (pPipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) {
PIPELINE_STATE *pBasePipeline = nullptr;
if (!((pPipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) ^
(pPipeline->graphicsPipelineCI.basePipelineIndex != -1))) {
// This check is a superset of "VUID-VkGraphicsPipelineCreateInfo-flags-00724" and
// "VUID-VkGraphicsPipelineCreateInfo-flags-00725"
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), kVUID_Core_DrawState_InvalidPipelineCreateState,
"Invalid Pipeline CreateInfo: exactly one of base pipeline index and handle must be specified");
} else if (pPipeline->graphicsPipelineCI.basePipelineIndex != -1) {
if (pPipeline->graphicsPipelineCI.basePipelineIndex >= pipelineIndex) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-vkCreateGraphicsPipelines-flags-00720",
"Invalid Pipeline CreateInfo: base pipeline must occur earlier in array than derivative pipeline.");
} else {
pBasePipeline = pPipelines[pPipeline->graphicsPipelineCI.basePipelineIndex].get();
}
} else if (pPipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) {
pBasePipeline = GetPipelineState(pPipeline->graphicsPipelineCI.basePipelineHandle);
}
if (pBasePipeline && !(pBasePipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), kVUID_Core_DrawState_InvalidPipelineCreateState,
"Invalid Pipeline CreateInfo: base pipeline does not allow derivatives.");
}
}
return skip;
}
// UNLOCKED pipeline validation. DO NOT lookup objects in the CoreChecks->* maps in this function.
bool CoreChecks::ValidatePipelineUnlocked(std::vector<std::unique_ptr<PIPELINE_STATE>> const &pPipelines, int pipelineIndex) {
bool skip = false;
PIPELINE_STATE *pPipeline = pPipelines[pipelineIndex].get();
// Ensure the subpass index is valid. If not, then ValidateAndCapturePipelineShaderState
// produces nonsense errors that confuse users. Other layers should already
// emit errors for renderpass being invalid.
auto subpass_desc = &pPipeline->rp_state->createInfo.pSubpasses[pPipeline->graphicsPipelineCI.subpass];
if (pPipeline->graphicsPipelineCI.subpass >= pPipeline->rp_state->createInfo.subpassCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-subpass-00759",
"Invalid Pipeline CreateInfo State: Subpass index %u is out of range for this renderpass (0..%u).",
pPipeline->graphicsPipelineCI.subpass, pPipeline->rp_state->createInfo.subpassCount - 1);
subpass_desc = nullptr;
}
if (pPipeline->graphicsPipelineCI.pColorBlendState != NULL) {
const safe_VkPipelineColorBlendStateCreateInfo *color_blend_state = pPipeline->graphicsPipelineCI.pColorBlendState;
if (color_blend_state->attachmentCount != subpass_desc->colorAttachmentCount) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-attachmentCount-00746",
"vkCreateGraphicsPipelines(): Render pass (%s) subpass %u has colorAttachmentCount of %u which doesn't "
"match the pColorBlendState->attachmentCount of %u.",
report_data->FormatHandle(pPipeline->rp_state->renderPass).c_str(), pPipeline->graphicsPipelineCI.subpass,
subpass_desc->colorAttachmentCount, color_blend_state->attachmentCount);
}
if (!enabled_features.core.independentBlend) {
if (pPipeline->attachments.size() > 1) {
VkPipelineColorBlendAttachmentState *pAttachments = &pPipeline->attachments[0];
for (size_t i = 1; i < pPipeline->attachments.size(); i++) {
// Quoting the spec: "If [the independent blend] feature is not enabled, the VkPipelineColorBlendAttachmentState
// settings for all color attachments must be identical." VkPipelineColorBlendAttachmentState contains
// only attachment state, so memcmp is best suited for the comparison
if (memcmp(static_cast<const void *>(pAttachments), static_cast<const void *>(&pAttachments[i]),
sizeof(pAttachments[0]))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineColorBlendStateCreateInfo-pAttachments-00605",
"Invalid Pipeline CreateInfo: If independent blend feature not enabled, all elements of "
"pAttachments must be identical.");
break;
}
}
}
}
if (!enabled_features.core.logicOp && (pPipeline->graphicsPipelineCI.pColorBlendState->logicOpEnable != VK_FALSE)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkPipelineColorBlendStateCreateInfo-logicOpEnable-00606",
"Invalid Pipeline CreateInfo: If logic operations feature not enabled, logicOpEnable must be VK_FALSE.");
}
for (size_t i = 0; i < pPipeline->attachments.size(); i++) {
if ((pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) ||
(pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) ||
(pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) ||
(pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) {
if (!enabled_features.core.dualSrcBlend) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineColorBlendAttachmentState-srcColorBlendFactor-00608",
"vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER
"].srcColorBlendFactor uses a dual-source blend factor (%d), but this device feature is not "
"enabled.",
pipelineIndex, i, pPipeline->attachments[i].srcColorBlendFactor);
}
}
if ((pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) ||
(pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) ||
(pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) ||
(pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) {
if (!enabled_features.core.dualSrcBlend) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineColorBlendAttachmentState-dstColorBlendFactor-00609",
"vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER
"].dstColorBlendFactor uses a dual-source blend factor (%d), but this device feature is not "
"enabled.",
pipelineIndex, i, pPipeline->attachments[i].dstColorBlendFactor);
}
}
if ((pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) ||
(pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) ||
(pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) ||
(pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) {
if (!enabled_features.core.dualSrcBlend) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineColorBlendAttachmentState-srcAlphaBlendFactor-00610",
"vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER
"].srcAlphaBlendFactor uses a dual-source blend factor (%d), but this device feature is not "
"enabled.",
pipelineIndex, i, pPipeline->attachments[i].srcAlphaBlendFactor);
}
}
if ((pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) ||
(pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) ||
(pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) ||
(pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) {
if (!enabled_features.core.dualSrcBlend) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineColorBlendAttachmentState-dstAlphaBlendFactor-00611",
"vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER
"].dstAlphaBlendFactor uses a dual-source blend factor (%d), but this device feature is not "
"enabled.",
pipelineIndex, i, pPipeline->attachments[i].dstAlphaBlendFactor);
}
}
}
}
if (ValidateAndCapturePipelineShaderState(pPipeline)) {
skip = true;
}
// Each shader's stage must be unique
if (pPipeline->duplicate_shaders) {
for (uint32_t stage = VK_SHADER_STAGE_VERTEX_BIT; stage & VK_SHADER_STAGE_ALL_GRAPHICS; stage <<= 1) {
if (pPipeline->duplicate_shaders & stage) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), kVUID_Core_DrawState_InvalidPipelineCreateState,
"Invalid Pipeline CreateInfo State: Multiple shaders provided for stage %s",
string_VkShaderStageFlagBits(VkShaderStageFlagBits(stage)));
}
}
}
if (device_extensions.vk_nv_mesh_shader) {
// VS or mesh is required
if (!(pPipeline->active_shaders & (VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_MESH_BIT_NV))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-stage-02096",
"Invalid Pipeline CreateInfo State: Vertex Shader or Mesh Shader required.");
}
// Can't mix mesh and VTG
if ((pPipeline->active_shaders & (VK_SHADER_STAGE_MESH_BIT_NV | VK_SHADER_STAGE_TASK_BIT_NV)) &&
(pPipeline->active_shaders &
(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT |
VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-pStages-02095",
"Invalid Pipeline CreateInfo State: Geometric shader stages must either be all mesh (mesh | task) "
"or all VTG (vertex, tess control, tess eval, geom).");
}
} else {
// VS is required
if (!(pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-stage-00727",
"Invalid Pipeline CreateInfo State: Vertex Shader required.");
}
}
if (!enabled_features.mesh_shader.meshShader && (pPipeline->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkPipelineShaderStageCreateInfo-stage-02091",
"Invalid Pipeline CreateInfo State: Mesh Shader not supported.");
}
if (!enabled_features.mesh_shader.taskShader && (pPipeline->active_shaders & VK_SHADER_STAGE_TASK_BIT_NV)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkPipelineShaderStageCreateInfo-stage-02092",
"Invalid Pipeline CreateInfo State: Task Shader not supported.");
}
// Either both or neither TC/TE shaders should be defined
bool has_control = (pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) != 0;
bool has_eval = (pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) != 0;
if (has_control && !has_eval) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-pStages-00729",
"Invalid Pipeline CreateInfo State: TE and TC shaders must be included or excluded as a pair.");
}
if (!has_control && has_eval) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-pStages-00730",
"Invalid Pipeline CreateInfo State: TE and TC shaders must be included or excluded as a pair.");
}
// Compute shaders should be specified independent of Gfx shaders
if (pPipeline->active_shaders & VK_SHADER_STAGE_COMPUTE_BIT) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-stage-00728",
"Invalid Pipeline CreateInfo State: Do not specify Compute Shader for Gfx Pipeline.");
}
if ((pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT) && !pPipeline->graphicsPipelineCI.pInputAssemblyState) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-pStages-02098",
"Invalid Pipeline CreateInfo State: Missing pInputAssemblyState.");
}
// VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive topology is only valid for tessellation pipelines.
// Mismatching primitive topology and tessellation fails graphics pipeline creation.
if (has_control && has_eval &&
(!pPipeline->graphicsPipelineCI.pInputAssemblyState ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology != VK_PRIMITIVE_TOPOLOGY_PATCH_LIST)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-pStages-00736",
"Invalid Pipeline CreateInfo State: VK_PRIMITIVE_TOPOLOGY_PATCH_LIST must be set as IA topology for "
"tessellation pipelines.");
}
if (pPipeline->graphicsPipelineCI.pInputAssemblyState) {
if (pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST) {
if (!has_control || !has_eval) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-topology-00737",
"Invalid Pipeline CreateInfo State: VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive topology is only valid "
"for tessellation pipelines.");
}
}
if ((pPipeline->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE) &&
(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineInputAssemblyStateCreateInfo-topology-00428",
"topology is %s and primitiveRestartEnable is VK_TRUE. It is invalid.",
string_VkPrimitiveTopology(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology));
}
if ((enabled_features.core.geometryShader == VK_FALSE) &&
(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY ||
pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineInputAssemblyStateCreateInfo-topology-00429",
"topology is %s and geometry shaders feature is not enabled. It is invalid.",
string_VkPrimitiveTopology(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology));
}
if ((enabled_features.core.tessellationShader == VK_FALSE) &&
(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineInputAssemblyStateCreateInfo-topology-00430",
"topology is %s and tessellation shaders feature is not enabled. It is invalid.",
string_VkPrimitiveTopology(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology));
}
}
// If a rasterization state is provided...
if (pPipeline->graphicsPipelineCI.pRasterizationState) {
if ((pPipeline->graphicsPipelineCI.pRasterizationState->depthClampEnable == VK_TRUE) &&
(!enabled_features.core.depthClamp)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineRasterizationStateCreateInfo-depthClampEnable-00782",
"vkCreateGraphicsPipelines(): the depthClamp device feature is disabled: the depthClampEnable member "
"of the VkPipelineRasterizationStateCreateInfo structure must be set to VK_FALSE.");
}
if (!IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_BIAS) &&
(pPipeline->graphicsPipelineCI.pRasterizationState->depthBiasClamp != 0.0) && (!enabled_features.core.depthBiasClamp)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), kVUID_Core_DrawState_InvalidFeature,
"vkCreateGraphicsPipelines(): the depthBiasClamp device feature is disabled: the depthBiasClamp member "
"of the VkPipelineRasterizationStateCreateInfo structure must be set to 0.0 unless the "
"VK_DYNAMIC_STATE_DEPTH_BIAS dynamic state is enabled");
}
// If rasterization is enabled...
if (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE) {
if ((pPipeline->graphicsPipelineCI.pMultisampleState->alphaToOneEnable == VK_TRUE) &&
(!enabled_features.core.alphaToOne)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineMultisampleStateCreateInfo-alphaToOneEnable-00785",
"vkCreateGraphicsPipelines(): the alphaToOne device feature is disabled: the alphaToOneEnable "
"member of the VkPipelineMultisampleStateCreateInfo structure must be set to VK_FALSE.");
}
// If subpass uses a depth/stencil attachment, pDepthStencilState must be a pointer to a valid structure
if (subpass_desc && subpass_desc->pDepthStencilAttachment &&
subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
if (!pPipeline->graphicsPipelineCI.pDepthStencilState) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00752",
"Invalid Pipeline CreateInfo State: pDepthStencilState is NULL when rasterization is enabled "
"and subpass uses a depth/stencil attachment.");
} else if ((pPipeline->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE) &&
(!enabled_features.core.depthBounds)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineDepthStencilStateCreateInfo-depthBoundsTestEnable-00598",
"vkCreateGraphicsPipelines(): the depthBounds device feature is disabled: the "
"depthBoundsTestEnable member of the VkPipelineDepthStencilStateCreateInfo structure must be "
"set to VK_FALSE.");
}
}
// If subpass uses color attachments, pColorBlendState must be valid pointer
if (subpass_desc) {
uint32_t color_attachment_count = 0;
for (uint32_t i = 0; i < subpass_desc->colorAttachmentCount; ++i) {
if (subpass_desc->pColorAttachments[i].attachment != VK_ATTACHMENT_UNUSED) {
++color_attachment_count;
}
}
if (color_attachment_count > 0 && pPipeline->graphicsPipelineCI.pColorBlendState == nullptr) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00753",
"Invalid Pipeline CreateInfo State: pColorBlendState is NULL when rasterization is enabled and "
"subpass uses color attachments.");
}
}
}
}
if ((pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT) && !pPipeline->graphicsPipelineCI.pVertexInputState) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkGraphicsPipelineCreateInfo-pStages-02097",
"Invalid Pipeline CreateInfo State: Missing pVertexInputState.");
}
auto vi = pPipeline->graphicsPipelineCI.pVertexInputState;
if (vi != NULL) {
for (uint32_t j = 0; j < vi->vertexAttributeDescriptionCount; j++) {
VkFormat format = vi->pVertexAttributeDescriptions[j].format;
// Internal call to get format info. Still goes through layers, could potentially go directly to ICD.
VkFormatProperties properties;
DispatchGetPhysicalDeviceFormatProperties(physical_device, format, &properties);
if ((properties.bufferFeatures & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) == 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkVertexInputAttributeDescription-format-00623",
"vkCreateGraphicsPipelines: pCreateInfo[%d].pVertexInputState->vertexAttributeDescriptions[%d].format "
"(%s) is not a supported vertex buffer format.",
pipelineIndex, j, string_VkFormat(format));
}
}
}
auto accumColorSamples = [subpass_desc, pPipeline](uint32_t &samples) {
for (uint32_t i = 0; i < subpass_desc->colorAttachmentCount; i++) {
const auto attachment = subpass_desc->pColorAttachments[i].attachment;
if (attachment != VK_ATTACHMENT_UNUSED) {
samples |= static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples);
}
}
};
if (!(device_extensions.vk_amd_mixed_attachment_samples || device_extensions.vk_nv_framebuffer_mixed_samples)) {
uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline));
uint32_t subpass_num_samples = 0;
accumColorSamples(subpass_num_samples);
if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
const auto attachment = subpass_desc->pDepthStencilAttachment->attachment;
subpass_num_samples |= static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples);
}
// subpass_num_samples is 0 when the subpass has no attachments or if all attachments are VK_ATTACHMENT_UNUSED.
// Only validate the value of subpass_num_samples if the subpass has attachments that are not VK_ATTACHMENT_UNUSED.
if (subpass_num_samples && (!IsPowerOfTwo(subpass_num_samples) || (subpass_num_samples != raster_samples))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-subpass-00757",
"vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) "
"does not match the number of samples of the RenderPass color and/or depth attachment.",
pipelineIndex, raster_samples);
}
}
if (device_extensions.vk_amd_mixed_attachment_samples) {
VkSampleCountFlagBits max_sample_count = static_cast<VkSampleCountFlagBits>(0);
for (uint32_t i = 0; i < subpass_desc->colorAttachmentCount; ++i) {
if (subpass_desc->pColorAttachments[i].attachment != VK_ATTACHMENT_UNUSED) {
max_sample_count =
std::max(max_sample_count,
pPipeline->rp_state->createInfo.pAttachments[subpass_desc->pColorAttachments[i].attachment].samples);
}
}
if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
max_sample_count =
std::max(max_sample_count,
pPipeline->rp_state->createInfo.pAttachments[subpass_desc->pDepthStencilAttachment->attachment].samples);
}
if ((pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE) &&
(pPipeline->graphicsPipelineCI.pMultisampleState->rasterizationSamples != max_sample_count)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-subpass-01505",
"vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%s) != max "
"attachment samples (%s) used in subpass %u.",
pipelineIndex,
string_VkSampleCountFlagBits(pPipeline->graphicsPipelineCI.pMultisampleState->rasterizationSamples),
string_VkSampleCountFlagBits(max_sample_count), pPipeline->graphicsPipelineCI.subpass);
}
}
if (device_extensions.vk_nv_framebuffer_mixed_samples) {
uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline));
uint32_t subpass_color_samples = 0;
accumColorSamples(subpass_color_samples);
if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
const auto attachment = subpass_desc->pDepthStencilAttachment->attachment;
const uint32_t subpass_depth_samples =
static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples);
if (pPipeline->graphicsPipelineCI.pDepthStencilState) {
const bool ds_test_enabled = (pPipeline->graphicsPipelineCI.pDepthStencilState->depthTestEnable == VK_TRUE) ||
(pPipeline->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE) ||
(pPipeline->graphicsPipelineCI.pDepthStencilState->stencilTestEnable == VK_TRUE);
if (ds_test_enabled && (!IsPowerOfTwo(subpass_depth_samples) || (raster_samples != subpass_depth_samples))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-subpass-01411",
"vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) "
"does not match the number of samples of the RenderPass depth attachment (%u).",
pipelineIndex, raster_samples, subpass_depth_samples);
}
}
}
if (IsPowerOfTwo(subpass_color_samples)) {
if (raster_samples < subpass_color_samples) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkGraphicsPipelineCreateInfo-subpass-01412",
"vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) "
"is not greater or equal to the number of samples of the RenderPass color attachment (%u).",
pipelineIndex, raster_samples, subpass_color_samples);
}
if (pPipeline->graphicsPipelineCI.pMultisampleState) {
if ((raster_samples > subpass_color_samples) &&
(pPipeline->graphicsPipelineCI.pMultisampleState->sampleShadingEnable == VK_TRUE)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkPipelineMultisampleStateCreateInfo-rasterizationSamples-01415",
"vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->sampleShadingEnable must be VK_FALSE when "
"pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) is greater than the number of samples of the "
"subpass color attachment (%u).",
pipelineIndex, pipelineIndex, raster_samples, subpass_color_samples);
}
const auto *coverage_modulation_state = lvl_find_in_chain<VkPipelineCoverageModulationStateCreateInfoNV>(
pPipeline->graphicsPipelineCI.pMultisampleState->pNext);
if (coverage_modulation_state && (coverage_modulation_state->coverageModulationTableEnable == VK_TRUE)) {
if (coverage_modulation_state->coverageModulationTableCount != (raster_samples / subpass_color_samples)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device),
"VUID-VkPipelineCoverageModulationStateCreateInfoNV-coverageModulationTableEnable-01405",
"vkCreateGraphicsPipelines: pCreateInfos[%d] VkPipelineCoverageModulationStateCreateInfoNV "
"coverageModulationTableCount of %u is invalid.",
pipelineIndex, coverage_modulation_state->coverageModulationTableCount);
}
}
}
}
}
if (device_extensions.vk_nv_fragment_coverage_to_color) {
const auto coverage_to_color_state =
lvl_find_in_chain<VkPipelineCoverageToColorStateCreateInfoNV>(pPipeline->graphicsPipelineCI.pMultisampleState);
if (coverage_to_color_state && coverage_to_color_state->coverageToColorEnable == VK_TRUE) {
bool attachment_is_valid = false;
std::string error_detail;
if (coverage_to_color_state->coverageToColorLocation < subpass_desc->colorAttachmentCount) {
const auto color_attachment_ref = subpass_desc->pColorAttachments[coverage_to_color_state->coverageToColorLocation];
if (color_attachment_ref.attachment != VK_ATTACHMENT_UNUSED) {
const auto color_attachment = pPipeline->rp_state->createInfo.pAttachments[color_attachment_ref.attachment];
switch (color_attachment.format) {
case VK_FORMAT_R8_UINT:
case VK_FORMAT_R8_SINT:
case VK_FORMAT_R16_UINT:
case VK_FORMAT_R16_SINT:
case VK_FORMAT_R32_UINT:
case VK_FORMAT_R32_SINT:
attachment_is_valid = true;
break;
default:
string_sprintf(&error_detail, "references an attachment with an invalid format (%s).",
string_VkFormat(color_attachment.format));
break;
}
} else {
string_sprintf(&error_detail,
"references an invalid attachment. The subpass pColorAttachments[%" PRIu32
"].attachment has the value "
"VK_ATTACHMENT_UNUSED.",
coverage_to_color_state->coverageToColorLocation);
}
} else {
string_sprintf(&error_detail,
"references an non-existing attachment since the subpass colorAttachmentCount is %" PRIu32 ".",
subpass_desc->colorAttachmentCount);
}
if (!attachment_is_valid) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkPipelineCoverageToColorStateCreateInfoNV-coverageToColorEnable-01404",
"vkCreateGraphicsPipelines: pCreateInfos[%" PRId32
"].pMultisampleState VkPipelineCoverageToColorStateCreateInfoNV "
"coverageToColorLocation = %" PRIu32 " %s",
pipelineIndex, coverage_to_color_state->coverageToColorLocation, error_detail.c_str());
}
}
}
return skip;
}
// Block of code at start here specifically for managing/tracking DSs
// Return Pool node ptr for specified pool or else NULL
DESCRIPTOR_POOL_STATE *CoreChecks::GetDescriptorPoolState(const VkDescriptorPool pool) {
auto pool_it = descriptorPoolMap.find(pool);
if (pool_it == descriptorPoolMap.end()) {
return NULL;
}
return pool_it->second.get();
}
// Validate that given set is valid and that it's not being used by an in-flight CmdBuffer
// func_str is the name of the calling function
// Return false if no errors occur
// Return true if validation error occurs and callback returns true (to skip upcoming API call down the chain)
bool CoreChecks::ValidateIdleDescriptorSet(VkDescriptorSet set, const char *func_str) {
if (disabled.idle_descriptor_set) return false;
bool skip = false;
auto set_node = setMap.find(set);
if (set_node == setMap.end()) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(set),
kVUID_Core_DrawState_DoubleDestroy, "Cannot call %s() on descriptor set %s that has not been allocated.",
func_str, report_data->FormatHandle(set).c_str());
} else {
// TODO : This covers various error cases so should pass error enum into this function and use passed in enum here
if (set_node->second->in_use.load()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
HandleToUint64(set), "VUID-vkFreeDescriptorSets-pDescriptorSets-00309",
"Cannot call %s() on descriptor set %s that is in use by a command buffer.", func_str,
report_data->FormatHandle(set).c_str());
}
}
return skip;
}
// Remove set from setMap and delete the set
void CoreChecks::FreeDescriptorSet(cvdescriptorset::DescriptorSet *descriptor_set) { setMap.erase(descriptor_set->GetSet()); }
// Free all DS Pools including their Sets & related sub-structs
// NOTE : Calls to this function should be wrapped in mutex
void CoreChecks::DeletePools() {
for (auto ii = descriptorPoolMap.begin(); ii != descriptorPoolMap.end();) {
// Remove this pools' sets from setMap and delete them
for (auto ds : ii->second->sets) {
FreeDescriptorSet(ds);
}
ii->second->sets.clear();
ii = descriptorPoolMap.erase(ii);
}
}
// For given CB object, fetch associated CB Node from map
CMD_BUFFER_STATE *CoreChecks::GetCBState(const VkCommandBuffer cb) {
auto it = commandBufferMap.find(cb);
if (it == commandBufferMap.end()) {
return NULL;
}
return it->second.get();
}
// If a renderpass is active, verify that the given command type is appropriate for current subpass state
bool CoreChecks::ValidateCmdSubpassState(const CMD_BUFFER_STATE *pCB, const CMD_TYPE cmd_type) {
if (!pCB->activeRenderPass) return false;
bool skip = false;
if (pCB->activeSubpassContents == VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS &&
(cmd_type != CMD_EXECUTECOMMANDS && cmd_type != CMD_NEXTSUBPASS && cmd_type != CMD_ENDRENDERPASS &&
cmd_type != CMD_NEXTSUBPASS2KHR && cmd_type != CMD_ENDRENDERPASS2KHR)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidCommandBuffer,
"Commands cannot be called in a subpass using secondary command buffers.");
} else if (pCB->activeSubpassContents == VK_SUBPASS_CONTENTS_INLINE && cmd_type == CMD_EXECUTECOMMANDS) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidCommandBuffer,
"vkCmdExecuteCommands() cannot be called in a subpass using inline commands.");
}
return skip;
}
bool CoreChecks::ValidateCmdQueueFlags(const CMD_BUFFER_STATE *cb_node, const char *caller_name, VkQueueFlags required_flags,
const char *error_code) {
auto pool = GetCommandPoolState(cb_node->createInfo.commandPool);
if (pool) {
VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[pool->queueFamilyIndex].queueFlags;
if (!(required_flags & queue_flags)) {
string required_flags_string;
for (auto flag : {VK_QUEUE_TRANSFER_BIT, VK_QUEUE_GRAPHICS_BIT, VK_QUEUE_COMPUTE_BIT}) {
if (flag & required_flags) {
if (required_flags_string.size()) {
required_flags_string += " or ";
}
required_flags_string += string_VkQueueFlagBits(flag);
}
}
return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_node->commandBuffer), error_code,
"Cannot call %s on a command buffer allocated from a pool without %s capabilities..", caller_name,
required_flags_string.c_str());
}
}
return false;
}
static char const *GetCauseStr(VK_OBJECT obj) {
if (obj.type == kVulkanObjectTypeDescriptorSet) return "destroyed or updated";
if (obj.type == kVulkanObjectTypeCommandBuffer) return "destroyed or rerecorded";
return "destroyed";
}
bool CoreChecks::ReportInvalidCommandBuffer(const CMD_BUFFER_STATE *cb_state, const char *call_source) {
bool skip = false;
for (auto obj : cb_state->broken_bindings) {
const char *type_str = object_string[obj.type];
const char *cause_str = GetCauseStr(obj);
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), kVUID_Core_DrawState_InvalidCommandBuffer,
"You are adding %s to command buffer %s that is invalid because bound %s %s was %s.", call_source,
report_data->FormatHandle(cb_state->commandBuffer).c_str(), type_str,
report_data->FormatHandle(obj.handle).c_str(), cause_str);
}
return skip;
}
// 'commandBuffer must be in the recording state' valid usage error code for each command
// Autogenerated as part of the vk_validation_error_message.h codegen
static const std::array<const char *, CMD_RANGE_SIZE> must_be_recording_list = {VUID_MUST_BE_RECORDING_LIST};
// Validate the given command being added to the specified cmd buffer, flagging errors if CB is not in the recording state or if
// there's an issue with the Cmd ordering
bool CoreChecks::ValidateCmd(const CMD_BUFFER_STATE *cb_state, const CMD_TYPE cmd, const char *caller_name) {
switch (cb_state->state) {
case CB_RECORDING:
return ValidateCmdSubpassState(cb_state, cmd);
case CB_INVALID_COMPLETE:
case CB_INVALID_INCOMPLETE:
return ReportInvalidCommandBuffer(cb_state, caller_name);
default:
assert(cmd != CMD_NONE);
const auto error = must_be_recording_list[cmd];
return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), error,
"You must call vkBeginCommandBuffer() before this call to %s.", caller_name);
}
}
bool CoreChecks::ValidateDeviceMaskToPhysicalDeviceCount(uint32_t deviceMask, VkDebugReportObjectTypeEXT VUID_handle_type,
uint64_t VUID_handle, const char *VUID) {
bool skip = false;
uint32_t count = 1 << physical_device_count;
if (count <= deviceMask) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VUID_handle_type, VUID_handle, VUID,
"deviceMask(0x%" PRIx32 ") is invaild. Physical device count is %" PRIu32 ".", deviceMask,
physical_device_count);
}
return skip;
}
bool CoreChecks::ValidateDeviceMaskToZero(uint32_t deviceMask, VkDebugReportObjectTypeEXT VUID_handle_type, uint64_t VUID_handle,
const char *VUID) {
bool skip = false;
if (deviceMask == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VUID_handle_type, VUID_handle, VUID,
"deviceMask(0x%" PRIx32 ") must be non-zero.", deviceMask);
}
return skip;
}
bool CoreChecks::ValidateDeviceMaskToCommandBuffer(CMD_BUFFER_STATE *pCB, uint32_t deviceMask,
VkDebugReportObjectTypeEXT VUID_handle_type, uint64_t VUID_handle,
const char *VUID) {
bool skip = false;
if ((deviceMask & pCB->initial_device_mask) != deviceMask) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VUID_handle_type, VUID_handle, VUID,
"deviceMask(0x%" PRIx32 ") is not a subset of the command buffer[%s] initial device mask(0x%" PRIx32 ").",
deviceMask, report_data->FormatHandle(pCB->commandBuffer).c_str(), pCB->initial_device_mask);
}
return skip;
}
bool CoreChecks::ValidateDeviceMaskToRenderPass(CMD_BUFFER_STATE *pCB, uint32_t deviceMask,
VkDebugReportObjectTypeEXT VUID_handle_type, uint64_t VUID_handle,
const char *VUID) {
bool skip = false;
if ((deviceMask & pCB->active_render_pass_device_mask) != deviceMask) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VUID_handle_type, VUID_handle, VUID,
"deviceMask(0x%" PRIx32 ") is not a subset of the render pass[%s] device mask(0x%" PRIx32 ").", deviceMask,
report_data->FormatHandle(pCB->activeRenderPass->renderPass).c_str(), pCB->active_render_pass_device_mask);
}
return skip;
}
// For given object struct return a ptr of BASE_NODE type for its wrapping struct
BASE_NODE *CoreChecks::GetStateStructPtrFromObject(VK_OBJECT object_struct) {
BASE_NODE *base_ptr = nullptr;
switch (object_struct.type) {
case kVulkanObjectTypeDescriptorSet: {
base_ptr = GetSetNode(reinterpret_cast<VkDescriptorSet &>(object_struct.handle));
break;
}
case kVulkanObjectTypeSampler: {
base_ptr = GetSamplerState(reinterpret_cast<VkSampler &>(object_struct.handle));
break;
}
case kVulkanObjectTypeQueryPool: {
base_ptr = GetQueryPoolState(reinterpret_cast<VkQueryPool &>(object_struct.handle));
break;
}
case kVulkanObjectTypePipeline: {
base_ptr = GetPipelineState(reinterpret_cast<VkPipeline &>(object_struct.handle));
break;
}
case kVulkanObjectTypeBuffer: {
base_ptr = GetBufferState(reinterpret_cast<VkBuffer &>(object_struct.handle));
break;
}
case kVulkanObjectTypeBufferView: {
base_ptr = GetBufferViewState(reinterpret_cast<VkBufferView &>(object_struct.handle));
break;
}
case kVulkanObjectTypeImage: {
base_ptr = GetImageState(reinterpret_cast<VkImage &>(object_struct.handle));
break;
}
case kVulkanObjectTypeImageView: {
base_ptr = GetImageViewState(reinterpret_cast<VkImageView &>(object_struct.handle));
break;
}
case kVulkanObjectTypeEvent: {
base_ptr = GetEventState(reinterpret_cast<VkEvent &>(object_struct.handle));
break;
}
case kVulkanObjectTypeDescriptorPool: {
base_ptr = GetDescriptorPoolState(reinterpret_cast<VkDescriptorPool &>(object_struct.handle));
break;
}
case kVulkanObjectTypeCommandPool: {
base_ptr = GetCommandPoolState(reinterpret_cast<VkCommandPool &>(object_struct.handle));
break;
}
case kVulkanObjectTypeFramebuffer: {
base_ptr = GetFramebufferState(reinterpret_cast<VkFramebuffer &>(object_struct.handle));
break;
}
case kVulkanObjectTypeRenderPass: {
base_ptr = GetRenderPassState(reinterpret_cast<VkRenderPass &>(object_struct.handle));
break;
}
case kVulkanObjectTypeDeviceMemory: {
base_ptr = GetDevMemState(reinterpret_cast<VkDeviceMemory &>(object_struct.handle));
break;
}
default:
// TODO : Any other objects to be handled here?
assert(0);
break;
}
return base_ptr;
}
// Tie the VK_OBJECT to the cmd buffer which includes:
// Add object_binding to cmd buffer
// Add cb_binding to object
static void AddCommandBufferBinding(std::unordered_set<CMD_BUFFER_STATE *> *cb_bindings, VK_OBJECT obj, CMD_BUFFER_STATE *cb_node) {
cb_bindings->insert(cb_node);
cb_node->object_bindings.insert(obj);
}
// For a given object, if cb_node is in that objects cb_bindings, remove cb_node
void CoreChecks::RemoveCommandBufferBinding(VK_OBJECT const *object, CMD_BUFFER_STATE *cb_node) {
BASE_NODE *base_obj = GetStateStructPtrFromObject(*object);
if (base_obj) base_obj->cb_bindings.erase(cb_node);
}
// Reset the command buffer state
// Maintain the createInfo and set state to CB_NEW, but clear all other state
void CoreChecks::ResetCommandBufferState(const VkCommandBuffer cb) {
CMD_BUFFER_STATE *pCB = GetCBState(cb);
if (pCB) {
pCB->in_use.store(0);
// Reset CB state (note that createInfo is not cleared)
pCB->commandBuffer = cb;
memset(&pCB->beginInfo, 0, sizeof(VkCommandBufferBeginInfo));
memset(&pCB->inheritanceInfo, 0, sizeof(VkCommandBufferInheritanceInfo));
pCB->hasDrawCmd = false;
pCB->state = CB_NEW;
pCB->submitCount = 0;
pCB->image_layout_change_count = 1; // Start at 1. 0 is insert value for validation cache versions, s.t. new == dirty
pCB->status = 0;
pCB->static_status = 0;
pCB->viewportMask = 0;
pCB->scissorMask = 0;
for (auto &item : pCB->lastBound) {
item.second.reset();
}
memset(&pCB->activeRenderPassBeginInfo, 0, sizeof(pCB->activeRenderPassBeginInfo));
pCB->activeRenderPass = nullptr;
pCB->activeSubpassContents = VK_SUBPASS_CONTENTS_INLINE;
pCB->activeSubpass = 0;
pCB->broken_bindings.clear();
pCB->waitedEvents.clear();
pCB->events.clear();
pCB->writeEventsBeforeWait.clear();
pCB->waitedEventsBeforeQueryReset.clear();
pCB->queryToStateMap.clear();
pCB->activeQueries.clear();
pCB->startedQueries.clear();
pCB->image_layout_map.clear();
pCB->eventToStageMap.clear();
pCB->draw_data.clear();
pCB->current_draw_data.vertex_buffer_bindings.clear();
pCB->vertex_buffer_used = false;
pCB->primaryCommandBuffer = VK_NULL_HANDLE;
// If secondary, invalidate any primary command buffer that may call us.
if (pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
InvalidateCommandBuffers(pCB->linkedCommandBuffers, {HandleToUint64(cb), kVulkanObjectTypeCommandBuffer});
}
// Remove reverse command buffer links.
for (auto pSubCB : pCB->linkedCommandBuffers) {
pSubCB->linkedCommandBuffers.erase(pCB);
}
pCB->linkedCommandBuffers.clear();
pCB->updateImages.clear();
pCB->updateBuffers.clear();
ClearCmdBufAndMemReferences(pCB);
pCB->queue_submit_functions.clear();
pCB->cmd_execute_commands_functions.clear();
pCB->eventUpdates.clear();
pCB->queryUpdates.clear();
// Remove object bindings
for (auto obj : pCB->object_bindings) {
RemoveCommandBufferBinding(&obj, pCB);
}
pCB->object_bindings.clear();
// Remove this cmdBuffer's reference from each FrameBuffer's CB ref list
for (auto framebuffer : pCB->framebuffers) {
auto fb_state = GetFramebufferState(framebuffer);
if (fb_state) fb_state->cb_bindings.erase(pCB);
}
pCB->framebuffers.clear();
pCB->activeFramebuffer = VK_NULL_HANDLE;
memset(&pCB->index_buffer_binding, 0, sizeof(pCB->index_buffer_binding));
pCB->qfo_transfer_image_barriers.Reset();
pCB->qfo_transfer_buffer_barriers.Reset();
// Clean up the label data
ResetCmdDebugUtilsLabel(report_data, pCB->commandBuffer);
pCB->debug_label.Reset();
}
if (enabled.gpu_validation) {
GpuResetCommandBuffer(cb);
}
}
CBStatusFlags MakeStaticStateMask(VkPipelineDynamicStateCreateInfo const *ds) {
// initially assume everything is static state
CBStatusFlags flags = CBSTATUS_ALL_STATE_SET;
if (ds) {
for (uint32_t i = 0; i < ds->dynamicStateCount; i++) {
switch (ds->pDynamicStates[i]) {
case VK_DYNAMIC_STATE_LINE_WIDTH:
flags &= ~CBSTATUS_LINE_WIDTH_SET;
break;
case VK_DYNAMIC_STATE_DEPTH_BIAS:
flags &= ~CBSTATUS_DEPTH_BIAS_SET;
break;
case VK_DYNAMIC_STATE_BLEND_CONSTANTS:
flags &= ~CBSTATUS_BLEND_CONSTANTS_SET;
break;
case VK_DYNAMIC_STATE_DEPTH_BOUNDS:
flags &= ~CBSTATUS_DEPTH_BOUNDS_SET;
break;
case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK:
flags &= ~CBSTATUS_STENCIL_READ_MASK_SET;
break;
case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK:
flags &= ~CBSTATUS_STENCIL_WRITE_MASK_SET;
break;
case VK_DYNAMIC_STATE_STENCIL_REFERENCE:
flags &= ~CBSTATUS_STENCIL_REFERENCE_SET;
break;
case VK_DYNAMIC_STATE_SCISSOR:
flags &= ~CBSTATUS_SCISSOR_SET;
break;
case VK_DYNAMIC_STATE_VIEWPORT:
flags &= ~CBSTATUS_VIEWPORT_SET;
break;
case VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV:
flags &= ~CBSTATUS_EXCLUSIVE_SCISSOR_SET;
break;
case VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV:
flags &= ~CBSTATUS_SHADING_RATE_PALETTE_SET;
break;
default:
break;
}
}
}
return flags;
}
// Flags validation error if the associated call is made inside a render pass. The apiName routine should ONLY be called outside a
// render pass.
bool CoreChecks::InsideRenderPass(const CMD_BUFFER_STATE *pCB, const char *apiName, const char *msgCode) {
bool inside = false;
if (pCB->activeRenderPass) {
inside = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), msgCode,
"%s: It is invalid to issue this call inside an active render pass (%s).", apiName,
report_data->FormatHandle(pCB->activeRenderPass->renderPass).c_str());
}
return inside;
}
// Flags validation error if the associated call is made outside a render pass. The apiName
// routine should ONLY be called inside a render pass.
bool CoreChecks::OutsideRenderPass(CMD_BUFFER_STATE *pCB, const char *apiName, const char *msgCode) {
bool outside = false;
if (((pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) && (!pCB->activeRenderPass)) ||
((pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) && (!pCB->activeRenderPass) &&
!(pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT))) {
outside = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), msgCode, "%s: This call must be issued inside an active render pass.",
apiName);
}
return outside;
}
void CoreChecks::InitGpuValidation() {
// Process the layer settings file.
enum CoreValidationGpuFlagBits {
CORE_VALIDATION_GPU_VALIDATION_ALL_BIT = 0x00000001,
CORE_VALIDATION_GPU_VALIDATION_RESERVE_BINDING_SLOT_BIT = 0x00000002,
};
typedef VkFlags CoreGPUFlags;
static const std::unordered_map<std::string, VkFlags> gpu_flags_option_definitions = {
{std::string("all"), CORE_VALIDATION_GPU_VALIDATION_ALL_BIT},
{std::string("reserve_binding_slot"), CORE_VALIDATION_GPU_VALIDATION_RESERVE_BINDING_SLOT_BIT},
};
std::string gpu_flags_key = "lunarg_core_validation.gpu_validation";
CoreGPUFlags gpu_flags = GetLayerOptionFlags(gpu_flags_key, gpu_flags_option_definitions, 0);
gpu_flags_key = "khronos_validation.gpu_validation";
gpu_flags |= GetLayerOptionFlags(gpu_flags_key, gpu_flags_option_definitions, 0);
if (gpu_flags & CORE_VALIDATION_GPU_VALIDATION_ALL_BIT) {
instance_state->enabled.gpu_validation = true;
}
if (gpu_flags & CORE_VALIDATION_GPU_VALIDATION_RESERVE_BINDING_SLOT_BIT) {
instance_state->enabled.gpu_validation_reserve_binding_slot = true;
}
}
void CoreChecks::PostCallRecordCreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator,
VkInstance *pInstance, VkResult result) {
if (VK_SUCCESS != result) return;
InitGpuValidation();
}
bool CoreChecks::ValidatePhysicalDeviceQueueFamily(const PHYSICAL_DEVICE_STATE *pd_state, uint32_t requested_queue_family,
const char *err_code, const char *cmd_name, const char *queue_family_var_name) {
bool skip = false;
const char *conditional_ext_cmd =
instance_extensions.vk_khr_get_physical_device_properties_2 ? " or vkGetPhysicalDeviceQueueFamilyProperties2[KHR]" : "";
std::string count_note = (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState)
? "the pQueueFamilyPropertyCount was never obtained"
: "i.e. is not less than " + std::to_string(pd_state->queue_family_count);
if (requested_queue_family >= pd_state->queue_family_count) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(pd_state->phys_device), err_code,
"%s: %s (= %" PRIu32
") is not less than any previously obtained pQueueFamilyPropertyCount from "
"vkGetPhysicalDeviceQueueFamilyProperties%s (%s).",
cmd_name, queue_family_var_name, requested_queue_family, conditional_ext_cmd, count_note.c_str());
}
return skip;
}
// Verify VkDeviceQueueCreateInfos
bool CoreChecks::ValidateDeviceQueueCreateInfos(const PHYSICAL_DEVICE_STATE *pd_state, uint32_t info_count,
const VkDeviceQueueCreateInfo *infos) {
bool skip = false;
std::unordered_set<uint32_t> queue_family_set;
for (uint32_t i = 0; i < info_count; ++i) {
const auto requested_queue_family = infos[i].queueFamilyIndex;
// Verify that requested queue family is known to be valid at this point in time
std::string queue_family_var_name = "pCreateInfo->pQueueCreateInfos[" + std::to_string(i) + "].queueFamilyIndex";
skip |= ValidatePhysicalDeviceQueueFamily(pd_state, requested_queue_family,
"VUID-VkDeviceQueueCreateInfo-queueFamilyIndex-00381", "vkCreateDevice",
queue_family_var_name.c_str());
if (queue_family_set.count(requested_queue_family)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(pd_state->phys_device), "VUID-VkDeviceCreateInfo-queueFamilyIndex-00372",
"CreateDevice(): %s (=%" PRIu32 ") is not unique within pQueueCreateInfos.",
queue_family_var_name.c_str(), requested_queue_family);
} else {
queue_family_set.insert(requested_queue_family);
}
// Verify that requested queue count of queue family is known to be valid at this point in time
if (requested_queue_family < pd_state->queue_family_count) {
const auto requested_queue_count = infos[i].queueCount;
const auto queue_family_props_count = pd_state->queue_family_properties.size();
const bool queue_family_has_props = requested_queue_family < queue_family_props_count;
const char *conditional_ext_cmd = instance_extensions.vk_khr_get_physical_device_properties_2
? " or vkGetPhysicalDeviceQueueFamilyProperties2[KHR]"
: "";
std::string count_note =
!queue_family_has_props
? "the pQueueFamilyProperties[" + std::to_string(requested_queue_family) + "] was never obtained"
: "i.e. is not less than or equal to " +
std::to_string(pd_state->queue_family_properties[requested_queue_family].queueCount);
if (!queue_family_has_props ||
requested_queue_count > pd_state->queue_family_properties[requested_queue_family].queueCount) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(pd_state->phys_device), "VUID-VkDeviceQueueCreateInfo-queueCount-00382",
"vkCreateDevice: pCreateInfo->pQueueCreateInfos[%" PRIu32 "].queueCount (=%" PRIu32
") is not less than or equal to available queue count for this pCreateInfo->pQueueCreateInfos[%" PRIu32
"].queueFamilyIndex} (=%" PRIu32 ") obtained previously from vkGetPhysicalDeviceQueueFamilyProperties%s (%s).",
i, requested_queue_count, i, requested_queue_family, conditional_ext_cmd, count_note.c_str());
}
}
}
return skip;
}
bool CoreChecks::PreCallValidateCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) {
bool skip = false;
auto pd_state = GetPhysicalDeviceState(gpu);
// TODO: object_tracker should perhaps do this instead
// and it does not seem to currently work anyway -- the loader just crashes before this point
if (!pd_state) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0,
kVUID_Core_DevLimit_MustQueryCount,
"Invalid call to vkCreateDevice() w/o first calling vkEnumeratePhysicalDevices().");
}
skip |= ValidateDeviceQueueCreateInfos(pd_state, pCreateInfo->queueCreateInfoCount, pCreateInfo->pQueueCreateInfos);
return skip;
}
void CoreChecks::PreCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDevice *pDevice,
std::unique_ptr<safe_VkDeviceCreateInfo> &modified_create_info) {
// GPU Validation can possibly turn on device features, so give it a chance to change the create info.
if (enabled.gpu_validation) {
VkPhysicalDeviceFeatures supported_features;
DispatchGetPhysicalDeviceFeatures(gpu, &supported_features);
GpuPreCallRecordCreateDevice(gpu, modified_create_info, &supported_features);
}
}
void CoreChecks::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) {
if (VK_SUCCESS != result) return;
const VkPhysicalDeviceFeatures *enabled_features_found = pCreateInfo->pEnabledFeatures;
if (nullptr == enabled_features_found) {
const auto *features2 = lvl_find_in_chain<VkPhysicalDeviceFeatures2KHR>(pCreateInfo->pNext);
if (features2) {
enabled_features_found = &(features2->features);
}
}
ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map);
ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeCoreValidation);
CoreChecks *core_checks = static_cast<CoreChecks *>(validation_data);
if (nullptr == enabled_features_found) {
core_checks->enabled_features.core = {};
} else {
core_checks->enabled_features.core = *enabled_features_found;
}
// Make sure that queue_family_properties are obtained for this device's physical_device, even if the app has not
// previously set them through an explicit API call.
uint32_t count;
auto pd_state = GetPhysicalDeviceState(gpu);
DispatchGetPhysicalDeviceQueueFamilyProperties(gpu, &count, nullptr);
pd_state->queue_family_count = count;
pd_state->queue_family_properties.resize(std::max(static_cast<uint32_t>(pd_state->queue_family_properties.size()), count));
DispatchGetPhysicalDeviceQueueFamilyProperties(gpu, &count, &pd_state->queue_family_properties[0]);
// Save local link to this device's physical device state
core_checks->physical_device_state = pd_state;
const auto *device_group_ci = lvl_find_in_chain<VkDeviceGroupDeviceCreateInfo>(pCreateInfo->pNext);
core_checks->physical_device_count =
device_group_ci && device_group_ci->physicalDeviceCount > 0 ? device_group_ci->physicalDeviceCount : 1;
const auto *descriptor_indexing_features = lvl_find_in_chain<VkPhysicalDeviceDescriptorIndexingFeaturesEXT>(pCreateInfo->pNext);
if (descriptor_indexing_features) {
core_checks->enabled_features.descriptor_indexing = *descriptor_indexing_features;
}
const auto *eight_bit_storage_features = lvl_find_in_chain<VkPhysicalDevice8BitStorageFeaturesKHR>(pCreateInfo->pNext);
if (eight_bit_storage_features) {
core_checks->enabled_features.eight_bit_storage = *eight_bit_storage_features;
}
const auto *exclusive_scissor_features = lvl_find_in_chain<VkPhysicalDeviceExclusiveScissorFeaturesNV>(pCreateInfo->pNext);
if (exclusive_scissor_features) {
core_checks->enabled_features.exclusive_scissor = *exclusive_scissor_features;
}
const auto *shading_rate_image_features = lvl_find_in_chain<VkPhysicalDeviceShadingRateImageFeaturesNV>(pCreateInfo->pNext);
if (shading_rate_image_features) {
core_checks->enabled_features.shading_rate_image = *shading_rate_image_features;
}
const auto *mesh_shader_features = lvl_find_in_chain<VkPhysicalDeviceMeshShaderFeaturesNV>(pCreateInfo->pNext);
if (mesh_shader_features) {
core_checks->enabled_features.mesh_shader = *mesh_shader_features;
}
const auto *inline_uniform_block_features =
lvl_find_in_chain<VkPhysicalDeviceInlineUniformBlockFeaturesEXT>(pCreateInfo->pNext);
if (inline_uniform_block_features) {
core_checks->enabled_features.inline_uniform_block = *inline_uniform_block_features;
}
const auto *transform_feedback_features = lvl_find_in_chain<VkPhysicalDeviceTransformFeedbackFeaturesEXT>(pCreateInfo->pNext);
if (transform_feedback_features) {
core_checks->enabled_features.transform_feedback_features = *transform_feedback_features;
}
const auto *float16_int8_features = lvl_find_in_chain<VkPhysicalDeviceFloat16Int8FeaturesKHR>(pCreateInfo->pNext);
if (float16_int8_features) {
core_checks->enabled_features.float16_int8 = *float16_int8_features;
}
const auto *vtx_attrib_div_features = lvl_find_in_chain<VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT>(pCreateInfo->pNext);
if (vtx_attrib_div_features) {
core_checks->enabled_features.vtx_attrib_divisor_features = *vtx_attrib_div_features;
}
const auto *scalar_block_layout_features = lvl_find_in_chain<VkPhysicalDeviceScalarBlockLayoutFeaturesEXT>(pCreateInfo->pNext);
if (scalar_block_layout_features) {
core_checks->enabled_features.scalar_block_layout_features = *scalar_block_layout_features;
}
const auto *buffer_address = lvl_find_in_chain<VkPhysicalDeviceBufferAddressFeaturesEXT>(pCreateInfo->pNext);
if (buffer_address) {
core_checks->enabled_features.buffer_address = *buffer_address;
}
const auto *cooperative_matrix_features = lvl_find_in_chain<VkPhysicalDeviceCooperativeMatrixFeaturesNV>(pCreateInfo->pNext);
if (cooperative_matrix_features) {
core_checks->enabled_features.cooperative_matrix_features = *cooperative_matrix_features;
}
const auto *float_controls_features = lvl_find_in_chain<VkPhysicalDeviceFloatControlsPropertiesKHR>(pCreateInfo->pNext);
if (float_controls_features) {
core_checks->enabled_features.float_controls = *float_controls_features;
}
// Store physical device properties and physical device mem limits into CoreChecks structs
DispatchGetPhysicalDeviceMemoryProperties(gpu, &core_checks->phys_dev_mem_props);
DispatchGetPhysicalDeviceProperties(gpu, &core_checks->phys_dev_props);
const auto &dev_ext = core_checks->device_extensions;
auto *phys_dev_props = &core_checks->phys_dev_ext_props;
if (dev_ext.vk_khr_push_descriptor) {
// Get the needed push_descriptor limits
VkPhysicalDevicePushDescriptorPropertiesKHR push_descriptor_prop;
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_khr_push_descriptor, &push_descriptor_prop);
phys_dev_props->max_push_descriptors = push_descriptor_prop.maxPushDescriptors;
}
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_ext_descriptor_indexing, &phys_dev_props->descriptor_indexing_props);
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_nv_shading_rate_image, &phys_dev_props->shading_rate_image_props);
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_nv_mesh_shader, &phys_dev_props->mesh_shader_props);
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_ext_inline_uniform_block, &phys_dev_props->inline_uniform_block_props);
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_ext_vertex_attribute_divisor, &phys_dev_props->vtx_attrib_divisor_props);
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_khr_depth_stencil_resolve, &phys_dev_props->depth_stencil_resolve_props);
GetPhysicalDeviceExtProperties(gpu, dev_ext.vk_ext_transform_feedback, &phys_dev_props->transform_feedback_props);
if (enabled.gpu_validation) {
core_checks->GpuPostCallRecordCreateDevice(&enabled);
}
if (core_checks->device_extensions.vk_nv_cooperative_matrix) {
// Get the needed cooperative_matrix properties
auto cooperative_matrix_props = lvl_init_struct<VkPhysicalDeviceCooperativeMatrixPropertiesNV>();
auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&cooperative_matrix_props);
instance_dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2);
core_checks->phys_dev_ext_props.cooperative_matrix_props = cooperative_matrix_props;
uint32_t numCooperativeMatrixProperties = 0;
instance_dispatch_table.GetPhysicalDeviceCooperativeMatrixPropertiesNV(gpu, &numCooperativeMatrixProperties, NULL);
core_checks->cooperative_matrix_properties.resize(numCooperativeMatrixProperties,
lvl_init_struct<VkCooperativeMatrixPropertiesNV>());
instance_dispatch_table.GetPhysicalDeviceCooperativeMatrixPropertiesNV(gpu, &numCooperativeMatrixProperties,
core_checks->cooperative_matrix_properties.data());
}
// Store queue family data
if ((pCreateInfo != nullptr) && (pCreateInfo->pQueueCreateInfos != nullptr)) {
for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; ++i) {
core_checks->queue_family_index_map.insert(
std::make_pair(pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex, pCreateInfo->pQueueCreateInfos[i].queueCount));
}
}
}
void CoreChecks::PreCallRecordDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) {
if (!device) return;
if (enabled.gpu_validation) {
GpuPreCallRecordDestroyDevice();
}
pipelineMap.clear();
renderPassMap.clear();
commandBufferMap.clear();
// This will also delete all sets in the pool & remove them from setMap
DeletePools();
// All sets should be removed
assert(setMap.empty());
descriptorSetLayoutMap.clear();
imageViewMap.clear();
imageMap.clear();
imageSubresourceMap.clear();
imageLayoutMap.clear();
bufferViewMap.clear();
bufferMap.clear();
// Queues persist until device is destroyed
queueMap.clear();
layer_debug_utils_destroy_device(device);
}
// For given stage mask, if Geometry shader stage is on w/o GS being enabled, report geo_error_id
// and if Tessellation Control or Evaluation shader stages are on w/o TS being enabled, report tess_error_id.
// Similarly for mesh and task shaders.
bool CoreChecks::ValidateStageMaskGsTsEnables(VkPipelineStageFlags stageMask, const char *caller, const char *geo_error_id,
const char *tess_error_id, const char *mesh_error_id, const char *task_error_id) {
bool skip = false;
if (!enabled_features.core.geometryShader && (stageMask & VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, geo_error_id,
"%s call includes a stageMask with VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT bit set when device does not have "
"geometryShader feature enabled.",
caller);
}
if (!enabled_features.core.tessellationShader &&
(stageMask & (VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, tess_error_id,
"%s call includes a stageMask with VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT and/or "
"VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT bit(s) set when device does not have "
"tessellationShader feature enabled.",
caller);
}
if (!enabled_features.mesh_shader.meshShader && (stageMask & VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, mesh_error_id,
"%s call includes a stageMask with VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV bit set when device does not have "
"VkPhysicalDeviceMeshShaderFeaturesNV::meshShader feature enabled.",
caller);
}
if (!enabled_features.mesh_shader.taskShader && (stageMask & VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, task_error_id,
"%s call includes a stageMask with VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV bit set when device does not have "
"VkPhysicalDeviceMeshShaderFeaturesNV::taskShader feature enabled.",
caller);
}
return skip;
}
// Loop through bound objects and increment their in_use counts.
void CoreChecks::IncrementBoundObjects(CMD_BUFFER_STATE const *cb_node) {
for (auto obj : cb_node->object_bindings) {
auto base_obj = GetStateStructPtrFromObject(obj);
if (base_obj) {
base_obj->in_use.fetch_add(1);
}
}
}
// Track which resources are in-flight by atomically incrementing their "in_use" count
void CoreChecks::IncrementResources(CMD_BUFFER_STATE *cb_node) {
cb_node->submitCount++;
cb_node->in_use.fetch_add(1);
// First Increment for all "generic" objects bound to cmd buffer, followed by special-case objects below
IncrementBoundObjects(cb_node);
// TODO : We should be able to remove the NULL look-up checks from the code below as long as
// all the corresponding cases are verified to cause CB_INVALID state and the CB_INVALID state
// should then be flagged prior to calling this function
for (auto draw_data_element : cb_node->draw_data) {
for (auto &vertex_buffer : draw_data_element.vertex_buffer_bindings) {
auto buffer_state = GetBufferState(vertex_buffer.buffer);
if (buffer_state) {
buffer_state->in_use.fetch_add(1);
}
}
}
for (auto event : cb_node->writeEventsBeforeWait) {
auto event_state = GetEventState(event);
if (event_state) event_state->write_in_use++;
}
}
// Note: This function assumes that the global lock is held by the calling thread.
// For the given queue, verify the queue state up to the given seq number.
// Currently the only check is to make sure that if there are events to be waited on prior to
// a QueryReset, make sure that all such events have been signalled.
bool CoreChecks::VerifyQueueStateToSeq(QUEUE_STATE *initial_queue, uint64_t initial_seq) {
bool skip = false;
// sequence number we want to validate up to, per queue
std::unordered_map<QUEUE_STATE *, uint64_t> target_seqs{{initial_queue, initial_seq}};
// sequence number we've completed validation for, per queue
std::unordered_map<QUEUE_STATE *, uint64_t> done_seqs;
std::vector<QUEUE_STATE *> worklist{initial_queue};
while (worklist.size()) {
auto queue = worklist.back();
worklist.pop_back();
auto target_seq = target_seqs[queue];
auto seq = std::max(done_seqs[queue], queue->seq);
auto sub_it = queue->submissions.begin() + int(seq - queue->seq); // seq >= queue->seq
for (; seq < target_seq; ++sub_it, ++seq) {
for (auto &wait : sub_it->waitSemaphores) {
auto other_queue = GetQueueState(wait.queue);
if (other_queue == queue) continue; // semaphores /always/ point backwards, so no point here.
auto other_target_seq = std::max(target_seqs[other_queue], wait.seq);
auto other_done_seq = std::max(done_seqs[other_queue], other_queue->seq);
// if this wait is for another queue, and covers new sequence
// numbers beyond what we've already validated, mark the new
// target seq and (possibly-re)add the queue to the worklist.
if (other_done_seq < other_target_seq) {
target_seqs[other_queue] = other_target_seq;
worklist.push_back(other_queue);
}
}
}
// finally mark the point we've now validated this queue to.
done_seqs[queue] = seq;
}
return skip;
}
// When the given fence is retired, verify outstanding queue operations through the point of the fence
bool CoreChecks::VerifyQueueStateToFence(VkFence fence) {
auto fence_state = GetFenceState(fence);
if (fence_state && fence_state->scope == kSyncScopeInternal && VK_NULL_HANDLE != fence_state->signaler.first) {
return VerifyQueueStateToSeq(GetQueueState(fence_state->signaler.first), fence_state->signaler.second);
}
return false;
}
// Decrement in-use count for objects bound to command buffer
void CoreChecks::DecrementBoundResources(CMD_BUFFER_STATE const *cb_node) {
BASE_NODE *base_obj = nullptr;
for (auto obj : cb_node->object_bindings) {
base_obj = GetStateStructPtrFromObject(obj);
if (base_obj) {
base_obj->in_use.fetch_sub(1);
}
}
}
void CoreChecks::RetireWorkOnQueue(QUEUE_STATE *pQueue, uint64_t seq) {
std::unordered_map<VkQueue, uint64_t> otherQueueSeqs;
// Roll this queue forward, one submission at a time.
while (pQueue->seq < seq) {
auto &submission = pQueue->submissions.front();
for (auto &wait : submission.waitSemaphores) {
auto pSemaphore = GetSemaphoreState(wait.semaphore);
if (pSemaphore) {
pSemaphore->in_use.fetch_sub(1);
}
auto &lastSeq = otherQueueSeqs[wait.queue];
lastSeq = std::max(lastSeq, wait.seq);
}
for (auto &semaphore : submission.signalSemaphores) {
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore) {
pSemaphore->in_use.fetch_sub(1);
}
}
for (auto &semaphore : submission.externalSemaphores) {
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore) {
pSemaphore->in_use.fetch_sub(1);
}
}
for (auto cb : submission.cbs) {
auto cb_node = GetCBState(cb);
if (!cb_node) {
continue;
}
// First perform decrement on general case bound objects
DecrementBoundResources(cb_node);
for (auto draw_data_element : cb_node->draw_data) {
for (auto &vertex_buffer_binding : draw_data_element.vertex_buffer_bindings) {
auto buffer_state = GetBufferState(vertex_buffer_binding.buffer);
if (buffer_state) {
buffer_state->in_use.fetch_sub(1);
}
}
}
for (auto event : cb_node->writeEventsBeforeWait) {
auto eventNode = eventMap.find(event);
if (eventNode != eventMap.end()) {
eventNode->second.write_in_use--;
}
}
for (auto queryStatePair : cb_node->queryToStateMap) {
queryToStateMap[queryStatePair.first] = queryStatePair.second;
}
for (auto eventStagePair : cb_node->eventToStageMap) {
eventMap[eventStagePair.first].stageMask = eventStagePair.second;
}
cb_node->in_use.fetch_sub(1);
}
auto pFence = GetFenceState(submission.fence);
if (pFence && pFence->scope == kSyncScopeInternal) {
pFence->state = FENCE_RETIRED;
}
pQueue->submissions.pop_front();
pQueue->seq++;
}
// Roll other queues forward to the highest seq we saw a wait for
for (auto qs : otherQueueSeqs) {
RetireWorkOnQueue(GetQueueState(qs.first), qs.second);
}
}
// Submit a fence to a queue, delimiting previous fences and previous untracked
// work by it.
static void SubmitFence(QUEUE_STATE *pQueue, FENCE_STATE *pFence, uint64_t submitCount) {
pFence->state = FENCE_INFLIGHT;
pFence->signaler.first = pQueue->queue;
pFence->signaler.second = pQueue->seq + pQueue->submissions.size() + submitCount;
}
bool CoreChecks::ValidateCommandBufferSimultaneousUse(CMD_BUFFER_STATE *pCB, int current_submit_count) {
bool skip = false;
if ((pCB->in_use.load() || current_submit_count > 1) &&
!(pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
"VUID-vkQueueSubmit-pCommandBuffers-00071",
"Command Buffer %s is already in use and is not marked for simultaneous use.",
report_data->FormatHandle(pCB->commandBuffer).c_str());
}
return skip;
}
bool CoreChecks::ValidateCommandBufferState(CMD_BUFFER_STATE *cb_state, const char *call_source, int current_submit_count,
const char *vu_id) {
bool skip = false;
if (disabled.command_buffer_state) return skip;
// Validate ONE_TIME_SUBMIT_BIT CB is not being submitted more than once
if ((cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) &&
(cb_state->submitCount + current_submit_count > 1)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
kVUID_Core_DrawState_CommandBufferSingleSubmitViolation,
"Commandbuffer %s was begun w/ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT set, but has been submitted 0x%" PRIxLEAST64
"times.",
report_data->FormatHandle(cb_state->commandBuffer).c_str(), cb_state->submitCount + current_submit_count);
}
// Validate that cmd buffers have been updated
switch (cb_state->state) {
case CB_INVALID_INCOMPLETE:
case CB_INVALID_COMPLETE:
skip |= ReportInvalidCommandBuffer(cb_state, call_source);
break;
case CB_NEW:
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
(uint64_t)(cb_state->commandBuffer), vu_id,
"Command buffer %s used in the call to %s is unrecorded and contains no commands.",
report_data->FormatHandle(cb_state->commandBuffer).c_str(), call_source);
break;
case CB_RECORDING:
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), kVUID_Core_DrawState_NoEndCommandBuffer,
"You must call vkEndCommandBuffer() on command buffer %s before this call to %s!",
report_data->FormatHandle(cb_state->commandBuffer).c_str(), call_source);
break;
default: /* recorded */
break;
}
return skip;
}
bool CoreChecks::ValidateResources(CMD_BUFFER_STATE *cb_node) {
bool skip = false;
// TODO : We should be able to remove the NULL look-up checks from the code below as long as
// all the corresponding cases are verified to cause CB_INVALID state and the CB_INVALID state
// should then be flagged prior to calling this function
for (const auto &draw_data_element : cb_node->draw_data) {
for (const auto &vertex_buffer_binding : draw_data_element.vertex_buffer_bindings) {
auto buffer_state = GetBufferState(vertex_buffer_binding.buffer);
if ((vertex_buffer_binding.buffer != VK_NULL_HANDLE) && (!buffer_state)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
HandleToUint64(vertex_buffer_binding.buffer), kVUID_Core_DrawState_InvalidBuffer,
"Cannot submit cmd buffer using deleted buffer %s.",
report_data->FormatHandle(vertex_buffer_binding.buffer).c_str());
}
}
}
return skip;
}
// Check that the queue family index of 'queue' matches one of the entries in pQueueFamilyIndices
bool CoreChecks::ValidImageBufferQueue(CMD_BUFFER_STATE *cb_node, const VK_OBJECT *object, VkQueue queue, uint32_t count,
const uint32_t *indices) {
bool found = false;
bool skip = false;
auto queue_state = GetQueueState(queue);
if (queue_state) {
for (uint32_t i = 0; i < count; i++) {
if (indices[i] == queue_state->queueFamilyIndex) {
found = true;
break;
}
}
if (!found) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, get_debug_report_enum[object->type], object->handle,
kVUID_Core_DrawState_InvalidQueueFamily,
"vkQueueSubmit: Command buffer %s contains %s %s which was not created allowing concurrent access to "
"this queue family %d.",
report_data->FormatHandle(cb_node->commandBuffer).c_str(), object_string[object->type],
report_data->FormatHandle(object->handle).c_str(), queue_state->queueFamilyIndex);
}
}
return skip;
}
// Validate that queueFamilyIndices of primary command buffers match this queue
// Secondary command buffers were previously validated in vkCmdExecuteCommands().
bool CoreChecks::ValidateQueueFamilyIndices(CMD_BUFFER_STATE *pCB, VkQueue queue) {
bool skip = false;
auto pPool = GetCommandPoolState(pCB->createInfo.commandPool);
auto queue_state = GetQueueState(queue);
if (pPool && queue_state) {
if (pPool->queueFamilyIndex != queue_state->queueFamilyIndex) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), "VUID-vkQueueSubmit-pCommandBuffers-00074",
"vkQueueSubmit: Primary command buffer %s created in queue family %d is being submitted on queue %s "
"from queue family %d.",
report_data->FormatHandle(pCB->commandBuffer).c_str(), pPool->queueFamilyIndex,
report_data->FormatHandle(queue).c_str(), queue_state->queueFamilyIndex);
}
// Ensure that any bound images or buffers created with SHARING_MODE_CONCURRENT have access to the current queue family
for (auto object : pCB->object_bindings) {
if (object.type == kVulkanObjectTypeImage) {
auto image_state = GetImageState(reinterpret_cast<VkImage &>(object.handle));
if (image_state && image_state->createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) {
skip |= ValidImageBufferQueue(pCB, &object, queue, image_state->createInfo.queueFamilyIndexCount,
image_state->createInfo.pQueueFamilyIndices);
}
} else if (object.type == kVulkanObjectTypeBuffer) {
auto buffer_state = GetBufferState(reinterpret_cast<VkBuffer &>(object.handle));
if (buffer_state && buffer_state->createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) {
skip |= ValidImageBufferQueue(pCB, &object, queue, buffer_state->createInfo.queueFamilyIndexCount,
buffer_state->createInfo.pQueueFamilyIndices);
}
}
}
}
return skip;
}
bool CoreChecks::ValidatePrimaryCommandBufferState(CMD_BUFFER_STATE *pCB, int current_submit_count,
QFOTransferCBScoreboards<VkImageMemoryBarrier> *qfo_image_scoreboards,
QFOTransferCBScoreboards<VkBufferMemoryBarrier> *qfo_buffer_scoreboards) {
// Track in-use for resources off of primary and any secondary CBs
bool skip = false;
// If USAGE_SIMULTANEOUS_USE_BIT not set then CB cannot already be executing
// on device
skip |= ValidateCommandBufferSimultaneousUse(pCB, current_submit_count);
skip |= ValidateResources(pCB);
skip |= ValidateQueuedQFOTransfers(pCB, qfo_image_scoreboards, qfo_buffer_scoreboards);
for (auto pSubCB : pCB->linkedCommandBuffers) {
skip |= ValidateResources(pSubCB);
skip |= ValidateQueuedQFOTransfers(pSubCB, qfo_image_scoreboards, qfo_buffer_scoreboards);
// TODO: replace with InvalidateCommandBuffers() at recording.
if ((pSubCB->primaryCommandBuffer != pCB->commandBuffer) &&
!(pSubCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) {
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
"VUID-vkQueueSubmit-pCommandBuffers-00073",
"Commandbuffer %s was submitted with secondary buffer %s but that buffer has subsequently been bound to "
"primary cmd buffer %s and it does not have VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set.",
report_data->FormatHandle(pCB->commandBuffer).c_str(), report_data->FormatHandle(pSubCB->commandBuffer).c_str(),
report_data->FormatHandle(pSubCB->primaryCommandBuffer).c_str());
}
}
skip |= ValidateCommandBufferState(pCB, "vkQueueSubmit()", current_submit_count, "VUID-vkQueueSubmit-pCommandBuffers-00072");
return skip;
}
bool CoreChecks::ValidateFenceForSubmit(FENCE_STATE *pFence) {
bool skip = false;
if (pFence && pFence->scope == kSyncScopeInternal) {
if (pFence->state == FENCE_INFLIGHT) {
// TODO: opportunities for "VUID-vkQueueSubmit-fence-00064", "VUID-vkQueueBindSparse-fence-01114",
// "VUID-vkAcquireNextImageKHR-fence-01287"
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
HandleToUint64(pFence->fence), kVUID_Core_DrawState_InvalidFence,
"Fence %s is already in use by another submission.", report_data->FormatHandle(pFence->fence).c_str());
}
else if (pFence->state == FENCE_RETIRED) {
// TODO: opportunities for "VUID-vkQueueSubmit-fence-00063", "VUID-vkQueueBindSparse-fence-01113",
// "VUID-vkAcquireNextImageKHR-fence-01287"
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
HandleToUint64(pFence->fence), kVUID_Core_MemTrack_FenceState,
"Fence %s submitted in SIGNALED state. Fences must be reset before being submitted",
report_data->FormatHandle(pFence->fence).c_str());
}
}
return skip;
}
void CoreChecks::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
VkResult result) {
uint64_t early_retire_seq = 0;
auto pQueue = GetQueueState(queue);
auto pFence = GetFenceState(fence);
if (pFence) {
if (pFence->scope == kSyncScopeInternal) {
// Mark fence in use
SubmitFence(pQueue, pFence, std::max(1u, submitCount));
if (!submitCount) {
// If no submissions, but just dropping a fence on the end of the queue,
// record an empty submission with just the fence, so we can determine
// its completion.
pQueue->submissions.emplace_back(std::vector<VkCommandBuffer>(), std::vector<SEMAPHORE_WAIT>(),
std::vector<VkSemaphore>(), std::vector<VkSemaphore>(), fence);
}
} else {
// Retire work up until this fence early, we will not see the wait that corresponds to this signal
early_retire_seq = pQueue->seq + pQueue->submissions.size();
if (!external_sync_warning) {
external_sync_warning = true;
log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence),
kVUID_Core_DrawState_QueueForwardProgress,
"vkQueueSubmit(): Signaling external fence %s on queue %s will disable validation of preceding command "
"buffer lifecycle states and the in-use status of associated objects.",
report_data->FormatHandle(fence).c_str(), report_data->FormatHandle(queue).c_str());
}
}
}
// Now process each individual submit
for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
std::vector<VkCommandBuffer> cbs;
const VkSubmitInfo *submit = &pSubmits[submit_idx];
vector<SEMAPHORE_WAIT> semaphore_waits;
vector<VkSemaphore> semaphore_signals;
vector<VkSemaphore> semaphore_externals;
for (uint32_t i = 0; i < submit->waitSemaphoreCount; ++i) {
VkSemaphore semaphore = submit->pWaitSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore) {
if (pSemaphore->scope == kSyncScopeInternal) {
if (pSemaphore->signaler.first != VK_NULL_HANDLE) {
semaphore_waits.push_back({semaphore, pSemaphore->signaler.first, pSemaphore->signaler.second});
pSemaphore->in_use.fetch_add(1);
}
pSemaphore->signaler.first = VK_NULL_HANDLE;
pSemaphore->signaled = false;
} else {
semaphore_externals.push_back(semaphore);
pSemaphore->in_use.fetch_add(1);
if (pSemaphore->scope == kSyncScopeExternalTemporary) {
pSemaphore->scope = kSyncScopeInternal;
}
}
}
}
for (uint32_t i = 0; i < submit->signalSemaphoreCount; ++i) {
VkSemaphore semaphore = submit->pSignalSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore) {
if (pSemaphore->scope == kSyncScopeInternal) {
pSemaphore->signaler.first = queue;
pSemaphore->signaler.second = pQueue->seq + pQueue->submissions.size() + 1;
pSemaphore->signaled = true;
pSemaphore->in_use.fetch_add(1);
semaphore_signals.push_back(semaphore);
} else {
// Retire work up until this submit early, we will not see the wait that corresponds to this signal
early_retire_seq = std::max(early_retire_seq, pQueue->seq + pQueue->submissions.size() + 1);
if (!external_sync_warning) {
external_sync_warning = true;
log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress,
"vkQueueSubmit(): Signaling external semaphore %s on queue %s will disable validation of preceding "
"command buffer lifecycle states and the in-use status of associated objects.",
report_data->FormatHandle(semaphore).c_str(), report_data->FormatHandle(queue).c_str());
}
}
}
}
for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
auto cb_node = GetCBState(submit->pCommandBuffers[i]);
if (cb_node) {
cbs.push_back(submit->pCommandBuffers[i]);
for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
cbs.push_back(secondaryCmdBuffer->commandBuffer);
UpdateCmdBufImageLayouts(secondaryCmdBuffer);
IncrementResources(secondaryCmdBuffer);
RecordQueuedQFOTransfers(secondaryCmdBuffer);
}
UpdateCmdBufImageLayouts(cb_node);
IncrementResources(cb_node);
RecordQueuedQFOTransfers(cb_node);
}
}
pQueue->submissions.emplace_back(cbs, semaphore_waits, semaphore_signals, semaphore_externals,
submit_idx == submitCount - 1 ? fence : VK_NULL_HANDLE);
}
if (early_retire_seq) {
RetireWorkOnQueue(pQueue, early_retire_seq);
}
if (enabled.gpu_validation) {
GpuPostCallQueueSubmit(queue, submitCount, pSubmits, fence);
}
}
bool CoreChecks::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
auto pFence = GetFenceState(fence);
bool skip = ValidateFenceForSubmit(pFence);
if (skip) {
return true;
}
unordered_set<VkSemaphore> signaled_semaphores;
unordered_set<VkSemaphore> unsignaled_semaphores;
unordered_set<VkSemaphore> internal_semaphores;
vector<VkCommandBuffer> current_cmds;
unordered_map<ImageSubresourcePair, IMAGE_LAYOUT_STATE> localImageLayoutMap;
// Now verify each individual submit
for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
const VkSubmitInfo *submit = &pSubmits[submit_idx];
for (uint32_t i = 0; i < submit->waitSemaphoreCount; ++i) {
skip |= ValidateStageMaskGsTsEnables(
submit->pWaitDstStageMask[i], "vkQueueSubmit()", "VUID-VkSubmitInfo-pWaitDstStageMask-00076",
"VUID-VkSubmitInfo-pWaitDstStageMask-00077", "VUID-VkSubmitInfo-pWaitDstStageMask-02089",
"VUID-VkSubmitInfo-pWaitDstStageMask-02090");
VkSemaphore semaphore = submit->pWaitSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) {
if (unsignaled_semaphores.count(semaphore) ||
(!(signaled_semaphores.count(semaphore)) && !(pSemaphore->signaled))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress,
"Queue %s is waiting on semaphore %s that has no way to be signaled.",
report_data->FormatHandle(queue).c_str(), report_data->FormatHandle(semaphore).c_str());
} else {
signaled_semaphores.erase(semaphore);
unsignaled_semaphores.insert(semaphore);
}
}
if (pSemaphore && pSemaphore->scope == kSyncScopeExternalTemporary) {
internal_semaphores.insert(semaphore);
}
}
for (uint32_t i = 0; i < submit->signalSemaphoreCount; ++i) {
VkSemaphore semaphore = submit->pSignalSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) {
if (signaled_semaphores.count(semaphore) || (!(unsignaled_semaphores.count(semaphore)) && pSemaphore->signaled)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress,
"Queue %s is signaling semaphore %s that was previously signaled by queue %s but has not since "
"been waited on by any queue.",
report_data->FormatHandle(queue).c_str(), report_data->FormatHandle(semaphore).c_str(),
report_data->FormatHandle(pSemaphore->signaler.first).c_str());
} else {
unsignaled_semaphores.erase(semaphore);
signaled_semaphores.insert(semaphore);
}
}
}
QFOTransferCBScoreboards<VkImageMemoryBarrier> qfo_image_scoreboards;
QFOTransferCBScoreboards<VkBufferMemoryBarrier> qfo_buffer_scoreboards;
for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
auto cb_node = GetCBState(submit->pCommandBuffers[i]);
if (cb_node) {
skip |= ValidateCmdBufImageLayouts(cb_node, imageLayoutMap, localImageLayoutMap);
current_cmds.push_back(submit->pCommandBuffers[i]);
skip |= ValidatePrimaryCommandBufferState(
cb_node, (int)std::count(current_cmds.begin(), current_cmds.end(), submit->pCommandBuffers[i]),
&qfo_image_scoreboards, &qfo_buffer_scoreboards);
skip |= ValidateQueueFamilyIndices(cb_node, queue);
// Potential early exit here as bad object state may crash in delayed function calls
if (skip) {
return true;
}
// Call submit-time functions to validate/update state
for (auto &function : cb_node->queue_submit_functions) {
skip |= function();
}
for (auto &function : cb_node->eventUpdates) {
skip |= function(queue);
}
for (auto &function : cb_node->queryUpdates) {
skip |= function(queue);
}
}
}
auto chained_device_group_struct = lvl_find_in_chain<VkDeviceGroupSubmitInfo>(submit->pNext);
if (chained_device_group_struct && chained_device_group_struct->commandBufferCount > 0) {
for (uint32_t i = 0; i < chained_device_group_struct->commandBufferCount; ++i) {
skip |= ValidateDeviceMaskToPhysicalDeviceCount(chained_device_group_struct->pCommandBufferDeviceMasks[i],
VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue),
"VUID-VkDeviceGroupSubmitInfo-pCommandBufferDeviceMasks-00086");
}
}
}
return skip;
}
void CoreChecks::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
if (enabled.gpu_validation && device_extensions.vk_ext_descriptor_indexing) {
GpuPreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
}
}
#ifdef VK_USE_PLATFORM_ANDROID_KHR
// Android-specific validation that uses types defined only on Android and only for NDK versions
// that support the VK_ANDROID_external_memory_android_hardware_buffer extension.
// This chunk could move into a seperate core_validation_android.cpp file... ?
// clang-format off
// Map external format and usage flags to/from equivalent Vulkan flags
// (Tables as of v1.1.92)
// AHardwareBuffer Format Vulkan Format
// ====================== =============
// AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM VK_FORMAT_R8G8B8A8_UNORM
// AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM VK_FORMAT_R8G8B8A8_UNORM
// AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM VK_FORMAT_R8G8B8_UNORM
// AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM VK_FORMAT_R5G6B5_UNORM_PACK16
// AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT VK_FORMAT_R16G16B16A16_SFLOAT
// AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM VK_FORMAT_A2B10G10R10_UNORM_PACK32
// AHARDWAREBUFFER_FORMAT_D16_UNORM VK_FORMAT_D16_UNORM
// AHARDWAREBUFFER_FORMAT_D24_UNORM VK_FORMAT_X8_D24_UNORM_PACK32
// AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT VK_FORMAT_D24_UNORM_S8_UINT
// AHARDWAREBUFFER_FORMAT_D32_FLOAT VK_FORMAT_D32_SFLOAT
// AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT VK_FORMAT_D32_SFLOAT_S8_UINT
// AHARDWAREBUFFER_FORMAT_S8_UINT VK_FORMAT_S8_UINT
// The AHARDWAREBUFFER_FORMAT_* are an enum in the NDK headers, but get passed in to Vulkan
// as uint32_t. Casting the enums here avoids scattering casts around in the code.
std::map<uint32_t, VkFormat> ahb_format_map_a2v = {
{ (uint32_t)AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM, VK_FORMAT_R8G8B8A8_UNORM },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM, VK_FORMAT_R8G8B8_UNORM },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM, VK_FORMAT_R5G6B5_UNORM_PACK16 },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32 },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_D16_UNORM, VK_FORMAT_D16_UNORM },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_D24_UNORM, VK_FORMAT_X8_D24_UNORM_PACK32 },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_D32_FLOAT, VK_FORMAT_D32_SFLOAT },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT },
{ (uint32_t)AHARDWAREBUFFER_FORMAT_S8_UINT, VK_FORMAT_S8_UINT }
};
// AHardwareBuffer Usage Vulkan Usage or Creation Flag (Intermixed - Aargh!)
// ===================== ===================================================
// None VK_IMAGE_USAGE_TRANSFER_SRC_BIT
// None VK_IMAGE_USAGE_TRANSFER_DST_BIT
// AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE VK_IMAGE_USAGE_SAMPLED_BIT
// AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT
// AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
// AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT
// AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE None
// AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT VK_IMAGE_CREATE_PROTECTED_BIT
// None VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT
// None VK_IMAGE_CREATE_EXTENDED_USAGE_BIT
// Same casting rationale. De-mixing the table to prevent type confusion and aliasing
std::map<uint64_t, VkImageUsageFlags> ahb_usage_map_a2v = {
{ (uint64_t)AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, (VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) },
{ (uint64_t)AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT },
{ (uint64_t)AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE, 0 }, // No equivalent
};
std::map<uint64_t, VkImageCreateFlags> ahb_create_map_a2v = {
{ (uint64_t)AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP, VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT },
{ (uint64_t)AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT, VK_IMAGE_CREATE_PROTECTED_BIT },
{ (uint64_t)AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE, 0 }, // No equivalent
};
std::map<VkImageUsageFlags, uint64_t> ahb_usage_map_v2a = {
{ VK_IMAGE_USAGE_SAMPLED_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE },
{ VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE },
{ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT },
};
std::map<VkImageCreateFlags, uint64_t> ahb_create_map_v2a = {
{ VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP },
{ VK_IMAGE_CREATE_PROTECTED_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT },
};
// clang-format on
//
// AHB-extension new APIs
//
bool CoreChecks::PreCallValidateGetAndroidHardwareBufferPropertiesANDROID(VkDevice device, const struct AHardwareBuffer *buffer,
VkAndroidHardwareBufferPropertiesANDROID *pProperties) {
bool skip = false;
// buffer must be a valid Android hardware buffer object with at least one of the AHARDWAREBUFFER_USAGE_GPU_* usage flags.
AHardwareBuffer_Desc ahb_desc;
AHardwareBuffer_describe(buffer, &ahb_desc);
uint32_t required_flags = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT |
AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE |
AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER;
if (0 == (ahb_desc.usage & required_flags)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-vkGetAndroidHardwareBufferPropertiesANDROID-buffer-01884",
"vkGetAndroidHardwareBufferPropertiesANDROID: The AHardwareBuffer's AHardwareBuffer_Desc.usage (0x%" PRIx64
") does not have any AHARDWAREBUFFER_USAGE_GPU_* flags set.",
ahb_desc.usage);
}
return skip;
}
void CoreChecks::PostCallRecordGetAndroidHardwareBufferPropertiesANDROID(VkDevice device, const struct AHardwareBuffer *buffer,
VkAndroidHardwareBufferPropertiesANDROID *pProperties,
VkResult result) {
if (VK_SUCCESS != result) return;
auto ahb_format_props = lvl_find_in_chain<VkAndroidHardwareBufferFormatPropertiesANDROID>(pProperties->pNext);
if (ahb_format_props) {
ahb_ext_formats_set.insert(ahb_format_props->externalFormat);
}
}
bool CoreChecks::PreCallValidateGetMemoryAndroidHardwareBufferANDROID(VkDevice device,
const VkMemoryGetAndroidHardwareBufferInfoANDROID *pInfo,
struct AHardwareBuffer **pBuffer) {
bool skip = false;
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(pInfo->memory);
// VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID must have been included in
// VkExportMemoryAllocateInfoKHR::handleTypes when memory was created.
if (!mem_info->is_export ||
(0 == (mem_info->export_handle_type_flags & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-handleTypes-01882",
"vkGetMemoryAndroidHardwareBufferANDROID: The VkDeviceMemory (%s) was not allocated for export, or the "
"export handleTypes (0x%" PRIx32
") did not contain VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID.",
report_data->FormatHandle(pInfo->memory).c_str(), mem_info->export_handle_type_flags);
}
// If the pNext chain of the VkMemoryAllocateInfo used to allocate memory included a VkMemoryDedicatedAllocateInfo
// with non-NULL image member, then that image must already be bound to memory.
if (mem_info->is_dedicated && (VK_NULL_HANDLE != mem_info->dedicated_image)) {
auto image_state = GetImageState(mem_info->dedicated_image);
if ((nullptr == image_state) || (0 == (image_state->GetBoundMemory().count(pInfo->memory)))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-pNext-01883",
"vkGetMemoryAndroidHardwareBufferANDROID: The VkDeviceMemory (%s) was allocated using a dedicated "
"image (%s), but that image is not bound to the VkDeviceMemory object.",
report_data->FormatHandle(pInfo->memory).c_str(),
report_data->FormatHandle(mem_info->dedicated_image).c_str());
}
}
return skip;
}
//
// AHB-specific validation within non-AHB APIs
//
bool CoreChecks::ValidateAllocateMemoryANDROID(const VkMemoryAllocateInfo *alloc_info) {
bool skip = false;
auto import_ahb_info = lvl_find_in_chain<VkImportAndroidHardwareBufferInfoANDROID>(alloc_info->pNext);
auto exp_mem_alloc_info = lvl_find_in_chain<VkExportMemoryAllocateInfo>(alloc_info->pNext);
auto mem_ded_alloc_info = lvl_find_in_chain<VkMemoryDedicatedAllocateInfo>(alloc_info->pNext);
if ((import_ahb_info) && (NULL != import_ahb_info->buffer)) {
// This is an import with handleType of VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID
AHardwareBuffer_Desc ahb_desc = {};
AHardwareBuffer_describe(import_ahb_info->buffer, &ahb_desc);
// If buffer is not NULL, it must be a valid Android hardware buffer object with AHardwareBuffer_Desc::format and
// AHardwareBuffer_Desc::usage compatible with Vulkan as described in Android Hardware Buffers.
//
// BLOB & GPU_DATA_BUFFER combo specifically allowed
if ((AHARDWAREBUFFER_FORMAT_BLOB != ahb_desc.format) || (0 == (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER))) {
// Otherwise, must be a combination from the AHardwareBuffer Format and Usage Equivalence tables
// Usage must have at least one bit from the table. It may have additional bits not in the table
uint64_t ahb_equiv_usage_bits = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT |
AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE |
AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT;
if ((0 == (ahb_desc.usage & ahb_equiv_usage_bits)) || (0 == ahb_format_map_a2v.count(ahb_desc.format))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkImportAndroidHardwareBufferInfoANDROID-buffer-01881",
"vkAllocateMemory: The AHardwareBuffer_Desc's format ( %u ) and/or usage ( 0x%" PRIx64
" ) are not compatible with Vulkan.",
ahb_desc.format, ahb_desc.usage);
}
}
// Collect external buffer info
VkPhysicalDeviceExternalBufferInfo pdebi = {};
pdebi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO;
pdebi.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
if (AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE & ahb_desc.usage) {
pdebi.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE];
}
if (AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT & ahb_desc.usage) {
pdebi.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT];
}
VkExternalBufferProperties ext_buf_props = {};
ext_buf_props.sType = VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES;
DispatchGetPhysicalDeviceExternalBufferProperties(physical_device, &pdebi, &ext_buf_props);
// Collect external format info
VkPhysicalDeviceExternalImageFormatInfo pdeifi = {};
pdeifi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;
pdeifi.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
VkPhysicalDeviceImageFormatInfo2 pdifi2 = {};
pdifi2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
pdifi2.pNext = &pdeifi;
if (0 < ahb_format_map_a2v.count(ahb_desc.format)) pdifi2.format = ahb_format_map_a2v[ahb_desc.format];
pdifi2.type = VK_IMAGE_TYPE_2D; // Seems likely
pdifi2.tiling = VK_IMAGE_TILING_OPTIMAL; // Ditto
if (AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE & ahb_desc.usage) {
pdifi2.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE];
}
if (AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT & ahb_desc.usage) {
pdifi2.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT];
}
if (AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP & ahb_desc.usage) {
pdifi2.flags |= ahb_create_map_a2v[AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP];
}
if (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT & ahb_desc.usage) {
pdifi2.flags |= ahb_create_map_a2v[AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT];
}
VkExternalImageFormatProperties ext_img_fmt_props = {};
ext_img_fmt_props.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES;
VkImageFormatProperties2 ifp2 = {};
ifp2.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
ifp2.pNext = &ext_img_fmt_props;
VkResult fmt_lookup_result = GetPDImageFormatProperties2(&pdifi2, &ifp2);
// If buffer is not NULL, Android hardware buffers must be supported for import, as reported by
// VkExternalImageFormatProperties or VkExternalBufferProperties.
if (0 == (ext_buf_props.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)) {
if ((VK_SUCCESS != fmt_lookup_result) || (0 == (ext_img_fmt_props.externalMemoryProperties.externalMemoryFeatures &
VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkImportAndroidHardwareBufferInfoANDROID-buffer-01880",
"vkAllocateMemory: Neither the VkExternalImageFormatProperties nor the VkExternalBufferProperties "
"structs for the AHardwareBuffer include the VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT flag.");
}
}
// Retrieve buffer and format properties of the provided AHardwareBuffer
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_format_props = {};
ahb_format_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
VkAndroidHardwareBufferPropertiesANDROID ahb_props = {};
ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
ahb_props.pNext = &ahb_format_props;
DispatchGetAndroidHardwareBufferPropertiesANDROID(device, import_ahb_info->buffer, &ahb_props);
// allocationSize must be the size returned by vkGetAndroidHardwareBufferPropertiesANDROID for the Android hardware buffer
if (alloc_info->allocationSize != ahb_props.allocationSize) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-allocationSize-02383",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID "
"struct, allocationSize (%" PRId64
") does not match the AHardwareBuffer's reported allocationSize (%" PRId64 ").",
alloc_info->allocationSize, ahb_props.allocationSize);
}
// memoryTypeIndex must be one of those returned by vkGetAndroidHardwareBufferPropertiesANDROID for the AHardwareBuffer
// Note: memoryTypeIndex is an index, memoryTypeBits is a bitmask
uint32_t mem_type_bitmask = 1 << alloc_info->memoryTypeIndex;
if (0 == (mem_type_bitmask & ahb_props.memoryTypeBits)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-memoryTypeIndex-02385",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID "
"struct, memoryTypeIndex (%" PRId32
") does not correspond to a bit set in AHardwareBuffer's reported "
"memoryTypeBits bitmask (0x%" PRIx32 ").",
alloc_info->memoryTypeIndex, ahb_props.memoryTypeBits);
}
// Checks for allocations without a dedicated allocation requirement
if ((nullptr == mem_ded_alloc_info) || (VK_NULL_HANDLE == mem_ded_alloc_info->image)) {
// the Android hardware buffer must have a format of AHARDWAREBUFFER_FORMAT_BLOB and a usage that includes
// AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER
if (((uint64_t)AHARDWAREBUFFER_FORMAT_BLOB != ahb_desc.format) ||
(0 == (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER))) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkMemoryAllocateInfo-pNext-02384",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID "
"struct without a dedicated allocation requirement, while the AHardwareBuffer_Desc's format ( %u ) is not "
"AHARDWAREBUFFER_FORMAT_BLOB or usage (0x%" PRIx64 ") does not include AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER.",
ahb_desc.format, ahb_desc.usage);
}
} else { // Checks specific to import with a dedicated allocation requirement
VkImageCreateInfo *ici = &(GetImageState(mem_ded_alloc_info->image)->createInfo);
// The Android hardware buffer's usage must include at least one of AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT or
// AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE
if (0 == (ahb_desc.usage & (AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE))) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkMemoryAllocateInfo-pNext-02386",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID and a "
"dedicated allocation requirement, while the AHardwareBuffer's usage (0x%" PRIx64
") contains neither AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT nor AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE.",
ahb_desc.usage);
}
// the format of image must be VK_FORMAT_UNDEFINED or the format returned by
// vkGetAndroidHardwareBufferPropertiesANDROID
if ((ici->format != ahb_format_props.format) && (VK_FORMAT_UNDEFINED != ici->format)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-pNext-02387",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained "
"VkImportAndroidHardwareBufferInfoANDROID, the dedicated allocation image's "
"format (%s) is not VK_FORMAT_UNDEFINED and does not match the AHardwareBuffer's format (%s).",
string_VkFormat(ici->format), string_VkFormat(ahb_format_props.format));
}
// The width, height, and array layer dimensions of image and the Android hardwarebuffer must be identical
if ((ici->extent.width != ahb_desc.width) || (ici->extent.height != ahb_desc.height) ||
(ici->arrayLayers != ahb_desc.layers)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-pNext-02388",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained "
"VkImportAndroidHardwareBufferInfoANDROID, the dedicated allocation image's "
"width, height, and arrayLayers (%" PRId32 " %" PRId32 " %" PRId32
") do not match those of the AHardwareBuffer (%" PRId32 " %" PRId32 " %" PRId32 ").",
ici->extent.width, ici->extent.height, ici->arrayLayers, ahb_desc.width, ahb_desc.height,
ahb_desc.layers);
}
// If the Android hardware buffer's usage includes AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE, the image must
// have either a full mipmap chain or exactly 1 mip level.
//
// NOTE! The language of this VUID contradicts the language in the spec (1.1.93), which says "The
// AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE flag does not correspond to a Vulkan image usage or creation flag. Instead,
// its presence indicates that the Android hardware buffer contains a complete mipmap chain, and its absence indicates
// that the Android hardware buffer contains only a single mip level."
//
// TODO: This code implements the VUID's meaning, but it seems likely that the spec text is actually correct.
// Clarification requested.
if ((ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE) && (ici->mipLevels != 1) &&
(ici->mipLevels != FullMipChainLevels(ici->extent))) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-pNext-02389",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID, "
"usage includes AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE but mipLevels (%" PRId32
") is neither 1 nor full mip "
"chain levels (%" PRId32 ").",
ici->mipLevels, FullMipChainLevels(ici->extent));
}
// each bit set in the usage of image must be listed in AHardwareBuffer Usage Equivalence, and if there is a
// corresponding AHARDWAREBUFFER_USAGE bit listed that bit must be included in the Android hardware buffer's
// AHardwareBuffer_Desc::usage
if (ici->usage &
~(VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-pNext-02390",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID, "
"dedicated image usage bits include one or more with no AHardwareBuffer equivalent.");
}
bool illegal_usage = false;
std::vector<VkImageUsageFlags> usages = {VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT};
for (VkImageUsageFlags ubit : usages) {
if (ici->usage & ubit) {
uint64_t ahb_usage = ahb_usage_map_v2a[ubit];
if (0 == (ahb_usage & ahb_desc.usage)) illegal_usage = true;
}
}
if (illegal_usage) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-pNext-02390",
"vkAllocateMemory: VkMemoryAllocateInfo struct with chained "
"VkImportAndroidHardwareBufferInfoANDROID, one or more AHardwareBuffer usage bits equivalent to "
"the provided image's usage bits are missing from AHardwareBuffer_Desc.usage.");
}
}
} else { // Not an import
if ((exp_mem_alloc_info) && (mem_ded_alloc_info) &&
(0 != (VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID & exp_mem_alloc_info->handleTypes)) &&
(VK_NULL_HANDLE != mem_ded_alloc_info->image)) {
// This is an Android HW Buffer export
if (0 != alloc_info->allocationSize) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateInfo-pNext-01874",
"vkAllocateMemory: pNext chain indicates a dedicated Android Hardware Buffer export allocation, "
"but allocationSize is non-zero.");
}
} else {
if (0 == alloc_info->allocationSize) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkMemoryAllocateInfo-pNext-01874",
"vkAllocateMemory: pNext chain does not indicate a dedicated export allocation, but allocationSize is 0.");
};
}
}
return skip;
}
bool CoreChecks::ValidateGetImageMemoryRequirements2ANDROID(const VkImage image) {
bool skip = false;
IMAGE_STATE *image_state = GetImageState(image);
if (image_state->imported_ahb && (0 == image_state->GetBoundMemory().size())) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image),
"VUID-VkImageMemoryRequirementsInfo2-image-01897",
"vkGetImageMemoryRequirements2: Attempt to query layout from an image created with "
"VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID handleType, which has not yet been "
"bound to memory.");
}
return skip;
}
static bool ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(const debug_report_data *report_data,
const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo,
const VkImageFormatProperties2 *pImageFormatProperties) {
bool skip = false;
const VkAndroidHardwareBufferUsageANDROID *ahb_usage =
lvl_find_in_chain<VkAndroidHardwareBufferUsageANDROID>(pImageFormatProperties->pNext);
if (nullptr != ahb_usage) {
const VkPhysicalDeviceExternalImageFormatInfo *pdeifi =
lvl_find_in_chain<VkPhysicalDeviceExternalImageFormatInfo>(pImageFormatInfo->pNext);
if ((nullptr == pdeifi) || (VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID != pdeifi->handleType)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkGetPhysicalDeviceImageFormatProperties2-pNext-01868",
"vkGetPhysicalDeviceImageFormatProperties2: pImageFormatProperties includes a chained "
"VkAndroidHardwareBufferUsageANDROID struct, but pImageFormatInfo does not include a chained "
"VkPhysicalDeviceExternalImageFormatInfo struct with handleType "
"VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID.");
}
}
return skip;
}
bool CoreChecks::ValidateCreateSamplerYcbcrConversionANDROID(const VkSamplerYcbcrConversionCreateInfo *create_info) {
const VkExternalFormatANDROID *ext_format_android = lvl_find_in_chain<VkExternalFormatANDROID>(create_info->pNext);
if ((nullptr != ext_format_android) && (0 != ext_format_android->externalFormat)) {
if (VK_FORMAT_UNDEFINED != create_info->format) {
return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, 0,
"VUID-VkSamplerYcbcrConversionCreateInfo-format-01904",
"vkCreateSamplerYcbcrConversion[KHR]: CreateInfo format is not VK_FORMAT_UNDEFINED while "
"there is a chained VkExternalFormatANDROID struct.");
}
} else if (VK_FORMAT_UNDEFINED == create_info->format) {
return log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, 0,
"VUID-VkSamplerYcbcrConversionCreateInfo-format-01904",
"vkCreateSamplerYcbcrConversion[KHR]: CreateInfo format is VK_FORMAT_UNDEFINED with no chained "
"VkExternalFormatANDROID struct.");
}
return false;
}
void CoreChecks::RecordCreateSamplerYcbcrConversionANDROID(const VkSamplerYcbcrConversionCreateInfo *create_info,
VkSamplerYcbcrConversion ycbcr_conversion) {
const VkExternalFormatANDROID *ext_format_android = lvl_find_in_chain<VkExternalFormatANDROID>(create_info->pNext);
if (ext_format_android && (0 != ext_format_android->externalFormat)) {
ycbcr_conversion_ahb_fmt_map.emplace(ycbcr_conversion, ext_format_android->externalFormat);
}
};
void CoreChecks::RecordDestroySamplerYcbcrConversionANDROID(VkSamplerYcbcrConversion ycbcr_conversion) {
ycbcr_conversion_ahb_fmt_map.erase(ycbcr_conversion);
};
#else // !VK_USE_PLATFORM_ANDROID_KHR
bool CoreChecks::ValidateAllocateMemoryANDROID(const VkMemoryAllocateInfo *alloc_info) { return false; }
static bool ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(const debug_report_data *report_data,
const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo,
const VkImageFormatProperties2 *pImageFormatProperties) {
return false;
}
bool CoreChecks::ValidateCreateSamplerYcbcrConversionANDROID(const VkSamplerYcbcrConversionCreateInfo *create_info) {
return false;
}
bool CoreChecks::ValidateGetImageMemoryRequirements2ANDROID(const VkImage image) { return false; }
void CoreChecks::RecordCreateSamplerYcbcrConversionANDROID(const VkSamplerYcbcrConversionCreateInfo *create_info,
VkSamplerYcbcrConversion ycbcr_conversion){};
void CoreChecks::RecordDestroySamplerYcbcrConversionANDROID(VkSamplerYcbcrConversion ycbcr_conversion){};
#endif // VK_USE_PLATFORM_ANDROID_KHR
bool CoreChecks::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
bool skip = false;
if (memObjMap.size() >= phys_dev_props.limits.maxMemoryAllocationCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
kVUIDUndefined, "Number of currently valid memory objects is not less than the maximum allowed (%u).",
phys_dev_props.limits.maxMemoryAllocationCount);
}
if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
skip |= ValidateAllocateMemoryANDROID(pAllocateInfo);
} else {
if (0 == pAllocateInfo->allocationSize) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkMemoryAllocateInfo-allocationSize-00638", "vkAllocateMemory: allocationSize is 0.");
};
}
auto chained_flags_struct = lvl_find_in_chain<VkMemoryAllocateFlagsInfo>(pAllocateInfo->pNext);
if (chained_flags_struct && chained_flags_struct->flags == VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT) {
skip |= ValidateDeviceMaskToPhysicalDeviceCount(chained_flags_struct->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateFlagsInfo-deviceMask-00675");
skip |= ValidateDeviceMaskToZero(chained_flags_struct->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkMemoryAllocateFlagsInfo-deviceMask-00676");
}
// TODO: VUIDs ending in 00643, 00644, 00646, 00647, 01742, 01743, 01745, 00645, 00648, 01744
return skip;
}
void CoreChecks::PostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory, VkResult result) {
if (VK_SUCCESS == result) {
AddMemObjInfo(device, *pMemory, pAllocateInfo);
}
return;
}
// For given obj node, if it is use, flag a validation error and return callback result, else return false
bool CoreChecks::ValidateObjectNotInUse(BASE_NODE *obj_node, VK_OBJECT obj_struct, const char *caller_name,
const char *error_code) {
if (disabled.object_in_use) return false;
bool skip = false;
if (obj_node->in_use.load()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, get_debug_report_enum[obj_struct.type], obj_struct.handle,
error_code, "Cannot call %s on %s %s that is currently in use by a command buffer.", caller_name,
object_string[obj_struct.type], report_data->FormatHandle(obj_struct.handle).c_str());
}
return skip;
}
bool CoreChecks::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory mem, const VkAllocationCallbacks *pAllocator) {
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem);
VK_OBJECT obj_struct = {HandleToUint64(mem), kVulkanObjectTypeDeviceMemory};
bool skip = false;
if (mem_info) {
skip |= ValidateObjectNotInUse(mem_info, obj_struct, "vkFreeMemory", "VUID-vkFreeMemory-memory-00677");
}
return skip;
}
void CoreChecks::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory mem, const VkAllocationCallbacks *pAllocator) {
if (!mem) return;
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem);
VK_OBJECT obj_struct = {HandleToUint64(mem), kVulkanObjectTypeDeviceMemory};
// Clear mem binding for any bound objects
for (auto obj : mem_info->obj_bindings) {
BINDABLE *bindable_state = nullptr;
switch (obj.type) {
case kVulkanObjectTypeImage:
bindable_state = GetImageState(reinterpret_cast<VkImage &>(obj.handle));
break;
case kVulkanObjectTypeBuffer:
bindable_state = GetBufferState(reinterpret_cast<VkBuffer &>(obj.handle));
break;
default:
// Should only have buffer or image objects bound to memory
assert(0);
}
assert(bindable_state);
bindable_state->binding.mem = MEMORY_UNBOUND;
bindable_state->UpdateBoundMemorySet();
}
// Any bound cmd buffers are now invalid
InvalidateCommandBuffers(mem_info->cb_bindings, obj_struct);
memObjMap.erase(mem);
}
// Validate that given Map memory range is valid. This means that the memory should not already be mapped,
// and that the size of the map range should be:
// 1. Not zero
// 2. Within the size of the memory allocation
bool CoreChecks::ValidateMapMemRange(VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size) {
bool skip = false;
if (size == 0) {
skip =
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem),
kVUID_Core_MemTrack_InvalidMap, "VkMapMemory: Attempting to map memory range of size zero");
}
auto mem_element = memObjMap.find(mem);
if (mem_element != memObjMap.end()) {
auto mem_info = mem_element->second.get();
// It is an application error to call VkMapMemory on an object that is already mapped
if (mem_info->mem_range.size != 0) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), kVUID_Core_MemTrack_InvalidMap,
"VkMapMemory: Attempting to map memory on an already-mapped object %s.",
report_data->FormatHandle(mem).c_str());
}
// Validate that offset + size is within object's allocationSize
if (size == VK_WHOLE_SIZE) {
if (offset >= mem_info->alloc_info.allocationSize) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), kVUID_Core_MemTrack_InvalidMap,
"Mapping Memory from 0x%" PRIx64 " to 0x%" PRIx64
" with size of VK_WHOLE_SIZE oversteps total array size 0x%" PRIx64,
offset, mem_info->alloc_info.allocationSize, mem_info->alloc_info.allocationSize);
}
} else {
if ((offset + size) > mem_info->alloc_info.allocationSize) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), "VUID-vkMapMemory-size-00681",
"Mapping Memory from 0x%" PRIx64 " to 0x%" PRIx64 " oversteps total array size 0x%" PRIx64 ".",
offset, size + offset, mem_info->alloc_info.allocationSize);
}
}
}
return skip;
}
void CoreChecks::StoreMemRanges(VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size) {
auto mem_info = GetDevMemState(mem);
if (mem_info) {
mem_info->mem_range.offset = offset;
mem_info->mem_range.size = size;
}
}
// Guard value for pad data
static char NoncoherentMemoryFillValue = 0xb;
void CoreChecks::InitializeAndTrackMemory(VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size, void **ppData) {
auto mem_info = GetDevMemState(mem);
if (mem_info) {
mem_info->p_driver_data = *ppData;
uint32_t index = mem_info->alloc_info.memoryTypeIndex;
if (phys_dev_mem_props.memoryTypes[index].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
mem_info->shadow_copy = 0;
} else {
if (size == VK_WHOLE_SIZE) {
size = mem_info->alloc_info.allocationSize - offset;
}
mem_info->shadow_pad_size = phys_dev_props.limits.minMemoryMapAlignment;
assert(SafeModulo(mem_info->shadow_pad_size, phys_dev_props.limits.minMemoryMapAlignment) == 0);
// Ensure start of mapped region reflects hardware alignment constraints
uint64_t map_alignment = phys_dev_props.limits.minMemoryMapAlignment;
// From spec: (ppData - offset) must be aligned to at least limits::minMemoryMapAlignment.
uint64_t start_offset = offset % map_alignment;
// Data passed to driver will be wrapped by a guardband of data to detect over- or under-writes.
mem_info->shadow_copy_base =
malloc(static_cast<size_t>(2 * mem_info->shadow_pad_size + size + map_alignment + start_offset));
mem_info->shadow_copy =
reinterpret_cast<char *>((reinterpret_cast<uintptr_t>(mem_info->shadow_copy_base) + map_alignment) &
~(map_alignment - 1)) +
start_offset;
assert(SafeModulo(reinterpret_cast<uintptr_t>(mem_info->shadow_copy) + mem_info->shadow_pad_size - start_offset,
map_alignment) == 0);
memset(mem_info->shadow_copy, NoncoherentMemoryFillValue, static_cast<size_t>(2 * mem_info->shadow_pad_size + size));
*ppData = static_cast<char *>(mem_info->shadow_copy) + mem_info->shadow_pad_size;
}
}
}
// Verify that state for fence being waited on is appropriate. That is,
// a fence being waited on should not already be signaled and
// it should have been submitted on a queue or during acquire next image
bool CoreChecks::VerifyWaitFenceState(VkFence fence, const char *apiCall) {
bool skip = false;
auto pFence = GetFenceState(fence);
if (pFence && pFence->scope == kSyncScopeInternal) {
if (pFence->state == FENCE_UNSIGNALED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
HandleToUint64(fence), kVUID_Core_MemTrack_FenceState,
"%s called for fence %s which has not been submitted on a Queue or during acquire next image.", apiCall,
report_data->FormatHandle(fence).c_str());
}
}
return skip;
}
void CoreChecks::RetireFence(VkFence fence) {
auto pFence = GetFenceState(fence);
if (pFence && pFence->scope == kSyncScopeInternal) {
if (pFence->signaler.first != VK_NULL_HANDLE) {
// Fence signaller is a queue -- use this as proof that prior operations on that queue have completed.
RetireWorkOnQueue(GetQueueState(pFence->signaler.first), pFence->signaler.second);
} else {
// Fence signaller is the WSI. We're not tracking what the WSI op actually /was/ in CV yet, but we need to mark
// the fence as retired.
pFence->state = FENCE_RETIRED;
}
}
}
bool CoreChecks::PreCallValidateWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll,
uint64_t timeout) {
// Verify fence status of submitted fences
bool skip = false;
for (uint32_t i = 0; i < fenceCount; i++) {
skip |= VerifyWaitFenceState(pFences[i], "vkWaitForFences");
skip |= VerifyQueueStateToFence(pFences[i]);
}
return skip;
}
void CoreChecks::PostCallRecordWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll,
uint64_t timeout, VkResult result) {
if (VK_SUCCESS != result) return;
// When we know that all fences are complete we can clean/remove their CBs
if ((VK_TRUE == waitAll) || (1 == fenceCount)) {
for (uint32_t i = 0; i < fenceCount; i++) {
RetireFence(pFences[i]);
}
}
// NOTE : Alternate case not handled here is when some fences have completed. In
// this case for app to guarantee which fences completed it will have to call
// vkGetFenceStatus() at which point we'll clean/remove their CBs if complete.
}
bool CoreChecks::PreCallValidateGetFenceStatus(VkDevice device, VkFence fence) {
return VerifyWaitFenceState(fence, "vkGetFenceStatus()");
}
void CoreChecks::PostCallRecordGetFenceStatus(VkDevice device, VkFence fence, VkResult result) {
if (VK_SUCCESS != result) return;
RetireFence(fence);
}
void CoreChecks::RecordGetDeviceQueueState(uint32_t queue_family_index, VkQueue queue) {
// Add queue to tracking set only if it is new
auto queue_is_new = queues.emplace(queue);
if (queue_is_new.second == true) {
QUEUE_STATE *queue_state = &queueMap[queue];
queue_state->queue = queue;
queue_state->queueFamilyIndex = queue_family_index;
queue_state->seq = 0;
}
}
bool CoreChecks::ValidateGetDeviceQueue(uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue *pQueue, const char *valid_qfi_vuid,
const char *qfi_in_range_vuid) {
bool skip = false;
skip |= ValidateDeviceQueueFamily(queueFamilyIndex, "vkGetDeviceQueue", "queueFamilyIndex", valid_qfi_vuid);
const auto &queue_data = queue_family_index_map.find(queueFamilyIndex);
if (queue_data != queue_family_index_map.end() && queue_data->second <= queueIndex) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
qfi_in_range_vuid,
"vkGetDeviceQueue: queueIndex (=%" PRIu32
") is not less than the number of queues requested from queueFamilyIndex (=%" PRIu32
") when the device was created (i.e. is not less than %" PRIu32 ").",
queueIndex, queueFamilyIndex, queue_data->second);
}
return skip;
}
bool CoreChecks::PreCallValidateGetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue *pQueue) {
return ValidateGetDeviceQueue(queueFamilyIndex, queueIndex, pQueue, "VUID-vkGetDeviceQueue-queueFamilyIndex-00384",
"VUID-vkGetDeviceQueue-queueIndex-00385");
}
void CoreChecks::PostCallRecordGetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue *pQueue) {
RecordGetDeviceQueueState(queueFamilyIndex, *pQueue);
}
void CoreChecks::PostCallRecordGetDeviceQueue2(VkDevice device, const VkDeviceQueueInfo2 *pQueueInfo, VkQueue *pQueue) {
RecordGetDeviceQueueState(pQueueInfo->queueFamilyIndex, *pQueue);
}
bool CoreChecks::PreCallValidateQueueWaitIdle(VkQueue queue) {
QUEUE_STATE *queue_state = GetQueueState(queue);
return VerifyQueueStateToSeq(queue_state, queue_state->seq + queue_state->submissions.size());
}
void CoreChecks::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
if (VK_SUCCESS != result) return;
QUEUE_STATE *queue_state = GetQueueState(queue);
RetireWorkOnQueue(queue_state, queue_state->seq + queue_state->submissions.size());
}
bool CoreChecks::PreCallValidateDeviceWaitIdle(VkDevice device) {
bool skip = false;
for (auto &queue : queueMap) {
skip |= VerifyQueueStateToSeq(&queue.second, queue.second.seq + queue.second.submissions.size());
}
return skip;
}
void CoreChecks::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
if (VK_SUCCESS != result) return;
for (auto &queue : queueMap) {
RetireWorkOnQueue(&queue.second, queue.second.seq + queue.second.submissions.size());
}
}
bool CoreChecks::PreCallValidateDestroyFence(VkDevice device, VkFence fence, const VkAllocationCallbacks *pAllocator) {
FENCE_STATE *fence_node = GetFenceState(fence);
bool skip = false;
if (fence_node) {
if (fence_node->scope == kSyncScopeInternal && fence_node->state == FENCE_INFLIGHT) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence),
"VUID-vkDestroyFence-fence-01120", "Fence %s is in use.", report_data->FormatHandle(fence).c_str());
}
}
return skip;
}
void CoreChecks::PreCallRecordDestroyFence(VkDevice device, VkFence fence, const VkAllocationCallbacks *pAllocator) {
if (!fence) return;
fenceMap.erase(fence);
}
bool CoreChecks::PreCallValidateDestroySemaphore(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks *pAllocator) {
SEMAPHORE_STATE *sema_node = GetSemaphoreState(semaphore);
VK_OBJECT obj_struct = {HandleToUint64(semaphore), kVulkanObjectTypeSemaphore};
bool skip = false;
if (sema_node) {
skip |= ValidateObjectNotInUse(sema_node, obj_struct, "vkDestroySemaphore", "VUID-vkDestroySemaphore-semaphore-01137");
}
return skip;
}
void CoreChecks::PreCallRecordDestroySemaphore(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks *pAllocator) {
if (!semaphore) return;
semaphoreMap.erase(semaphore);
}
bool CoreChecks::PreCallValidateDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
EVENT_STATE *event_state = GetEventState(event);
VK_OBJECT obj_struct = {HandleToUint64(event), kVulkanObjectTypeEvent};
bool skip = false;
if (event_state) {
skip |= ValidateObjectNotInUse(event_state, obj_struct, "vkDestroyEvent", "VUID-vkDestroyEvent-event-01145");
}
return skip;
}
void CoreChecks::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
if (!event) return;
EVENT_STATE *event_state = GetEventState(event);
VK_OBJECT obj_struct = {HandleToUint64(event), kVulkanObjectTypeEvent};
InvalidateCommandBuffers(event_state->cb_bindings, obj_struct);
eventMap.erase(event);
}
bool CoreChecks::PreCallValidateDestroyQueryPool(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks *pAllocator) {
if (disabled.query_validation) return false;
QUERY_POOL_STATE *qp_state = GetQueryPoolState(queryPool);
VK_OBJECT obj_struct = {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool};
bool skip = false;
if (qp_state) {
skip |= ValidateObjectNotInUse(qp_state, obj_struct, "vkDestroyQueryPool", "VUID-vkDestroyQueryPool-queryPool-00793");
}
return skip;
}
void CoreChecks::PreCallRecordDestroyQueryPool(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks *pAllocator) {
if (!queryPool) return;
QUERY_POOL_STATE *qp_state = GetQueryPoolState(queryPool);
VK_OBJECT obj_struct = {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool};
InvalidateCommandBuffers(qp_state->cb_bindings, obj_struct);
queryPoolMap.erase(queryPool);
}
bool CoreChecks::PreCallValidateGetQueryPoolResults(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery,
uint32_t queryCount, size_t dataSize, void *pData, VkDeviceSize stride,
VkQueryResultFlags flags) {
if (disabled.query_validation) return false;
bool skip = false;
auto query_pool_state = queryPoolMap.find(queryPool);
if (query_pool_state != queryPoolMap.end()) {
if ((query_pool_state->second->createInfo.queryType == VK_QUERY_TYPE_TIMESTAMP) && (flags & VK_QUERY_RESULT_PARTIAL_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0,
"VUID-vkGetQueryPoolResults-queryType-00818",
"QueryPool %s was created with a queryType of VK_QUERY_TYPE_TIMESTAMP but flags contains "
"VK_QUERY_RESULT_PARTIAL_BIT.",
report_data->FormatHandle(queryPool).c_str());
}
}
return skip;
}
void CoreChecks::PostCallRecordGetQueryPoolResults(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount,
size_t dataSize, void *pData, VkDeviceSize stride, VkQueryResultFlags flags,
VkResult result) {
if ((VK_SUCCESS != result) && (VK_NOT_READY != result)) return;
// TODO: clean this up, it's insanely wasteful.
unordered_map<QueryObject, std::vector<VkCommandBuffer>> queries_in_flight;
for (auto &cmd_buffer : commandBufferMap) {
if (cmd_buffer.second->in_use.load()) {
for (auto query_state_pair : cmd_buffer.second->queryToStateMap) {
queries_in_flight[query_state_pair.first].push_back(cmd_buffer.first);
}
}
}
for (uint32_t i = 0; i < queryCount; ++i) {
QueryObject query = {queryPool, firstQuery + i};
auto qif_pair = queries_in_flight.find(query);
auto query_state_pair = queryToStateMap.find(query);
if (query_state_pair != queryToStateMap.end()) {
// Available and in flight
if (qif_pair != queries_in_flight.end() && query_state_pair != queryToStateMap.end() && query_state_pair->second) {
for (auto cmd_buffer : qif_pair->second) {
auto cb = GetCBState(cmd_buffer);
auto query_event_pair = cb->waitedEventsBeforeQueryReset.find(query);
if (query_event_pair != cb->waitedEventsBeforeQueryReset.end()) {
for (auto event : query_event_pair->second) {
eventMap[event].needsSignaled = true;
}
}
}
}
}
}
}
// Return true if given ranges intersect, else false
// Prereq : For both ranges, range->end - range->start > 0. This case should have already resulted
// in an error so not checking that here
// pad_ranges bool indicates a linear and non-linear comparison which requires padding
// In the case where padding is required, if an alias is encountered then a validation error is reported and skip
// may be set by the callback function so caller should merge in skip value if padding case is possible.
// This check can be skipped by passing skip_checks=true, for call sites outside the validation path.
bool CoreChecks::RangesIntersect(MEMORY_RANGE const *range1, MEMORY_RANGE const *range2, bool *skip, bool skip_checks) {
*skip = false;
auto r1_start = range1->start;
auto r1_end = range1->end;
auto r2_start = range2->start;
auto r2_end = range2->end;
VkDeviceSize pad_align = 1;
if (range1->linear != range2->linear) {
pad_align = phys_dev_props.limits.bufferImageGranularity;
}
if ((r1_end & ~(pad_align - 1)) < (r2_start & ~(pad_align - 1))) return false;
if ((r1_start & ~(pad_align - 1)) > (r2_end & ~(pad_align - 1))) return false;
if (!skip_checks && (range1->linear != range2->linear)) {
// In linear vs. non-linear case, warn of aliasing
const char *r1_linear_str = range1->linear ? "Linear" : "Non-linear";
const char *r1_type_str = range1->image ? "image" : "buffer";
const char *r2_linear_str = range2->linear ? "linear" : "non-linear";
const char *r2_type_str = range2->image ? "image" : "buffer";
auto obj_type = range1->image ? VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT : VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT;
*skip |= log_msg(
report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, obj_type, range1->handle, kVUID_Core_MemTrack_InvalidAliasing,
"%s %s %s is aliased with %s %s %s which may indicate a bug. For further info refer to the Buffer-Image Granularity "
"section of the Vulkan specification. "
"(https://www.khronos.org/registry/vulkan/specs/1.0-extensions/xhtml/vkspec.html#resources-bufferimagegranularity)",
r1_linear_str, r1_type_str, report_data->FormatHandle(range1->handle).c_str(), r2_linear_str, r2_type_str,
report_data->FormatHandle(range2->handle).c_str());
}
// Ranges intersect
return true;
}
// Simplified RangesIntersect that calls above function to check range1 for intersection with offset & end addresses
bool CoreChecks::RangesIntersect(MEMORY_RANGE const *range1, VkDeviceSize offset, VkDeviceSize end) {
// Create a local MEMORY_RANGE struct to wrap offset/size
MEMORY_RANGE range_wrap;
// Synch linear with range1 to avoid padding and potential validation error case
range_wrap.linear = range1->linear;
range_wrap.start = offset;
range_wrap.end = end;
bool tmp_bool;
return RangesIntersect(range1, &range_wrap, &tmp_bool, true);
}
bool CoreChecks::ValidateInsertMemoryRange(uint64_t handle, DEVICE_MEMORY_STATE *mem_info, VkDeviceSize memoryOffset,
VkMemoryRequirements memRequirements, bool is_image, bool is_linear,
const char *api_name) {
bool skip = false;
MEMORY_RANGE range;
range.image = is_image;
range.handle = handle;
range.linear = is_linear;
range.memory = mem_info->mem;
range.start = memoryOffset;
range.size = memRequirements.size;
range.end = memoryOffset + memRequirements.size - 1;
range.aliases.clear();
// Check for aliasing problems.
for (auto &obj_range_pair : mem_info->bound_ranges) {
auto check_range = &obj_range_pair.second;
bool intersection_error = false;
if (RangesIntersect(&range, check_range, &intersection_error, false)) {
skip |= intersection_error;
range.aliases.insert(check_range);
}
}
if (memoryOffset >= mem_info->alloc_info.allocationSize) {
const char *error_code =
is_image ? "VUID-vkBindImageMemory-memoryOffset-01046" : "VUID-vkBindBufferMemory-memoryOffset-01031";
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem_info->mem), error_code,
"In %s, attempting to bind memory (%s) to object (%s), memoryOffset=0x%" PRIxLEAST64
" must be less than the memory allocation size 0x%" PRIxLEAST64 ".",
api_name, report_data->FormatHandle(mem_info->mem).c_str(), report_data->FormatHandle(handle).c_str(),
memoryOffset, mem_info->alloc_info.allocationSize);
}
return skip;
}
// Object with given handle is being bound to memory w/ given mem_info struct.
// Track the newly bound memory range with given memoryOffset
// Also scan any previous ranges, track aliased ranges with new range, and flag an error if a linear
// and non-linear range incorrectly overlap.
// Return true if an error is flagged and the user callback returns "true", otherwise false
// is_image indicates an image object, otherwise handle is for a buffer
// is_linear indicates a buffer or linear image
void CoreChecks::InsertMemoryRange(uint64_t handle, DEVICE_MEMORY_STATE *mem_info, VkDeviceSize memoryOffset,
VkMemoryRequirements memRequirements, bool is_image, bool is_linear) {
MEMORY_RANGE range;
range.image = is_image;
range.handle = handle;
range.linear = is_linear;
range.memory = mem_info->mem;
range.start = memoryOffset;
range.size = memRequirements.size;
range.end = memoryOffset + memRequirements.size - 1;
range.aliases.clear();
// Update Memory aliasing
// Save aliased ranges so we can copy into final map entry below. Can't do it in loop b/c we don't yet have final ptr. If we
// inserted into map before loop to get the final ptr, then we may enter loop when not needed & we check range against itself
std::unordered_set<MEMORY_RANGE *> tmp_alias_ranges;
for (auto &obj_range_pair : mem_info->bound_ranges) {
auto check_range = &obj_range_pair.second;
bool intersection_error = false;
if (RangesIntersect(&range, check_range, &intersection_error, true)) {
range.aliases.insert(check_range);
tmp_alias_ranges.insert(check_range);
}
}
mem_info->bound_ranges[handle] = std::move(range);
for (auto tmp_range : tmp_alias_ranges) {
tmp_range->aliases.insert(&mem_info->bound_ranges[handle]);
}
if (is_image)
mem_info->bound_images.insert(handle);
else
mem_info->bound_buffers.insert(handle);
}
bool CoreChecks::ValidateInsertImageMemoryRange(VkImage image, DEVICE_MEMORY_STATE *mem_info, VkDeviceSize mem_offset,
VkMemoryRequirements mem_reqs, bool is_linear, const char *api_name) {
return ValidateInsertMemoryRange(HandleToUint64(image), mem_info, mem_offset, mem_reqs, true, is_linear, api_name);
}
void CoreChecks::InsertImageMemoryRange(VkImage image, DEVICE_MEMORY_STATE *mem_info, VkDeviceSize mem_offset,
VkMemoryRequirements mem_reqs, bool is_linear) {
InsertMemoryRange(HandleToUint64(image), mem_info, mem_offset, mem_reqs, true, is_linear);
}
bool CoreChecks::ValidateInsertBufferMemoryRange(VkBuffer buffer, DEVICE_MEMORY_STATE *mem_info, VkDeviceSize mem_offset,
VkMemoryRequirements mem_reqs, const char *api_name) {
return ValidateInsertMemoryRange(HandleToUint64(buffer), mem_info, mem_offset, mem_reqs, false, true, api_name);
}
void CoreChecks::InsertBufferMemoryRange(VkBuffer buffer, DEVICE_MEMORY_STATE *mem_info, VkDeviceSize mem_offset,
VkMemoryRequirements mem_reqs) {
InsertMemoryRange(HandleToUint64(buffer), mem_info, mem_offset, mem_reqs, false, true);
}
// Remove MEMORY_RANGE struct for give handle from bound_ranges of mem_info
// is_image indicates if handle is for image or buffer
// This function will also remove the handle-to-index mapping from the appropriate
// map and clean up any aliases for range being removed.
static void RemoveMemoryRange(uint64_t handle, DEVICE_MEMORY_STATE *mem_info, bool is_image) {
auto erase_range = &mem_info->bound_ranges[handle];
for (auto alias_range : erase_range->aliases) {
alias_range->aliases.erase(erase_range);
}
erase_range->aliases.clear();
mem_info->bound_ranges.erase(handle);
if (is_image) {
mem_info->bound_images.erase(handle);
} else {
mem_info->bound_buffers.erase(handle);
}
}
void CoreChecks::RemoveBufferMemoryRange(uint64_t handle, DEVICE_MEMORY_STATE *mem_info) {
RemoveMemoryRange(handle, mem_info, false);
}
void CoreChecks::RemoveImageMemoryRange(uint64_t handle, DEVICE_MEMORY_STATE *mem_info) {
RemoveMemoryRange(handle, mem_info, true);
}
bool CoreChecks::ValidateMemoryTypes(const DEVICE_MEMORY_STATE *mem_info, const uint32_t memory_type_bits, const char *funcName,
const char *msgCode) {
bool skip = false;
if (((1 << mem_info->alloc_info.memoryTypeIndex) & memory_type_bits) == 0) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem_info->mem), msgCode,
"%s(): MemoryRequirements->memoryTypeBits (0x%X) for this object type are not compatible with the memory "
"type (0x%X) of this memory object %s.",
funcName, memory_type_bits, mem_info->alloc_info.memoryTypeIndex,
report_data->FormatHandle(mem_info->mem).c_str());
}
return skip;
}
bool CoreChecks::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset, const char *api_name) {
BUFFER_STATE *buffer_state = GetBufferState(buffer);
bool skip = false;
if (buffer_state) {
// Track objects tied to memory
uint64_t buffer_handle = HandleToUint64(buffer);
skip = ValidateSetMemBinding(mem, buffer_handle, kVulkanObjectTypeBuffer, api_name);
if (!buffer_state->memory_requirements_checked) {
// There's not an explicit requirement in the spec to call vkGetBufferMemoryRequirements() prior to calling
// BindBufferMemory, but it's implied in that memory being bound must conform with VkMemoryRequirements from
// vkGetBufferMemoryRequirements()
skip |=
log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle,
kVUID_Core_DrawState_InvalidBuffer,
"%s: Binding memory to buffer %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
api_name, report_data->FormatHandle(buffer_handle).c_str());
// Make the call for them so we can verify the state
DispatchGetBufferMemoryRequirements(device, buffer, &buffer_state->requirements);
}
// Validate bound memory range information
const auto mem_info = GetDevMemState(mem);
if (mem_info) {
skip |= ValidateInsertBufferMemoryRange(buffer, mem_info, memoryOffset, buffer_state->requirements, api_name);
skip |= ValidateMemoryTypes(mem_info, buffer_state->requirements.memoryTypeBits, api_name,
"VUID-vkBindBufferMemory-memory-01035");
}
// Validate memory requirements alignment
if (SafeModulo(memoryOffset, buffer_state->requirements.alignment) != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle,
"VUID-vkBindBufferMemory-memoryOffset-01036",
"%s: memoryOffset is 0x%" PRIxLEAST64
" but must be an integer multiple of the VkMemoryRequirements::alignment value 0x%" PRIxLEAST64
", returned from a call to vkGetBufferMemoryRequirements with buffer.",
api_name, memoryOffset, buffer_state->requirements.alignment);
}
if (mem_info) {
// Validate memory requirements size
if (buffer_state->requirements.size > (mem_info->alloc_info.allocationSize - memoryOffset)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle,
"VUID-vkBindBufferMemory-size-01037",
"%s: memory size minus memoryOffset is 0x%" PRIxLEAST64
" but must be at least as large as VkMemoryRequirements::size value 0x%" PRIxLEAST64
", returned from a call to vkGetBufferMemoryRequirements with buffer.",
api_name, mem_info->alloc_info.allocationSize - memoryOffset, buffer_state->requirements.size);
}
// Validate dedicated allocation
if (mem_info->is_dedicated && ((mem_info->dedicated_buffer != buffer) || (memoryOffset != 0))) {
// TODO: Add vkBindBufferMemory2KHR error message when added to spec.
auto validation_error = kVUIDUndefined;
if (strcmp(api_name, "vkBindBufferMemory()") == 0) {
validation_error = "VUID-vkBindBufferMemory-memory-01508";
}
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle,
validation_error,
"%s: for dedicated memory allocation %s, VkMemoryDedicatedAllocateInfoKHR::buffer %s must be equal "
"to buffer %s and memoryOffset 0x%" PRIxLEAST64 " must be zero.",
api_name, report_data->FormatHandle(mem).c_str(),
report_data->FormatHandle(mem_info->dedicated_buffer).c_str(),
report_data->FormatHandle(buffer_handle).c_str(), memoryOffset);
}
}
}
return skip;
}
bool CoreChecks::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset) {
const char *api_name = "vkBindBufferMemory()";
return ValidateBindBufferMemory(buffer, mem, memoryOffset, api_name);
}
void CoreChecks::UpdateBindBufferMemoryState(VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset) {
BUFFER_STATE *buffer_state = GetBufferState(buffer);
if (buffer_state) {
// Track bound memory range information
auto mem_info = GetDevMemState(mem);
if (mem_info) {
InsertBufferMemoryRange(buffer, mem_info, memoryOffset, buffer_state->requirements);
}
// Track objects tied to memory
uint64_t buffer_handle = HandleToUint64(buffer);
SetMemBinding(mem, buffer_state, memoryOffset, buffer_handle, kVulkanObjectTypeBuffer);
}
}
void CoreChecks::PostCallRecordBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset,
VkResult result) {
if (VK_SUCCESS != result) return;
UpdateBindBufferMemoryState(buffer, mem, memoryOffset);
}
bool CoreChecks::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
const VkBindBufferMemoryInfoKHR *pBindInfos) {
char api_name[64];
bool skip = false;
for (uint32_t i = 0; i < bindInfoCount; i++) {
sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name);
}
return skip;
}
bool CoreChecks::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
const VkBindBufferMemoryInfoKHR *pBindInfos) {
char api_name[64];
bool skip = false;
for (uint32_t i = 0; i < bindInfoCount; i++) {
sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name);
}
return skip;
}
void CoreChecks::PostCallRecordBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
const VkBindBufferMemoryInfoKHR *pBindInfos, VkResult result) {
for (uint32_t i = 0; i < bindInfoCount; i++) {
UpdateBindBufferMemoryState(pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset);
}
}
void CoreChecks::PostCallRecordBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
const VkBindBufferMemoryInfoKHR *pBindInfos, VkResult result) {
for (uint32_t i = 0; i < bindInfoCount; i++) {
UpdateBindBufferMemoryState(pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset);
}
}
void CoreChecks::RecordGetBufferMemoryRequirementsState(VkBuffer buffer, VkMemoryRequirements *pMemoryRequirements) {
BUFFER_STATE *buffer_state = GetBufferState(buffer);
if (buffer_state) {
buffer_state->requirements = *pMemoryRequirements;
buffer_state->memory_requirements_checked = true;
}
}
void CoreChecks::PostCallRecordGetBufferMemoryRequirements(VkDevice device, VkBuffer buffer,
VkMemoryRequirements *pMemoryRequirements) {
RecordGetBufferMemoryRequirementsState(buffer, pMemoryRequirements);
}
void CoreChecks::PostCallRecordGetBufferMemoryRequirements2(VkDevice device, const VkBufferMemoryRequirementsInfo2KHR *pInfo,
VkMemoryRequirements2KHR *pMemoryRequirements) {
RecordGetBufferMemoryRequirementsState(pInfo->buffer, &pMemoryRequirements->memoryRequirements);
}
void CoreChecks::PostCallRecordGetBufferMemoryRequirements2KHR(VkDevice device, const VkBufferMemoryRequirementsInfo2KHR *pInfo,
VkMemoryRequirements2KHR *pMemoryRequirements) {
RecordGetBufferMemoryRequirementsState(pInfo->buffer, &pMemoryRequirements->memoryRequirements);
}
bool CoreChecks::ValidateGetImageMemoryRequirements2(const VkImageMemoryRequirementsInfo2 *pInfo) {
bool skip = false;
if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
skip |= ValidateGetImageMemoryRequirements2ANDROID(pInfo->image);
}
return skip;
}
bool CoreChecks::PreCallValidateGetImageMemoryRequirements2(VkDevice device, const VkImageMemoryRequirementsInfo2 *pInfo,
VkMemoryRequirements2 *pMemoryRequirements) {
return ValidateGetImageMemoryRequirements2(pInfo);
}
bool CoreChecks::PreCallValidateGetImageMemoryRequirements2KHR(VkDevice device, const VkImageMemoryRequirementsInfo2 *pInfo,
VkMemoryRequirements2 *pMemoryRequirements) {
return ValidateGetImageMemoryRequirements2(pInfo);
}
void CoreChecks::RecordGetImageMemoryRequiementsState(VkImage image, VkMemoryRequirements *pMemoryRequirements) {
IMAGE_STATE *image_state = GetImageState(image);
if (image_state) {
image_state->requirements = *pMemoryRequirements;
image_state->memory_requirements_checked = true;
}
}
void CoreChecks::PostCallRecordGetImageMemoryRequirements(VkDevice device, VkImage image,
VkMemoryRequirements *pMemoryRequirements) {
RecordGetImageMemoryRequiementsState(image, pMemoryRequirements);
}
void CoreChecks::PostCallRecordGetImageMemoryRequirements2(VkDevice device, const VkImageMemoryRequirementsInfo2 *pInfo,
VkMemoryRequirements2 *pMemoryRequirements) {
RecordGetImageMemoryRequiementsState(pInfo->image, &pMemoryRequirements->memoryRequirements);
}
void CoreChecks::PostCallRecordGetImageMemoryRequirements2KHR(VkDevice device, const VkImageMemoryRequirementsInfo2 *pInfo,
VkMemoryRequirements2 *pMemoryRequirements) {
RecordGetImageMemoryRequiementsState(pInfo->image, &pMemoryRequirements->memoryRequirements);
}
static void RecordGetImageSparseMemoryRequirementsState(IMAGE_STATE *image_state,
VkSparseImageMemoryRequirements *sparse_image_memory_requirements) {
image_state->sparse_requirements.emplace_back(*sparse_image_memory_requirements);
if (sparse_image_memory_requirements->formatProperties.aspectMask & VK_IMAGE_ASPECT_METADATA_BIT) {
image_state->sparse_metadata_required = true;
}
}
void CoreChecks::PostCallRecordGetImageSparseMemoryRequirements(VkDevice device, VkImage image,
uint32_t *pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements *pSparseMemoryRequirements) {
auto image_state = GetImageState(image);
image_state->get_sparse_reqs_called = true;
if (!pSparseMemoryRequirements) return;
for (uint32_t i = 0; i < *pSparseMemoryRequirementCount; i++) {
RecordGetImageSparseMemoryRequirementsState(image_state, &pSparseMemoryRequirements[i]);
}
}
void CoreChecks::PostCallRecordGetImageSparseMemoryRequirements2(VkDevice device,
const VkImageSparseMemoryRequirementsInfo2KHR *pInfo,
uint32_t *pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements2KHR *pSparseMemoryRequirements) {
auto image_state = GetImageState(pInfo->image);
image_state->get_sparse_reqs_called = true;
if (!pSparseMemoryRequirements) return;
for (uint32_t i = 0; i < *pSparseMemoryRequirementCount; i++) {
assert(!pSparseMemoryRequirements[i].pNext); // TODO: If an extension is ever added here we need to handle it
RecordGetImageSparseMemoryRequirementsState(image_state, &pSparseMemoryRequirements[i].memoryRequirements);
}
}
void CoreChecks::PostCallRecordGetImageSparseMemoryRequirements2KHR(
VkDevice device, const VkImageSparseMemoryRequirementsInfo2KHR *pInfo, uint32_t *pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements2KHR *pSparseMemoryRequirements) {
auto image_state = GetImageState(pInfo->image);
image_state->get_sparse_reqs_called = true;
if (!pSparseMemoryRequirements) return;
for (uint32_t i = 0; i < *pSparseMemoryRequirementCount; i++) {
assert(!pSparseMemoryRequirements[i].pNext); // TODO: If an extension is ever added here we need to handle it
RecordGetImageSparseMemoryRequirementsState(image_state, &pSparseMemoryRequirements[i].memoryRequirements);
}
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceImageFormatProperties2(VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo,
VkImageFormatProperties2 *pImageFormatProperties) {
// Can't wrap AHB-specific validation in a device extension check here, but no harm
bool skip = ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(report_data, pImageFormatInfo, pImageFormatProperties);
return skip;
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceImageFormatProperties2KHR(VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo,
VkImageFormatProperties2 *pImageFormatProperties) {
// Can't wrap AHB-specific validation in a device extension check here, but no harm
bool skip = ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(report_data, pImageFormatInfo, pImageFormatProperties);
return skip;
}
void CoreChecks::PreCallRecordDestroyShaderModule(VkDevice device, VkShaderModule shaderModule,
const VkAllocationCallbacks *pAllocator) {
if (!shaderModule) return;
shaderModuleMap.erase(shaderModule);
}
bool CoreChecks::PreCallValidateDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator) {
PIPELINE_STATE *pipeline_state = GetPipelineState(pipeline);
VK_OBJECT obj_struct = {HandleToUint64(pipeline), kVulkanObjectTypePipeline};
bool skip = false;
if (pipeline_state) {
skip |= ValidateObjectNotInUse(pipeline_state, obj_struct, "vkDestroyPipeline", "VUID-vkDestroyPipeline-pipeline-00765");
}
return skip;
}
void CoreChecks::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator) {
if (!pipeline) return;
PIPELINE_STATE *pipeline_state = GetPipelineState(pipeline);
VK_OBJECT obj_struct = {HandleToUint64(pipeline), kVulkanObjectTypePipeline};
// Any bound cmd buffers are now invalid
InvalidateCommandBuffers(pipeline_state->cb_bindings, obj_struct);
if (enabled.gpu_validation) {
GpuPreCallRecordDestroyPipeline(pipeline);
}
pipelineMap.erase(pipeline);
}
void CoreChecks::PreCallRecordDestroyPipelineLayout(VkDevice device, VkPipelineLayout pipelineLayout,
const VkAllocationCallbacks *pAllocator) {
if (!pipelineLayout) return;
pipelineLayoutMap.erase(pipelineLayout);
}
bool CoreChecks::PreCallValidateDestroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *pAllocator) {
SAMPLER_STATE *sampler_state = GetSamplerState(sampler);
VK_OBJECT obj_struct = {HandleToUint64(sampler), kVulkanObjectTypeSampler};
bool skip = false;
if (sampler_state) {
skip |= ValidateObjectNotInUse(sampler_state, obj_struct, "vkDestroySampler", "VUID-vkDestroySampler-sampler-01082");
}
return skip;
}
void CoreChecks::PreCallRecordDestroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *pAllocator) {
if (!sampler) return;
SAMPLER_STATE *sampler_state = GetSamplerState(sampler);
VK_OBJECT obj_struct = {HandleToUint64(sampler), kVulkanObjectTypeSampler};
// Any bound cmd buffers are now invalid
if (sampler_state) {
InvalidateCommandBuffers(sampler_state->cb_bindings, obj_struct);
}
samplerMap.erase(sampler);
}
void CoreChecks::PreCallRecordDestroyDescriptorSetLayout(VkDevice device, VkDescriptorSetLayout descriptorSetLayout,
const VkAllocationCallbacks *pAllocator) {
if (!descriptorSetLayout) return;
auto layout_it = descriptorSetLayoutMap.find(descriptorSetLayout);
if (layout_it != descriptorSetLayoutMap.end()) {
layout_it->second.get()->MarkDestroyed();
descriptorSetLayoutMap.erase(layout_it);
}
}
bool CoreChecks::PreCallValidateDestroyDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool,
const VkAllocationCallbacks *pAllocator) {
DESCRIPTOR_POOL_STATE *desc_pool_state = GetDescriptorPoolState(descriptorPool);
VK_OBJECT obj_struct = {HandleToUint64(descriptorPool), kVulkanObjectTypeDescriptorPool};
bool skip = false;
if (desc_pool_state) {
skip |= ValidateObjectNotInUse(desc_pool_state, obj_struct, "vkDestroyDescriptorPool",
"VUID-vkDestroyDescriptorPool-descriptorPool-00303");
}
return skip;
}
void CoreChecks::PreCallRecordDestroyDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool,
const VkAllocationCallbacks *pAllocator) {
if (!descriptorPool) return;
DESCRIPTOR_POOL_STATE *desc_pool_state = GetDescriptorPoolState(descriptorPool);
VK_OBJECT obj_struct = {HandleToUint64(descriptorPool), kVulkanObjectTypeDescriptorPool};
if (desc_pool_state) {
// Any bound cmd buffers are now invalid
InvalidateCommandBuffers(desc_pool_state->cb_bindings, obj_struct);
// Free sets that were in this pool
for (auto ds : desc_pool_state->sets) {
FreeDescriptorSet(ds);
}
descriptorPoolMap.erase(descriptorPool);
}
}
// Verify cmdBuffer in given cb_node is not in global in-flight set, and return skip result
// If this is a secondary command buffer, then make sure its primary is also in-flight
// If primary is not in-flight, then remove secondary from global in-flight set
// This function is only valid at a point when cmdBuffer is being reset or freed
bool CoreChecks::CheckCommandBufferInFlight(const CMD_BUFFER_STATE *cb_node, const char *action, const char *error_code) {
bool skip = false;
if (cb_node->in_use.load()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_node->commandBuffer), error_code, "Attempt to %s command buffer (%s) which is in use.",
action, report_data->FormatHandle(cb_node->commandBuffer).c_str());
}
return skip;
}
// Iterate over all cmdBuffers in given commandPool and verify that each is not in use
bool CoreChecks::CheckCommandBuffersInFlight(COMMAND_POOL_STATE *pPool, const char *action, const char *error_code) {
bool skip = false;
for (auto cmd_buffer : pPool->commandBuffers) {
skip |= CheckCommandBufferInFlight(GetCBState(cmd_buffer), action, error_code);
}
return skip;
}
// Free all command buffers in given list, removing all references/links to them using ResetCommandBufferState
void CoreChecks::FreeCommandBufferStates(COMMAND_POOL_STATE *pool_state, const uint32_t command_buffer_count,
const VkCommandBuffer *command_buffers) {
for (uint32_t i = 0; i < command_buffer_count; i++) {
auto cb_state = GetCBState(command_buffers[i]);
// Remove references to command buffer's state and delete
if (cb_state) {
// reset prior to delete, removing various references to it.
// TODO: fix this, it's insane.
ResetCommandBufferState(cb_state->commandBuffer);
// Remove the cb_state's references from COMMAND_POOL_STATEs
pool_state->commandBuffers.erase(command_buffers[i]);
// Remove the cb debug labels
EraseCmdDebugUtilsLabel(report_data, cb_state->commandBuffer);
// Remove CBState from CB map
commandBufferMap.erase(cb_state->commandBuffer);
}
}
}
bool CoreChecks::PreCallValidateFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount,
const VkCommandBuffer *pCommandBuffers) {
bool skip = false;
for (uint32_t i = 0; i < commandBufferCount; i++) {
auto cb_node = GetCBState(pCommandBuffers[i]);
// Delete CB information structure, and remove from commandBufferMap
if (cb_node) {
skip |= CheckCommandBufferInFlight(cb_node, "free", "VUID-vkFreeCommandBuffers-pCommandBuffers-00047");
}
}
return skip;
}
void CoreChecks::PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount,
const VkCommandBuffer *pCommandBuffers) {
auto pPool = GetCommandPoolState(commandPool);
FreeCommandBufferStates(pPool, commandBufferCount, pCommandBuffers);
}
bool CoreChecks::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkCommandPool *pCommandPool) {
return ValidateDeviceQueueFamily(pCreateInfo->queueFamilyIndex, "vkCreateCommandPool", "pCreateInfo->queueFamilyIndex",
"VUID-vkCreateCommandPool-queueFamilyIndex-01937");
}
void CoreChecks::PostCallRecordCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkCommandPool *pCommandPool,
VkResult result) {
if (VK_SUCCESS != result) return;
std::unique_ptr<COMMAND_POOL_STATE> cmd_pool_state(new COMMAND_POOL_STATE{});
cmd_pool_state->createFlags = pCreateInfo->flags;
cmd_pool_state->queueFamilyIndex = pCreateInfo->queueFamilyIndex;
commandPoolMap[*pCommandPool] = std::move(cmd_pool_state);
}
bool CoreChecks::PreCallValidateCreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkQueryPool *pQueryPool) {
if (disabled.query_validation) return false;
bool skip = false;
if (pCreateInfo && pCreateInfo->queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS) {
if (!enabled_features.core.pipelineStatisticsQuery) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0,
"VUID-VkQueryPoolCreateInfo-queryType-00791",
"Query pool with type VK_QUERY_TYPE_PIPELINE_STATISTICS created on a device with "
"VkDeviceCreateInfo.pEnabledFeatures.pipelineStatisticsQuery == VK_FALSE.");
}
}
return skip;
}
void CoreChecks::PostCallRecordCreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkQueryPool *pQueryPool, VkResult result) {
if (VK_SUCCESS != result) return;
std::unique_ptr<QUERY_POOL_STATE> query_pool_state(new QUERY_POOL_STATE{});
query_pool_state->createInfo = *pCreateInfo;
queryPoolMap[*pQueryPool] = std::move(query_pool_state);
}
bool CoreChecks::PreCallValidateDestroyCommandPool(VkDevice device, VkCommandPool commandPool,
const VkAllocationCallbacks *pAllocator) {
COMMAND_POOL_STATE *cp_state = GetCommandPoolState(commandPool);
bool skip = false;
if (cp_state) {
// Verify that command buffers in pool are complete (not in-flight)
skip |= CheckCommandBuffersInFlight(cp_state, "destroy command pool with", "VUID-vkDestroyCommandPool-commandPool-00041");
}
return skip;
}
void CoreChecks::PreCallRecordDestroyCommandPool(VkDevice device, VkCommandPool commandPool,
const VkAllocationCallbacks *pAllocator) {
if (!commandPool) return;
COMMAND_POOL_STATE *cp_state = GetCommandPoolState(commandPool);
// Remove cmdpool from cmdpoolmap, after freeing layer data for the command buffers
// "When a pool is destroyed, all command buffers allocated from the pool are freed."
if (cp_state) {
// Create a vector, as FreeCommandBufferStates deletes from cp_state->commandBuffers during iteration.
std::vector<VkCommandBuffer> cb_vec{cp_state->commandBuffers.begin(), cp_state->commandBuffers.end()};
FreeCommandBufferStates(cp_state, static_cast<uint32_t>(cb_vec.size()), cb_vec.data());
commandPoolMap.erase(commandPool);
}
}
bool CoreChecks::PreCallValidateResetCommandPool(VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags) {
auto command_pool_state = GetCommandPoolState(commandPool);
return CheckCommandBuffersInFlight(command_pool_state, "reset command pool with", "VUID-vkResetCommandPool-commandPool-00040");
}
void CoreChecks::PostCallRecordResetCommandPool(VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags,
VkResult result) {
if (VK_SUCCESS != result) return;
// Reset all of the CBs allocated from this pool
auto command_pool_state = GetCommandPoolState(commandPool);
for (auto cmdBuffer : command_pool_state->commandBuffers) {
ResetCommandBufferState(cmdBuffer);
}
}
bool CoreChecks::PreCallValidateResetFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences) {
bool skip = false;
for (uint32_t i = 0; i < fenceCount; ++i) {
auto pFence = GetFenceState(pFences[i]);
if (pFence && pFence->scope == kSyncScopeInternal && pFence->state == FENCE_INFLIGHT) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,
HandleToUint64(pFences[i]), "VUID-vkResetFences-pFences-01123", "Fence %s is in use.",
report_data->FormatHandle(pFences[i]).c_str());
}
}
return skip;
}
void CoreChecks::PostCallRecordResetFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkResult result) {
for (uint32_t i = 0; i < fenceCount; ++i) {
auto pFence = GetFenceState(pFences[i]);
if (pFence) {
if (pFence->scope == kSyncScopeInternal) {
pFence->state = FENCE_UNSIGNALED;
} else if (pFence->scope == kSyncScopeExternalTemporary) {
pFence->scope = kSyncScopeInternal;
}
}
}
}
// For given cb_nodes, invalidate them and track object causing invalidation
void CoreChecks::InvalidateCommandBuffers(std::unordered_set<CMD_BUFFER_STATE *> const &cb_nodes, VK_OBJECT obj) {
for (auto cb_node : cb_nodes) {
if (cb_node->state == CB_RECORDING) {
log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_InvalidCommandBuffer,
"Invalidating a command buffer that's currently being recorded: %s.",
report_data->FormatHandle(cb_node->commandBuffer).c_str());
cb_node->state = CB_INVALID_INCOMPLETE;
} else if (cb_node->state == CB_RECORDED) {
cb_node->state = CB_INVALID_COMPLETE;
}
cb_node->broken_bindings.push_back(obj);
// if secondary, then propagate the invalidation to the primaries that will call us.
if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
InvalidateCommandBuffers(cb_node->linkedCommandBuffers, obj);
}
}
}
bool CoreChecks::PreCallValidateDestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer,
const VkAllocationCallbacks *pAllocator) {
FRAMEBUFFER_STATE *framebuffer_state = GetFramebufferState(framebuffer);
VK_OBJECT obj_struct = {HandleToUint64(framebuffer), kVulkanObjectTypeFramebuffer};
bool skip = false;
if (framebuffer_state) {
skip |= ValidateObjectNotInUse(framebuffer_state, obj_struct, "vkDestroyFramebuffer",
"VUID-vkDestroyFramebuffer-framebuffer-00892");
}
return skip;
}
void CoreChecks::PreCallRecordDestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer,
const VkAllocationCallbacks *pAllocator) {
if (!framebuffer) return;
FRAMEBUFFER_STATE *framebuffer_state = GetFramebufferState(framebuffer);
VK_OBJECT obj_struct = {HandleToUint64(framebuffer), kVulkanObjectTypeFramebuffer};
InvalidateCommandBuffers(framebuffer_state->cb_bindings, obj_struct);
frameBufferMap.erase(framebuffer);
}
bool CoreChecks::PreCallValidateDestroyRenderPass(VkDevice device, VkRenderPass renderPass,
const VkAllocationCallbacks *pAllocator) {
RENDER_PASS_STATE *rp_state = GetRenderPassState(renderPass);
VK_OBJECT obj_struct = {HandleToUint64(renderPass), kVulkanObjectTypeRenderPass};
bool skip = false;
if (rp_state) {
skip |= ValidateObjectNotInUse(rp_state, obj_struct, "vkDestroyRenderPass", "VUID-vkDestroyRenderPass-renderPass-00873");
}
return skip;
}
void CoreChecks::PreCallRecordDestroyRenderPass(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks *pAllocator) {
if (!renderPass) return;
RENDER_PASS_STATE *rp_state = GetRenderPassState(renderPass);
VK_OBJECT obj_struct = {HandleToUint64(renderPass), kVulkanObjectTypeRenderPass};
InvalidateCommandBuffers(rp_state->cb_bindings, obj_struct);
renderPassMap.erase(renderPass);
}
// Access helper functions for external modules
VkFormatProperties CoreChecks::GetPDFormatProperties(const VkFormat format) {
VkFormatProperties format_properties;
DispatchGetPhysicalDeviceFormatProperties(physical_device, format, &format_properties);
return format_properties;
}
VkResult CoreChecks::GetPDImageFormatProperties(const VkImageCreateInfo *image_ci,
VkImageFormatProperties *pImageFormatProperties) {
return DispatchGetPhysicalDeviceImageFormatProperties(physical_device, image_ci->format, image_ci->imageType, image_ci->tiling,
image_ci->usage, image_ci->flags, pImageFormatProperties);
}
VkResult CoreChecks::GetPDImageFormatProperties2(const VkPhysicalDeviceImageFormatInfo2 *phys_dev_image_fmt_info,
VkImageFormatProperties2 *pImageFormatProperties) {
if (!instance_extensions.vk_khr_get_physical_device_properties_2) return VK_ERROR_EXTENSION_NOT_PRESENT;
return DispatchGetPhysicalDeviceImageFormatProperties2(physical_device, phys_dev_image_fmt_info, pImageFormatProperties);
}
void CoreChecks::PostCallRecordCreateFence(VkDevice device, const VkFenceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkFence *pFence, VkResult result) {
if (VK_SUCCESS != result) return;
std::unique_ptr<FENCE_STATE> fence_state(new FENCE_STATE{});
fence_state->fence = *pFence;
fence_state->createInfo = *pCreateInfo;
fence_state->state = (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) ? FENCE_RETIRED : FENCE_UNSIGNALED;
fenceMap[*pFence] = std::move(fence_state);
}
// Validation cache:
// CV is the bottommost implementor of this extension. Don't pass calls down.
// utility function to set collective state for pipeline
void SetPipelineState(PIPELINE_STATE *pPipe) {
// If any attachment used by this pipeline has blendEnable, set top-level blendEnable
if (pPipe->graphicsPipelineCI.pColorBlendState) {
for (size_t i = 0; i < pPipe->attachments.size(); ++i) {
if (VK_TRUE == pPipe->attachments[i].blendEnable) {
if (((pPipe->attachments[i].dstAlphaBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
(pPipe->attachments[i].dstAlphaBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) ||
((pPipe->attachments[i].dstColorBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
(pPipe->attachments[i].dstColorBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) ||
((pPipe->attachments[i].srcAlphaBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
(pPipe->attachments[i].srcAlphaBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) ||
((pPipe->attachments[i].srcColorBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) &&
(pPipe->attachments[i].srcColorBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA))) {
pPipe->blendConstantsEnabled = true;
}
}
}
}
}
bool CoreChecks::ValidatePipelineVertexDivisors(std::vector<std::unique_ptr<PIPELINE_STATE>> const &pipe_state_vec,
const uint32_t count, const VkGraphicsPipelineCreateInfo *pipe_cis) {
bool skip = false;
const VkPhysicalDeviceLimits *device_limits = &phys_dev_props.limits;
for (uint32_t i = 0; i < count; i++) {
auto pvids_ci = lvl_find_in_chain<VkPipelineVertexInputDivisorStateCreateInfoEXT>(pipe_cis[i].pVertexInputState->pNext);
if (nullptr == pvids_ci) continue;
const PIPELINE_STATE *pipe_state = pipe_state_vec[i].get();
for (uint32_t j = 0; j < pvids_ci->vertexBindingDivisorCount; j++) {
const VkVertexInputBindingDivisorDescriptionEXT *vibdd = &(pvids_ci->pVertexBindingDivisors[j]);
if (vibdd->binding >= device_limits->maxVertexInputBindings) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkVertexInputBindingDivisorDescriptionEXT-binding-01869",
"vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, "
"pVertexBindingDivisors[%1u] binding index of (%1u) exceeds device maxVertexInputBindings (%1u).",
i, j, vibdd->binding, device_limits->maxVertexInputBindings);
}
if (vibdd->divisor > phys_dev_ext_props.vtx_attrib_divisor_props.maxVertexAttribDivisor) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkVertexInputBindingDivisorDescriptionEXT-divisor-01870",
"vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, "
"pVertexBindingDivisors[%1u] divisor of (%1u) exceeds extension maxVertexAttribDivisor (%1u).",
i, j, vibdd->divisor, phys_dev_ext_props.vtx_attrib_divisor_props.maxVertexAttribDivisor);
}
if ((0 == vibdd->divisor) && !enabled_features.vtx_attrib_divisor_features.vertexAttributeInstanceRateZeroDivisor) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkVertexInputBindingDivisorDescriptionEXT-vertexAttributeInstanceRateZeroDivisor-02228",
"vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, "
"pVertexBindingDivisors[%1u] divisor must not be 0 when vertexAttributeInstanceRateZeroDivisor feature is not "
"enabled.",
i, j);
}
if ((1 != vibdd->divisor) && !enabled_features.vtx_attrib_divisor_features.vertexAttributeInstanceRateDivisor) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkVertexInputBindingDivisorDescriptionEXT-vertexAttributeInstanceRateDivisor-02229",
"vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, "
"pVertexBindingDivisors[%1u] divisor (%1u) must be 1 when vertexAttributeInstanceRateDivisor feature is not "
"enabled.",
i, j, vibdd->divisor);
}
// Find the corresponding binding description and validate input rate setting
bool failed_01871 = true;
for (size_t k = 0; k < pipe_state->vertex_binding_descriptions_.size(); k++) {
if ((vibdd->binding == pipe_state->vertex_binding_descriptions_[k].binding) &&
(VK_VERTEX_INPUT_RATE_INSTANCE == pipe_state->vertex_binding_descriptions_[k].inputRate)) {
failed_01871 = false;
break;
}
}
if (failed_01871) { // Description not found, or has incorrect inputRate value
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkVertexInputBindingDivisorDescriptionEXT-inputRate-01871",
"vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, "
"pVertexBindingDivisors[%1u] specifies binding index (%1u), but that binding index's "
"VkVertexInputBindingDescription.inputRate member is not VK_VERTEX_INPUT_RATE_INSTANCE.",
i, j, vibdd->binding);
}
}
}
return skip;
}
bool CoreChecks::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
void *cgpl_state_data) {
bool skip = false;
create_graphics_pipeline_api_state *cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state *>(cgpl_state_data);
cgpl_state->pipe_state.reserve(count);
for (uint32_t i = 0; i < count; i++) {
cgpl_state->pipe_state.push_back(std::unique_ptr<PIPELINE_STATE>(new PIPELINE_STATE));
(cgpl_state->pipe_state)[i]->initGraphicsPipeline(&pCreateInfos[i],
GetRenderPassStateSharedPtr(pCreateInfos[i].renderPass));
(cgpl_state->pipe_state)[i]->pipeline_layout = *GetPipelineLayout(pCreateInfos[i].layout);
}
for (uint32_t i = 0; i < count; i++) {
skip |= ValidatePipelineLocked(cgpl_state->pipe_state, i);
}
for (uint32_t i = 0; i < count; i++) {
skip |= ValidatePipelineUnlocked(cgpl_state->pipe_state, i);
}
if (device_extensions.vk_ext_vertex_attribute_divisor) {
skip |= ValidatePipelineVertexDivisors(cgpl_state->pipe_state, count, pCreateInfos);
}
return skip;
}
// GPU validation may replace pCreateInfos for the down-chain call
void CoreChecks::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
void *cgpl_state_data) {
create_graphics_pipeline_api_state *cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state *>(cgpl_state_data);
cgpl_state->pCreateInfos = pCreateInfos;
// GPU Validation may replace instrumented shaders with non-instrumented ones, so allow it to modify the createinfos.
if (enabled.gpu_validation) {
cgpl_state->gpu_create_infos = GpuPreCallRecordCreateGraphicsPipelines(pipelineCache, count, pCreateInfos, pAllocator,
pPipelines, cgpl_state->pipe_state);
cgpl_state->pCreateInfos = reinterpret_cast<VkGraphicsPipelineCreateInfo *>(cgpl_state->gpu_create_infos.data());
}
}
void CoreChecks::PostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
VkResult result, void *cgpl_state_data) {
create_graphics_pipeline_api_state *cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state *>(cgpl_state_data);
// This API may create pipelines regardless of the return value
for (uint32_t i = 0; i < count; i++) {
if (pPipelines[i] != VK_NULL_HANDLE) {
(cgpl_state->pipe_state)[i]->pipeline = pPipelines[i];
pipelineMap[pPipelines[i]] = std::move((cgpl_state->pipe_state)[i]);
}
}
// GPU val needs clean up regardless of result
if (enabled.gpu_validation) {
GpuPostCallRecordCreateGraphicsPipelines(count, pCreateInfos, pAllocator, pPipelines);
cgpl_state->gpu_create_infos.clear();
}
cgpl_state->pipe_state.clear();
}
bool CoreChecks::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
void *pipe_state_data) {
bool skip = false;
std::vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state =
reinterpret_cast<std::vector<std::unique_ptr<PIPELINE_STATE>> *>(pipe_state_data);
pipe_state->reserve(count);
for (uint32_t i = 0; i < count; i++) {
// Create and initialize internal tracking data structure
pipe_state->push_back(unique_ptr<PIPELINE_STATE>(new PIPELINE_STATE));
(*pipe_state)[i]->initComputePipeline(&pCreateInfos[i]);
(*pipe_state)[i]->pipeline_layout = *GetPipelineLayout(pCreateInfos[i].layout);
// TODO: Add Compute Pipeline Verification
skip |= ValidateComputePipeline((*pipe_state)[i].get());
}
return skip;
}
void CoreChecks::PostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
VkResult result, void *pipe_state_data) {
std::vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state =
reinterpret_cast<std::vector<std::unique_ptr<PIPELINE_STATE>> *>(pipe_state_data);
// This API may create pipelines regardless of the return value
for (uint32_t i = 0; i < count; i++) {
if (pPipelines[i] != VK_NULL_HANDLE) {
(*pipe_state)[i]->pipeline = pPipelines[i];
pipelineMap[pPipelines[i]] = std::move((*pipe_state)[i]);
}
}
}
bool CoreChecks::PreCallValidateCreateRayTracingPipelinesNV(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkRayTracingPipelineCreateInfoNV *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
void *pipe_state_data) {
bool skip = false;
// The order of operations here is a little convoluted but gets the job done
// 1. Pipeline create state is first shadowed into PIPELINE_STATE struct
// 2. Create state is then validated (which uses flags setup during shadowing)
// 3. If everything looks good, we'll then create the pipeline and add NODE to pipelineMap
uint32_t i = 0;
vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state =
reinterpret_cast<vector<std::unique_ptr<PIPELINE_STATE>> *>(pipe_state_data);
pipe_state->reserve(count);
for (i = 0; i < count; i++) {
pipe_state->push_back(std::unique_ptr<PIPELINE_STATE>(new PIPELINE_STATE));
(*pipe_state)[i]->initRayTracingPipelineNV(&pCreateInfos[i]);
(*pipe_state)[i]->pipeline_layout = *GetPipelineLayout(pCreateInfos[i].layout);
}
for (i = 0; i < count; i++) {
skip |= ValidateRayTracingPipelineNV((*pipe_state)[i].get());
}
return skip;
}
void CoreChecks::PostCallRecordCreateRayTracingPipelinesNV(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
const VkRayTracingPipelineCreateInfoNV *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
VkResult result, void *pipe_state_data) {
vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state =
reinterpret_cast<vector<std::unique_ptr<PIPELINE_STATE>> *>(pipe_state_data);
// This API may create pipelines regardless of the return value
for (uint32_t i = 0; i < count; i++) {
if (pPipelines[i] != VK_NULL_HANDLE) {
(*pipe_state)[i]->pipeline = pPipelines[i];
pipelineMap[pPipelines[i]] = std::move((*pipe_state)[i]);
}
}
}
void CoreChecks::PostCallRecordCreateSampler(VkDevice device, const VkSamplerCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSampler *pSampler, VkResult result) {
samplerMap[*pSampler] = unique_ptr<SAMPLER_STATE>(new SAMPLER_STATE(pSampler, pCreateInfo));
}
bool CoreChecks::PreCallValidateCreateDescriptorSetLayout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorSetLayout *pSetLayout) {
return cvdescriptorset::DescriptorSetLayout::ValidateCreateInfo(
report_data, pCreateInfo, device_extensions.vk_khr_push_descriptor, phys_dev_ext_props.max_push_descriptors,
device_extensions.vk_ext_descriptor_indexing, &enabled_features.descriptor_indexing, &enabled_features.inline_uniform_block,
&phys_dev_ext_props.inline_uniform_block_props);
}
void CoreChecks::PostCallRecordCreateDescriptorSetLayout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDescriptorSetLayout *pSetLayout,
VkResult result) {
if (VK_SUCCESS != result) return;
descriptorSetLayoutMap[*pSetLayout] = std::make_shared<cvdescriptorset::DescriptorSetLayout>(pCreateInfo, *pSetLayout);
}
// Used by CreatePipelineLayout and CmdPushConstants.
// Note that the index argument is optional and only used by CreatePipelineLayout.
bool CoreChecks::ValidatePushConstantRange(const uint32_t offset, const uint32_t size, const char *caller_name,
uint32_t index = 0) {
if (disabled.push_constant_range) return false;
uint32_t const maxPushConstantsSize = phys_dev_props.limits.maxPushConstantsSize;
bool skip = false;
// Check that offset + size don't exceed the max.
// Prevent arithetic overflow here by avoiding addition and testing in this order.
if ((offset >= maxPushConstantsSize) || (size > maxPushConstantsSize - offset)) {
// This is a pain just to adapt the log message to the caller, but better to sort it out only when there is a problem.
if (0 == strcmp(caller_name, "vkCreatePipelineLayout()")) {
if (offset >= maxPushConstantsSize) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPushConstantRange-offset-00294",
"%s call has push constants index %u with offset %u that exceeds this device's maxPushConstantSize of %u.",
caller_name, index, offset, maxPushConstantsSize);
}
if (size > maxPushConstantsSize - offset) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPushConstantRange-size-00298",
"%s call has push constants index %u with offset %u and size %u that exceeds this device's "
"maxPushConstantSize of %u.",
caller_name, index, offset, size, maxPushConstantsSize);
}
} else if (0 == strcmp(caller_name, "vkCmdPushConstants()")) {
if (offset >= maxPushConstantsSize) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdPushConstants-offset-00370",
"%s call has push constants index %u with offset %u that exceeds this device's maxPushConstantSize of %u.",
caller_name, index, offset, maxPushConstantsSize);
}
if (size > maxPushConstantsSize - offset) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdPushConstants-size-00371",
"%s call has push constants index %u with offset %u and size %u that exceeds this device's "
"maxPushConstantSize of %u.",
caller_name, index, offset, size, maxPushConstantsSize);
}
} else {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_InternalError, "%s caller not supported.", caller_name);
}
}
// size needs to be non-zero and a multiple of 4.
if ((size == 0) || ((size & 0x3) != 0)) {
if (0 == strcmp(caller_name, "vkCreatePipelineLayout()")) {
if (size == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPushConstantRange-size-00296",
"%s call has push constants index %u with size %u. Size must be greater than zero.", caller_name,
index, size);
}
if (size & 0x3) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPushConstantRange-size-00297",
"%s call has push constants index %u with size %u. Size must be a multiple of 4.", caller_name,
index, size);
}
} else if (0 == strcmp(caller_name, "vkCmdPushConstants()")) {
if (size == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdPushConstants-size-arraylength",
"%s call has push constants index %u with size %u. Size must be greater than zero.", caller_name,
index, size);
}
if (size & 0x3) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdPushConstants-size-00369",
"%s call has push constants index %u with size %u. Size must be a multiple of 4.", caller_name,
index, size);
}
} else {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_InternalError, "%s caller not supported.", caller_name);
}
}
// offset needs to be a multiple of 4.
if ((offset & 0x3) != 0) {
if (0 == strcmp(caller_name, "vkCreatePipelineLayout()")) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPushConstantRange-offset-00295",
"%s call has push constants index %u with offset %u. Offset must be a multiple of 4.", caller_name,
index, offset);
} else if (0 == strcmp(caller_name, "vkCmdPushConstants()")) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-vkCmdPushConstants-offset-00368",
"%s call has push constants with offset %u. Offset must be a multiple of 4.", caller_name, offset);
} else {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_InternalError, "%s caller not supported.", caller_name);
}
}
return skip;
}
enum DSL_DESCRIPTOR_GROUPS {
DSL_TYPE_SAMPLERS = 0,
DSL_TYPE_UNIFORM_BUFFERS,
DSL_TYPE_STORAGE_BUFFERS,
DSL_TYPE_SAMPLED_IMAGES,
DSL_TYPE_STORAGE_IMAGES,
DSL_TYPE_INPUT_ATTACHMENTS,
DSL_TYPE_INLINE_UNIFORM_BLOCK,
DSL_NUM_DESCRIPTOR_GROUPS
};
// Used by PreCallValidateCreatePipelineLayout.
// Returns an array of size DSL_NUM_DESCRIPTOR_GROUPS of the maximum number of descriptors used in any single pipeline stage
std::valarray<uint32_t> GetDescriptorCountMaxPerStage(
const DeviceFeatures *enabled_features,
const std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> set_layouts, bool skip_update_after_bind) {
// Identify active pipeline stages
std::vector<VkShaderStageFlags> stage_flags = {VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT,
VK_SHADER_STAGE_COMPUTE_BIT};
if (enabled_features->core.geometryShader) {
stage_flags.push_back(VK_SHADER_STAGE_GEOMETRY_BIT);
}
if (enabled_features->core.tessellationShader) {
stage_flags.push_back(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
stage_flags.push_back(VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT);
}
// Allow iteration over enum values
std::vector<DSL_DESCRIPTOR_GROUPS> dsl_groups = {
DSL_TYPE_SAMPLERS, DSL_TYPE_UNIFORM_BUFFERS, DSL_TYPE_STORAGE_BUFFERS, DSL_TYPE_SAMPLED_IMAGES,
DSL_TYPE_STORAGE_IMAGES, DSL_TYPE_INPUT_ATTACHMENTS, DSL_TYPE_INLINE_UNIFORM_BLOCK};
// Sum by layouts per stage, then pick max of stages per type
std::valarray<uint32_t> max_sum(0U, DSL_NUM_DESCRIPTOR_GROUPS); // max descriptor sum among all pipeline stages
for (auto stage : stage_flags) {
std::valarray<uint32_t> stage_sum(0U, DSL_NUM_DESCRIPTOR_GROUPS); // per-stage sums
for (auto dsl : set_layouts) {
if (skip_update_after_bind &&
(dsl->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) {
continue;
}
for (uint32_t binding_idx = 0; binding_idx < dsl->GetBindingCount(); binding_idx++) {
const VkDescriptorSetLayoutBinding *binding = dsl->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
// Bindings with a descriptorCount of 0 are "reserved" and should be skipped
if (0 != (stage & binding->stageFlags) && binding->descriptorCount > 0) {
switch (binding->descriptorType) {
case VK_DESCRIPTOR_TYPE_SAMPLER:
stage_sum[DSL_TYPE_SAMPLERS] += binding->descriptorCount;
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
stage_sum[DSL_TYPE_UNIFORM_BUFFERS] += binding->descriptorCount;
break;
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
stage_sum[DSL_TYPE_STORAGE_BUFFERS] += binding->descriptorCount;
break;
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
stage_sum[DSL_TYPE_SAMPLED_IMAGES] += binding->descriptorCount;
break;
case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
stage_sum[DSL_TYPE_STORAGE_IMAGES] += binding->descriptorCount;
break;
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
stage_sum[DSL_TYPE_SAMPLED_IMAGES] += binding->descriptorCount;
stage_sum[DSL_TYPE_SAMPLERS] += binding->descriptorCount;
break;
case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
stage_sum[DSL_TYPE_INPUT_ATTACHMENTS] += binding->descriptorCount;
break;
case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT:
// count one block per binding. descriptorCount is number of bytes
stage_sum[DSL_TYPE_INLINE_UNIFORM_BLOCK]++;
break;
default:
break;
}
}
}
}
for (auto type : dsl_groups) {
max_sum[type] = std::max(stage_sum[type], max_sum[type]);
}
}
return max_sum;
}
// Used by PreCallValidateCreatePipelineLayout.
// Returns a map indexed by VK_DESCRIPTOR_TYPE_* enum of the summed descriptors by type.
// Note: descriptors only count against the limit once even if used by multiple stages.
std::map<uint32_t, uint32_t> GetDescriptorSum(
const std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> &set_layouts, bool skip_update_after_bind) {
std::map<uint32_t, uint32_t> sum_by_type;
for (auto dsl : set_layouts) {
if (skip_update_after_bind && (dsl->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) {
continue;
}
for (uint32_t binding_idx = 0; binding_idx < dsl->GetBindingCount(); binding_idx++) {
const VkDescriptorSetLayoutBinding *binding = dsl->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
// Bindings with a descriptorCount of 0 are "reserved" and should be skipped
if (binding->descriptorCount > 0) {
if (binding->descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) {
// count one block per binding. descriptorCount is number of bytes
sum_by_type[binding->descriptorType]++;
} else {
sum_by_type[binding->descriptorType] += binding->descriptorCount;
}
}
}
}
return sum_by_type;
}
bool CoreChecks::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout) {
bool skip = false;
// Validate layout count against device physical limit
if (pCreateInfo->setLayoutCount > phys_dev_props.limits.maxBoundDescriptorSets) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-setLayoutCount-00286",
"vkCreatePipelineLayout(): setLayoutCount (%d) exceeds physical device maxBoundDescriptorSets limit (%d).",
pCreateInfo->setLayoutCount, phys_dev_props.limits.maxBoundDescriptorSets);
}
// Validate Push Constant ranges
uint32_t i, j;
for (i = 0; i < pCreateInfo->pushConstantRangeCount; ++i) {
skip |= ValidatePushConstantRange(pCreateInfo->pPushConstantRanges[i].offset, pCreateInfo->pPushConstantRanges[i].size,
"vkCreatePipelineLayout()", i);
if (0 == pCreateInfo->pPushConstantRanges[i].stageFlags) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPushConstantRange-stageFlags-requiredbitmask",
"vkCreatePipelineLayout() call has no stageFlags set.");
}
}
// As of 1.0.28, there is a VU that states that a stage flag cannot appear more than once in the list of push constant ranges.
for (i = 0; i < pCreateInfo->pushConstantRangeCount; ++i) {
for (j = i + 1; j < pCreateInfo->pushConstantRangeCount; ++j) {
if (0 != (pCreateInfo->pPushConstantRanges[i].stageFlags & pCreateInfo->pPushConstantRanges[j].stageFlags)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pPushConstantRanges-00292",
"vkCreatePipelineLayout() Duplicate stage flags found in ranges %d and %d.", i, j);
}
}
}
// Early-out
if (skip) return skip;
std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> set_layouts(pCreateInfo->setLayoutCount, nullptr);
unsigned int push_descriptor_set_count = 0;
{
for (i = 0; i < pCreateInfo->setLayoutCount; ++i) {
set_layouts[i] = GetDescriptorSetLayout(this, pCreateInfo->pSetLayouts[i]);
if (set_layouts[i]->IsPushDescriptor()) ++push_descriptor_set_count;
}
}
if (push_descriptor_set_count > 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00293",
"vkCreatePipelineLayout() Multiple push descriptor sets found.");
}
// Max descriptors by type, within a single pipeline stage
std::valarray<uint32_t> max_descriptors_per_stage = GetDescriptorCountMaxPerStage(&enabled_features, set_layouts, true);
// Samplers
if (max_descriptors_per_stage[DSL_TYPE_SAMPLERS] > phys_dev_props.limits.maxPerStageDescriptorSamplers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00287",
"vkCreatePipelineLayout(): max per-stage sampler bindings count (%d) exceeds device "
"maxPerStageDescriptorSamplers limit (%d).",
max_descriptors_per_stage[DSL_TYPE_SAMPLERS], phys_dev_props.limits.maxPerStageDescriptorSamplers);
}
// Uniform buffers
if (max_descriptors_per_stage[DSL_TYPE_UNIFORM_BUFFERS] > phys_dev_props.limits.maxPerStageDescriptorUniformBuffers) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00288",
"vkCreatePipelineLayout(): max per-stage uniform buffer bindings count (%d) exceeds device "
"maxPerStageDescriptorUniformBuffers limit (%d).",
max_descriptors_per_stage[DSL_TYPE_UNIFORM_BUFFERS], phys_dev_props.limits.maxPerStageDescriptorUniformBuffers);
}
// Storage buffers
if (max_descriptors_per_stage[DSL_TYPE_STORAGE_BUFFERS] > phys_dev_props.limits.maxPerStageDescriptorStorageBuffers) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00289",
"vkCreatePipelineLayout(): max per-stage storage buffer bindings count (%d) exceeds device "
"maxPerStageDescriptorStorageBuffers limit (%d).",
max_descriptors_per_stage[DSL_TYPE_STORAGE_BUFFERS], phys_dev_props.limits.maxPerStageDescriptorStorageBuffers);
}
// Sampled images
if (max_descriptors_per_stage[DSL_TYPE_SAMPLED_IMAGES] > phys_dev_props.limits.maxPerStageDescriptorSampledImages) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00290",
"vkCreatePipelineLayout(): max per-stage sampled image bindings count (%d) exceeds device "
"maxPerStageDescriptorSampledImages limit (%d).",
max_descriptors_per_stage[DSL_TYPE_SAMPLED_IMAGES], phys_dev_props.limits.maxPerStageDescriptorSampledImages);
}
// Storage images
if (max_descriptors_per_stage[DSL_TYPE_STORAGE_IMAGES] > phys_dev_props.limits.maxPerStageDescriptorStorageImages) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00291",
"vkCreatePipelineLayout(): max per-stage storage image bindings count (%d) exceeds device "
"maxPerStageDescriptorStorageImages limit (%d).",
max_descriptors_per_stage[DSL_TYPE_STORAGE_IMAGES], phys_dev_props.limits.maxPerStageDescriptorStorageImages);
}
// Input attachments
if (max_descriptors_per_stage[DSL_TYPE_INPUT_ATTACHMENTS] > phys_dev_props.limits.maxPerStageDescriptorInputAttachments) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01676",
"vkCreatePipelineLayout(): max per-stage input attachment bindings count (%d) exceeds device "
"maxPerStageDescriptorInputAttachments limit (%d).",
max_descriptors_per_stage[DSL_TYPE_INPUT_ATTACHMENTS],
phys_dev_props.limits.maxPerStageDescriptorInputAttachments);
}
// Inline uniform blocks
if (max_descriptors_per_stage[DSL_TYPE_INLINE_UNIFORM_BLOCK] >
phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorInlineUniformBlocks) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-02214",
"vkCreatePipelineLayout(): max per-stage inline uniform block bindings count (%d) exceeds device "
"maxPerStageDescriptorInlineUniformBlocks limit (%d).",
max_descriptors_per_stage[DSL_TYPE_INLINE_UNIFORM_BLOCK],
phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorInlineUniformBlocks);
}
// Total descriptors by type
//
std::map<uint32_t, uint32_t> sum_all_stages = GetDescriptorSum(set_layouts, true);
// Samplers
uint32_t sum = sum_all_stages[VK_DESCRIPTOR_TYPE_SAMPLER] + sum_all_stages[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER];
if (sum > phys_dev_props.limits.maxDescriptorSetSamplers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01677",
"vkCreatePipelineLayout(): sum of sampler bindings among all stages (%d) exceeds device "
"maxDescriptorSetSamplers limit (%d).",
sum, phys_dev_props.limits.maxDescriptorSetSamplers);
}
// Uniform buffers
if (sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] > phys_dev_props.limits.maxDescriptorSetUniformBuffers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01678",
"vkCreatePipelineLayout(): sum of uniform buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetUniformBuffers limit (%d).",
sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER], phys_dev_props.limits.maxDescriptorSetUniformBuffers);
}
// Dynamic uniform buffers
if (sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] > phys_dev_props.limits.maxDescriptorSetUniformBuffersDynamic) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01679",
"vkCreatePipelineLayout(): sum of dynamic uniform buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetUniformBuffersDynamic limit (%d).",
sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC],
phys_dev_props.limits.maxDescriptorSetUniformBuffersDynamic);
}
// Storage buffers
if (sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] > phys_dev_props.limits.maxDescriptorSetStorageBuffers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01680",
"vkCreatePipelineLayout(): sum of storage buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetStorageBuffers limit (%d).",
sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER], phys_dev_props.limits.maxDescriptorSetStorageBuffers);
}
// Dynamic storage buffers
if (sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] > phys_dev_props.limits.maxDescriptorSetStorageBuffersDynamic) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01681",
"vkCreatePipelineLayout(): sum of dynamic storage buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetStorageBuffersDynamic limit (%d).",
sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC],
phys_dev_props.limits.maxDescriptorSetStorageBuffersDynamic);
}
// Sampled images
sum = sum_all_stages[VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] + sum_all_stages[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] +
sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER];
if (sum > phys_dev_props.limits.maxDescriptorSetSampledImages) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01682",
"vkCreatePipelineLayout(): sum of sampled image bindings among all stages (%d) exceeds device "
"maxDescriptorSetSampledImages limit (%d).",
sum, phys_dev_props.limits.maxDescriptorSetSampledImages);
}
// Storage images
sum = sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] + sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER];
if (sum > phys_dev_props.limits.maxDescriptorSetStorageImages) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01683",
"vkCreatePipelineLayout(): sum of storage image bindings among all stages (%d) exceeds device "
"maxDescriptorSetStorageImages limit (%d).",
sum, phys_dev_props.limits.maxDescriptorSetStorageImages);
}
// Input attachments
if (sum_all_stages[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] > phys_dev_props.limits.maxDescriptorSetInputAttachments) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01684",
"vkCreatePipelineLayout(): sum of input attachment bindings among all stages (%d) exceeds device "
"maxDescriptorSetInputAttachments limit (%d).",
sum_all_stages[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT], phys_dev_props.limits.maxDescriptorSetInputAttachments);
}
// Inline uniform blocks
if (sum_all_stages[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT] >
phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetInlineUniformBlocks) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-02216",
"vkCreatePipelineLayout(): sum of inline uniform block bindings among all stages (%d) exceeds device "
"maxDescriptorSetInlineUniformBlocks limit (%d).",
sum_all_stages[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT],
phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetInlineUniformBlocks);
}
if (device_extensions.vk_ext_descriptor_indexing) {
// XXX TODO: replace with correct VU messages
// Max descriptors by type, within a single pipeline stage
std::valarray<uint32_t> max_descriptors_per_stage_update_after_bind =
GetDescriptorCountMaxPerStage(&enabled_features, set_layouts, false);
// Samplers
if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLERS] >
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSamplers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-03022",
"vkCreatePipelineLayout(): max per-stage sampler bindings count (%d) exceeds device "
"maxPerStageDescriptorUpdateAfterBindSamplers limit (%d).",
max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLERS],
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSamplers);
}
// Uniform buffers
if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_UNIFORM_BUFFERS] >
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindUniformBuffers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-03023",
"vkCreatePipelineLayout(): max per-stage uniform buffer bindings count (%d) exceeds device "
"maxPerStageDescriptorUpdateAfterBindUniformBuffers limit (%d).",
max_descriptors_per_stage_update_after_bind[DSL_TYPE_UNIFORM_BUFFERS],
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindUniformBuffers);
}
// Storage buffers
if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_BUFFERS] >
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageBuffers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-03024",
"vkCreatePipelineLayout(): max per-stage storage buffer bindings count (%d) exceeds device "
"maxPerStageDescriptorUpdateAfterBindStorageBuffers limit (%d).",
max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_BUFFERS],
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageBuffers);
}
// Sampled images
if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLED_IMAGES] >
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSampledImages) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-03025",
"vkCreatePipelineLayout(): max per-stage sampled image bindings count (%d) exceeds device "
"maxPerStageDescriptorUpdateAfterBindSampledImages limit (%d).",
max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLED_IMAGES],
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSampledImages);
}
// Storage images
if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_IMAGES] >
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageImages) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-03026",
"vkCreatePipelineLayout(): max per-stage storage image bindings count (%d) exceeds device "
"maxPerStageDescriptorUpdateAfterBindStorageImages limit (%d).",
max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_IMAGES],
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageImages);
}
// Input attachments
if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_INPUT_ATTACHMENTS] >
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindInputAttachments) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-03027",
"vkCreatePipelineLayout(): max per-stage input attachment bindings count (%d) exceeds device "
"maxPerStageDescriptorUpdateAfterBindInputAttachments limit (%d).",
max_descriptors_per_stage_update_after_bind[DSL_TYPE_INPUT_ATTACHMENTS],
phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindInputAttachments);
}
// Inline uniform blocks
if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_INLINE_UNIFORM_BLOCK] >
phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-02215",
"vkCreatePipelineLayout(): max per-stage inline uniform block bindings count (%d) exceeds device "
"maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks limit (%d).",
max_descriptors_per_stage_update_after_bind[DSL_TYPE_INLINE_UNIFORM_BLOCK],
phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks);
}
// Total descriptors by type, summed across all pipeline stages
//
std::map<uint32_t, uint32_t> sum_all_stages_update_after_bind = GetDescriptorSum(set_layouts, false);
// Samplers
sum = sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_SAMPLER] +
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER];
if (sum > phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindSamplers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03036",
"vkCreatePipelineLayout(): sum of sampler bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindSamplers limit (%d).",
sum, phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindSamplers);
}
// Uniform buffers
if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] >
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03037",
"vkCreatePipelineLayout(): sum of uniform buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindUniformBuffers limit (%d).",
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER],
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffers);
}
// Dynamic uniform buffers
if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] >
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03038",
"vkCreatePipelineLayout(): sum of dynamic uniform buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindUniformBuffersDynamic limit (%d).",
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC],
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
}
// Storage buffers
if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] >
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageBuffers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03039",
"vkCreatePipelineLayout(): sum of storage buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindStorageBuffers limit (%d).",
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER],
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageBuffers);
}
// Dynamic storage buffers
if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] >
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03040",
"vkCreatePipelineLayout(): sum of dynamic storage buffer bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindStorageBuffersDynamic limit (%d).",
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC],
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
}
// Sampled images
sum = sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] +
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] +
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER];
if (sum > phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindSampledImages) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03041",
"vkCreatePipelineLayout(): sum of sampled image bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindSampledImages limit (%d).",
sum, phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindSampledImages);
}
// Storage images
sum = sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] +
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER];
if (sum > phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageImages) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03042",
"vkCreatePipelineLayout(): sum of storage image bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindStorageImages limit (%d).",
sum, phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageImages);
}
// Input attachments
if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] >
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindInputAttachments) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03043",
"vkCreatePipelineLayout(): sum of input attachment bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindInputAttachments limit (%d).",
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT],
phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindInputAttachments);
}
// Inline uniform blocks
if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT] >
phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetUpdateAfterBindInlineUniformBlocks) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineLayoutCreateInfo-descriptorType-02217",
"vkCreatePipelineLayout(): sum of inline uniform block bindings among all stages (%d) exceeds device "
"maxDescriptorSetUpdateAfterBindInlineUniformBlocks limit (%d).",
sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT],
phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetUpdateAfterBindInlineUniformBlocks);
}
}
return skip;
}
// For repeatable sorting, not very useful for "memory in range" search
struct PushConstantRangeCompare {
bool operator()(const VkPushConstantRange *lhs, const VkPushConstantRange *rhs) const {
if (lhs->offset == rhs->offset) {
if (lhs->size == rhs->size) {
// The comparison is arbitrary, but avoids false aliasing by comparing all fields.
return lhs->stageFlags < rhs->stageFlags;
}
// If the offsets are the same then sorting by the end of range is useful for validation
return lhs->size < rhs->size;
}
return lhs->offset < rhs->offset;
}
};
static PushConstantRangesDict push_constant_ranges_dict;
PushConstantRangesId GetCanonicalId(const VkPipelineLayoutCreateInfo *info) {
if (!info->pPushConstantRanges) {
// Hand back the empty entry (creating as needed)...
return push_constant_ranges_dict.look_up(PushConstantRanges());
}
// Sort the input ranges to ensure equivalent ranges map to the same id
std::set<const VkPushConstantRange *, PushConstantRangeCompare> sorted;
for (uint32_t i = 0; i < info->pushConstantRangeCount; i++) {
sorted.insert(info->pPushConstantRanges + i);
}
PushConstantRanges ranges(sorted.size());
for (const auto range : sorted) {
ranges.emplace_back(*range);
}
return push_constant_ranges_dict.look_up(std::move(ranges));
}
// Dictionary of canoncial form of the pipeline set layout of descriptor set layouts
static PipelineLayoutSetLayoutsDict pipeline_layout_set_layouts_dict;
// Dictionary of canonical form of the "compatible for set" records
static PipelineLayoutCompatDict pipeline_layout_compat_dict;
static PipelineLayoutCompatId GetCanonicalId(const uint32_t set_index, const PushConstantRangesId pcr_id,
const PipelineLayoutSetLayoutsId set_layouts_id) {
return pipeline_layout_compat_dict.look_up(PipelineLayoutCompatDef(set_index, pcr_id, set_layouts_id));
}
void CoreChecks::PreCallRecordCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout,
void *cpl_state_data) {
create_pipeline_layout_api_state *cpl_state = reinterpret_cast<create_pipeline_layout_api_state *>(cpl_state_data);
if (enabled.gpu_validation) {
GpuPreCallCreatePipelineLayout(pCreateInfo, pAllocator, pPipelineLayout, &cpl_state->new_layouts,
&cpl_state->modified_create_info);
}
}
void CoreChecks::PostCallRecordCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout,
VkResult result) {
// Clean up GPU validation
if (enabled.gpu_validation) {
GpuPostCallCreatePipelineLayout(result);
}
if (VK_SUCCESS != result) return;
std::unique_ptr<PIPELINE_LAYOUT_STATE> pipeline_layout_state(new PIPELINE_LAYOUT_STATE{});
pipeline_layout_state->layout = *pPipelineLayout;
pipeline_layout_state->set_layouts.resize(pCreateInfo->setLayoutCount);
PipelineLayoutSetLayoutsDef set_layouts(pCreateInfo->setLayoutCount);
for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) {
pipeline_layout_state->set_layouts[i] = GetDescriptorSetLayout(this, pCreateInfo->pSetLayouts[i]);
set_layouts[i] = pipeline_layout_state->set_layouts[i]->GetLayoutId();
}
// Get canonical form IDs for the "compatible for set" contents
pipeline_layout_state->push_constant_ranges = GetCanonicalId(pCreateInfo);
auto set_layouts_id = pipeline_layout_set_layouts_dict.look_up(set_layouts);
pipeline_layout_state->compat_for_set.reserve(pCreateInfo->setLayoutCount);
// Create table of "compatible for set N" cannonical forms for trivial accept validation
for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) {
pipeline_layout_state->compat_for_set.emplace_back(
GetCanonicalId(i, pipeline_layout_state->push_constant_ranges, set_layouts_id));
}
pipelineLayoutMap[*pPipelineLayout] = std::move(pipeline_layout_state);
}
void CoreChecks::PostCallRecordCreateDescriptorPool(VkDevice device, const VkDescriptorPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDescriptorPool *pDescriptorPool,
VkResult result) {
if (VK_SUCCESS != result) return;
descriptorPoolMap[*pDescriptorPool] =
std::unique_ptr<DESCRIPTOR_POOL_STATE>(new DESCRIPTOR_POOL_STATE(*pDescriptorPool, pCreateInfo));
}
bool CoreChecks::PreCallValidateResetDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool,
VkDescriptorPoolResetFlags flags) {
// Make sure sets being destroyed are not currently in-use
if (disabled.idle_descriptor_set) return false;
bool skip = false;
DESCRIPTOR_POOL_STATE *pPool = GetDescriptorPoolState(descriptorPool);
if (pPool != nullptr) {
for (auto ds : pPool->sets) {
if (ds && ds->in_use.load()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
HandleToUint64(descriptorPool), "VUID-vkResetDescriptorPool-descriptorPool-00313",
"It is invalid to call vkResetDescriptorPool() with descriptor sets in use by a command buffer.");
if (skip) break;
}
}
}
return skip;
}
void CoreChecks::PostCallRecordResetDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool,
VkDescriptorPoolResetFlags flags, VkResult result) {
if (VK_SUCCESS != result) return;
DESCRIPTOR_POOL_STATE *pPool = GetDescriptorPoolState(descriptorPool);
// TODO: validate flags
// For every set off of this pool, clear it, remove from setMap, and free cvdescriptorset::DescriptorSet
for (auto ds : pPool->sets) {
FreeDescriptorSet(ds);
}
pPool->sets.clear();
// Reset available count for each type and available sets for this pool
for (auto it = pPool->availableDescriptorTypeCount.begin(); it != pPool->availableDescriptorTypeCount.end(); ++it) {
pPool->availableDescriptorTypeCount[it->first] = pPool->maxDescriptorTypeCount[it->first];
}
pPool->availableSets = pPool->maxSets;
}
// Ensure the pool contains enough descriptors and descriptor sets to satisfy
// an allocation request. Fills common_data with the total number of descriptors of each type required,
// as well as DescriptorSetLayout ptrs used for later update.
bool CoreChecks::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo *pAllocateInfo,
VkDescriptorSet *pDescriptorSets, void *ads_state_data) {
// Always update common data
cvdescriptorset::AllocateDescriptorSetsData *ads_state =
reinterpret_cast<cvdescriptorset::AllocateDescriptorSetsData *>(ads_state_data);
UpdateAllocateDescriptorSetsData(pAllocateInfo, ads_state);
// All state checks for AllocateDescriptorSets is done in single function
return ValidateAllocateDescriptorSets(pAllocateInfo, ads_state);
}
// Allocation state was good and call down chain was made so update state based on allocating descriptor sets
void CoreChecks::PostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo *pAllocateInfo,
VkDescriptorSet *pDescriptorSets, VkResult result, void *ads_state_data) {
if (VK_SUCCESS != result) return;
// All the updates are contained in a single cvdescriptorset function
cvdescriptorset::AllocateDescriptorSetsData *ads_state =
reinterpret_cast<cvdescriptorset::AllocateDescriptorSetsData *>(ads_state_data);
PerformAllocateDescriptorSets(pAllocateInfo, pDescriptorSets, ads_state);
}
bool CoreChecks::PreCallValidateFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t count,
const VkDescriptorSet *pDescriptorSets) {
// Make sure that no sets being destroyed are in-flight
bool skip = false;
// First make sure sets being destroyed are not currently in-use
for (uint32_t i = 0; i < count; ++i) {
if (pDescriptorSets[i] != VK_NULL_HANDLE) {
skip |= ValidateIdleDescriptorSet(pDescriptorSets[i], "vkFreeDescriptorSets");
}
}
DESCRIPTOR_POOL_STATE *pool_state = GetDescriptorPoolState(descriptorPool);
if (pool_state && !(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT & pool_state->createInfo.flags)) {
// Can't Free from a NON_FREE pool
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
HandleToUint64(descriptorPool), "VUID-vkFreeDescriptorSets-descriptorPool-00312",
"It is invalid to call vkFreeDescriptorSets() with a pool created without setting "
"VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT.");
}
return skip;
}
void CoreChecks::PreCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t count,
const VkDescriptorSet *pDescriptorSets) {
DESCRIPTOR_POOL_STATE *pool_state = GetDescriptorPoolState(descriptorPool);
// Update available descriptor sets in pool
pool_state->availableSets += count;
// For each freed descriptor add its resources back into the pool as available and remove from pool and setMap
for (uint32_t i = 0; i < count; ++i) {
if (pDescriptorSets[i] != VK_NULL_HANDLE) {
auto descriptor_set = setMap[pDescriptorSets[i]].get();
uint32_t type_index = 0, descriptor_count = 0;
for (uint32_t j = 0; j < descriptor_set->GetBindingCount(); ++j) {
type_index = static_cast<uint32_t>(descriptor_set->GetTypeFromIndex(j));
descriptor_count = descriptor_set->GetDescriptorCountFromIndex(j);
pool_state->availableDescriptorTypeCount[type_index] += descriptor_count;
}
FreeDescriptorSet(descriptor_set);
pool_state->sets.erase(descriptor_set);
}
}
}
bool CoreChecks::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
const VkWriteDescriptorSet *pDescriptorWrites, uint32_t descriptorCopyCount,
const VkCopyDescriptorSet *pDescriptorCopies) {
// First thing to do is perform map look-ups.
// NOTE : UpdateDescriptorSets is somewhat unique in that it's operating on a number of DescriptorSets
// so we can't just do a single map look-up up-front, but do them individually in functions below
// Now make call(s) that validate state, but don't perform state updates in this function
// Note, here DescriptorSets is unique in that we don't yet have an instance. Using a helper function in the
// namespace which will parse params and make calls into specific class instances
return ValidateUpdateDescriptorSets(descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies,
"vkUpdateDescriptorSets()");
}
void CoreChecks::PreCallRecordUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
const VkWriteDescriptorSet *pDescriptorWrites, uint32_t descriptorCopyCount,
const VkCopyDescriptorSet *pDescriptorCopies) {
cvdescriptorset::PerformUpdateDescriptorSets(this, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount,
pDescriptorCopies);
}
void CoreChecks::PostCallRecordAllocateCommandBuffers(VkDevice device, const VkCommandBufferAllocateInfo *pCreateInfo,
VkCommandBuffer *pCommandBuffer, VkResult result) {
if (VK_SUCCESS != result) return;
auto pPool = GetCommandPoolState(pCreateInfo->commandPool);
if (pPool) {
for (uint32_t i = 0; i < pCreateInfo->commandBufferCount; i++) {
// Add command buffer to its commandPool map
pPool->commandBuffers.insert(pCommandBuffer[i]);
std::unique_ptr<CMD_BUFFER_STATE> pCB(new CMD_BUFFER_STATE{});
pCB->createInfo = *pCreateInfo;
pCB->device = device;
// Add command buffer to map
commandBufferMap[pCommandBuffer[i]] = std::move(pCB);
ResetCommandBufferState(pCommandBuffer[i]);
}
}
}
// Add bindings between the given cmd buffer & framebuffer and the framebuffer's children
void CoreChecks::AddFramebufferBinding(CMD_BUFFER_STATE *cb_state, FRAMEBUFFER_STATE *fb_state) {
AddCommandBufferBinding(&fb_state->cb_bindings, {HandleToUint64(fb_state->framebuffer), kVulkanObjectTypeFramebuffer},
cb_state);
const uint32_t attachmentCount = fb_state->createInfo.attachmentCount;
for (uint32_t attachment = 0; attachment < attachmentCount; ++attachment) {
auto view_state = GetAttachmentImageViewState(fb_state, attachment);
if (view_state) {
AddCommandBufferBindingImageView(cb_state, view_state);
}
}
}
bool CoreChecks::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
if (!cb_state) return false;
bool skip = false;
if (cb_state->in_use.load()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00049",
"Calling vkBeginCommandBuffer() on active command buffer %s before it has completed. You must check "
"command buffer fence before this call.",
report_data->FormatHandle(commandBuffer).c_str());
}
if (cb_state->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
// Secondary Command Buffer
const VkCommandBufferInheritanceInfo *pInfo = pBeginInfo->pInheritanceInfo;
if (!pInfo) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00051",
"vkBeginCommandBuffer(): Secondary Command Buffer (%s) must have inheritance info.",
report_data->FormatHandle(commandBuffer).c_str());
} else {
if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
assert(pInfo->renderPass);
auto framebuffer = GetFramebufferState(pInfo->framebuffer);
if (framebuffer) {
if (framebuffer->createInfo.renderPass != pInfo->renderPass) {
// renderPass that framebuffer was created with must be compatible with local renderPass
skip |= ValidateRenderPassCompatibility("framebuffer", framebuffer->rp_state.get(), "command buffer",
GetRenderPassState(pInfo->renderPass), "vkBeginCommandBuffer()",
"VUID-VkCommandBufferBeginInfo-flags-00055");
}
}
}
if ((pInfo->occlusionQueryEnable == VK_FALSE || enabled_features.core.occlusionQueryPrecise == VK_FALSE) &&
(pInfo->queryFlags & VK_QUERY_CONTROL_PRECISE_BIT)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00052",
"vkBeginCommandBuffer(): Secondary Command Buffer (%s) must not have VK_QUERY_CONTROL_PRECISE_BIT if "
"occulusionQuery is disabled or the device does not support precise occlusion queries.",
report_data->FormatHandle(commandBuffer).c_str());
}
}
if (pInfo && pInfo->renderPass != VK_NULL_HANDLE) {
auto renderPass = GetRenderPassState(pInfo->renderPass);
if (renderPass) {
if (pInfo->subpass >= renderPass->createInfo.subpassCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-VkCommandBufferBeginInfo-flags-00054",
"vkBeginCommandBuffer(): Secondary Command Buffers (%s) must have a subpass index (%d) that is "
"less than the number of subpasses (%d).",
report_data->FormatHandle(commandBuffer).c_str(), pInfo->subpass,
renderPass->createInfo.subpassCount);
}
}
}
}
if (CB_RECORDING == cb_state->state) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00049",
"vkBeginCommandBuffer(): Cannot call Begin on command buffer (%s) in the RECORDING state. Must first call "
"vkEndCommandBuffer().",
report_data->FormatHandle(commandBuffer).c_str());
} else if (CB_RECORDED == cb_state->state || CB_INVALID_COMPLETE == cb_state->state) {
VkCommandPool cmdPool = cb_state->createInfo.commandPool;
auto pPool = GetCommandPoolState(cmdPool);
if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & pPool->createFlags)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00050",
"Call to vkBeginCommandBuffer() on command buffer (%s) attempts to implicitly reset cmdBuffer created from "
"command pool (%s) that does NOT have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.",
report_data->FormatHandle(commandBuffer).c_str(), report_data->FormatHandle(cmdPool).c_str());
}
}
auto chained_device_group_struct = lvl_find_in_chain<VkDeviceGroupCommandBufferBeginInfo>(pBeginInfo->pNext);
if (chained_device_group_struct) {
skip |= ValidateDeviceMaskToPhysicalDeviceCount(
chained_device_group_struct->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer),
"VUID-VkDeviceGroupCommandBufferBeginInfo-deviceMask-00106");
skip |=
ValidateDeviceMaskToZero(chained_device_group_struct->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-VkDeviceGroupCommandBufferBeginInfo-deviceMask-00107");
}
return skip;
}
void CoreChecks::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
if (!cb_state) return;
// This implicitly resets the Cmd Buffer so make sure any fence is done and then clear memory references
ClearCmdBufAndMemReferences(cb_state);
if (cb_state->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
// Secondary Command Buffer
const VkCommandBufferInheritanceInfo *pInfo = pBeginInfo->pInheritanceInfo;
if (pInfo) {
if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
assert(pInfo->renderPass);
auto framebuffer = GetFramebufferState(pInfo->framebuffer);
if (framebuffer) {
// Connect this framebuffer and its children to this cmdBuffer
AddFramebufferBinding(cb_state, framebuffer);
}
}
}
}
if (CB_RECORDED == cb_state->state || CB_INVALID_COMPLETE == cb_state->state) {
ResetCommandBufferState(commandBuffer);
}
// Set updated state here in case implicit reset occurs above
cb_state->state = CB_RECORDING;
cb_state->beginInfo = *pBeginInfo;
if (cb_state->beginInfo.pInheritanceInfo) {
cb_state->inheritanceInfo = *(cb_state->beginInfo.pInheritanceInfo);
cb_state->beginInfo.pInheritanceInfo = &cb_state->inheritanceInfo;
// If we are a secondary command-buffer and inheriting. Update the items we should inherit.
if ((cb_state->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) &&
(cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
cb_state->activeRenderPass = GetRenderPassState(cb_state->beginInfo.pInheritanceInfo->renderPass);
cb_state->activeSubpass = cb_state->beginInfo.pInheritanceInfo->subpass;
cb_state->activeFramebuffer = cb_state->beginInfo.pInheritanceInfo->framebuffer;
cb_state->framebuffers.insert(cb_state->beginInfo.pInheritanceInfo->framebuffer);
}
}
auto chained_device_group_struct = lvl_find_in_chain<VkDeviceGroupCommandBufferBeginInfo>(pBeginInfo->pNext);
if (chained_device_group_struct) {
cb_state->initial_device_mask = chained_device_group_struct->deviceMask;
} else {
cb_state->initial_device_mask = (1 << physical_device_count) - 1;
}
}
bool CoreChecks::PreCallValidateEndCommandBuffer(VkCommandBuffer commandBuffer) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
if (!cb_state) return false;
bool skip = false;
if ((VK_COMMAND_BUFFER_LEVEL_PRIMARY == cb_state->createInfo.level) ||
!(cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
// This needs spec clarification to update valid usage, see comments in PR:
// https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/165
skip |= InsideRenderPass(cb_state, "vkEndCommandBuffer()", "VUID-vkEndCommandBuffer-commandBuffer-00060");
}
skip |= ValidateCmd(cb_state, CMD_ENDCOMMANDBUFFER, "vkEndCommandBuffer()");
for (auto query : cb_state->activeQueries) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkEndCommandBuffer-commandBuffer-00061",
"Ending command buffer with in progress query: queryPool %s, query %d.",
report_data->FormatHandle(query.pool).c_str(), query.query);
}
return skip;
}
void CoreChecks::PostCallRecordEndCommandBuffer(VkCommandBuffer commandBuffer, VkResult result) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
if (!cb_state) return;
// Cached validation is specific to a specific recording of a specific command buffer.
for (auto descriptor_set : cb_state->validated_descriptor_sets) {
descriptor_set->ClearCachedValidation(cb_state);
}
cb_state->validated_descriptor_sets.clear();
if (VK_SUCCESS == result) {
cb_state->state = CB_RECORDED;
}
}
bool CoreChecks::PreCallValidateResetCommandBuffer(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags) {
bool skip = false;
CMD_BUFFER_STATE *pCB = GetCBState(commandBuffer);
if (!pCB) return false;
VkCommandPool cmdPool = pCB->createInfo.commandPool;
auto pPool = GetCommandPoolState(cmdPool);
if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & pPool->createFlags)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkResetCommandBuffer-commandBuffer-00046",
"Attempt to reset command buffer (%s) created from command pool (%s) that does NOT have the "
"VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.",
report_data->FormatHandle(commandBuffer).c_str(), report_data->FormatHandle(cmdPool).c_str());
}
skip |= CheckCommandBufferInFlight(pCB, "reset", "VUID-vkResetCommandBuffer-commandBuffer-00045");
return skip;
}
void CoreChecks::PostCallRecordResetCommandBuffer(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags, VkResult result) {
if (VK_SUCCESS == result) {
ResetCommandBufferState(commandBuffer);
}
}
static const char *GetPipelineTypeName(VkPipelineBindPoint pipelineBindPoint) {
switch (pipelineBindPoint) {
case VK_PIPELINE_BIND_POINT_GRAPHICS:
return "graphics";
case VK_PIPELINE_BIND_POINT_COMPUTE:
return "compute";
case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV:
return "ray-tracing";
default:
return "unknown";
}
}
bool CoreChecks::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
VkPipeline pipeline) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdBindPipeline()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdBindPipeline-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_BINDPIPELINE, "vkCmdBindPipeline()");
static const std::map<VkPipelineBindPoint, std::string> bindpoint_errors = {
std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, "VUID-vkCmdBindPipeline-pipelineBindPoint-00777"),
std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, "VUID-vkCmdBindPipeline-pipelineBindPoint-00778"),
std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, "VUID-vkCmdBindPipeline-pipelineBindPoint-02391")};
skip |= ValidatePipelineBindPoint(cb_state, pipelineBindPoint, "vkCmdBindPipeline()", bindpoint_errors);
auto pipeline_state = GetPipelineState(pipeline);
assert(pipeline_state);
const auto &pipeline_state_bind_point = pipeline_state->getPipelineType();
if (pipelineBindPoint != pipeline_state_bind_point) {
if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdBindPipeline-pipelineBindPoint-00779",
"Cannot bind a pipeline of type %s to the graphics pipeline bind point",
GetPipelineTypeName(pipeline_state_bind_point));
} else if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_COMPUTE) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdBindPipeline-pipelineBindPoint-00780",
"Cannot bind a pipeline of type %s to the compute pipeline bind point",
GetPipelineTypeName(pipeline_state_bind_point));
} else if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_RAY_TRACING_NV) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdBindPipeline-pipelineBindPoint-02392",
"Cannot bind a pipeline of type %s to the ray-tracing pipeline bind point",
GetPipelineTypeName(pipeline_state_bind_point));
}
}
return skip;
}
void CoreChecks::PreCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
VkPipeline pipeline) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
auto pipe_state = GetPipelineState(pipeline);
if (VK_PIPELINE_BIND_POINT_GRAPHICS == pipelineBindPoint) {
cb_state->status &= ~cb_state->static_status;
cb_state->static_status = MakeStaticStateMask(pipe_state->graphicsPipelineCI.ptr()->pDynamicState);
cb_state->status |= cb_state->static_status;
}
cb_state->lastBound[pipelineBindPoint].pipeline_state = pipe_state;
SetPipelineState(pipe_state);
AddCommandBufferBinding(&pipe_state->cb_bindings, {HandleToUint64(pipeline), kVulkanObjectTypePipeline}, cb_state);
}
bool CoreChecks::PreCallValidateCmdSetViewport(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount,
const VkViewport *pViewports) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip =
ValidateCmdQueueFlags(cb_state, "vkCmdSetViewport()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetViewport-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETVIEWPORT, "vkCmdSetViewport()");
if (cb_state->static_status & CBSTATUS_VIEWPORT_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewport-None-01221",
"vkCmdSetViewport(): pipeline was created without VK_DYNAMIC_STATE_VIEWPORT flag.");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetViewport(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount,
const VkViewport *pViewports) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->viewportMask |= ((1u << viewportCount) - 1u) << firstViewport;
cb_state->status |= CBSTATUS_VIEWPORT_SET;
}
bool CoreChecks::PreCallValidateCmdSetScissor(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount,
const VkRect2D *pScissors) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip =
ValidateCmdQueueFlags(cb_state, "vkCmdSetScissor()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetScissor-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETSCISSOR, "vkCmdSetScissor()");
if (cb_state->static_status & CBSTATUS_SCISSOR_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-None-00590",
"vkCmdSetScissor(): pipeline was created without VK_DYNAMIC_STATE_SCISSOR flag..");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetScissor(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount,
const VkRect2D *pScissors) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->scissorMask |= ((1u << scissorCount) - 1u) << firstScissor;
cb_state->status |= CBSTATUS_SCISSOR_SET;
}
bool CoreChecks::PreCallValidateCmdSetExclusiveScissorNV(VkCommandBuffer commandBuffer, uint32_t firstExclusiveScissor,
uint32_t exclusiveScissorCount, const VkRect2D *pExclusiveScissors) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetExclusiveScissorNV()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetExclusiveScissorNV-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETEXCLUSIVESCISSORNV, "vkCmdSetExclusiveScissorNV()");
if (cb_state->static_status & CBSTATUS_EXCLUSIVE_SCISSOR_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-None-02032",
"vkCmdSetExclusiveScissorNV(): pipeline was created without VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV flag.");
}
if (!enabled_features.exclusive_scissor.exclusiveScissor) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-None-02031",
"vkCmdSetExclusiveScissorNV: The exclusiveScissor feature is disabled.");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetExclusiveScissorNV(VkCommandBuffer commandBuffer, uint32_t firstExclusiveScissor,
uint32_t exclusiveScissorCount, const VkRect2D *pExclusiveScissors) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
// TODO: We don't have VUIDs for validating that all exclusive scissors have been set.
// cb_state->exclusiveScissorMask |= ((1u << exclusiveScissorCount) - 1u) << firstExclusiveScissor;
cb_state->status |= CBSTATUS_EXCLUSIVE_SCISSOR_SET;
}
bool CoreChecks::PreCallValidateCmdBindShadingRateImageNV(VkCommandBuffer commandBuffer, VkImageView imageView,
VkImageLayout imageLayout) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdBindShadingRateImageNV()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdBindShadingRateImageNV-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_BINDSHADINGRATEIMAGENV, "vkCmdBindShadingRateImageNV()");
if (!enabled_features.shading_rate_image.shadingRateImage) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdBindShadingRateImageNV-None-02058",
"vkCmdBindShadingRateImageNV: The shadingRateImage feature is disabled.");
}
if (imageView != VK_NULL_HANDLE) {
auto view_state = GetImageViewState(imageView);
auto &ivci = view_state->create_info;
if (!view_state || (ivci.viewType != VK_IMAGE_VIEW_TYPE_2D && ivci.viewType != VK_IMAGE_VIEW_TYPE_2D_ARRAY)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
HandleToUint64(imageView), "VUID-vkCmdBindShadingRateImageNV-imageView-02059",
"vkCmdBindShadingRateImageNV: If imageView is not VK_NULL_HANDLE, it must be a valid "
"VkImageView handle of type VK_IMAGE_VIEW_TYPE_2D or VK_IMAGE_VIEW_TYPE_2D_ARRAY.");
}
if (view_state && ivci.format != VK_FORMAT_R8_UINT) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT, HandleToUint64(imageView),
"VUID-vkCmdBindShadingRateImageNV-imageView-02060",
"vkCmdBindShadingRateImageNV: If imageView is not VK_NULL_HANDLE, it must have a format of VK_FORMAT_R8_UINT.");
}
const VkImageCreateInfo *ici = view_state ? &GetImageState(view_state->create_info.image)->createInfo : nullptr;
if (ici && !(ici->usage & VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,
HandleToUint64(imageView), "VUID-vkCmdBindShadingRateImageNV-imageView-02061",
"vkCmdBindShadingRateImageNV: If imageView is not VK_NULL_HANDLE, the image must have been "
"created with VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV set.");
}
if (view_state) {
auto image_state = GetImageState(view_state->create_info.image);
bool hit_error = false;
// XXX TODO: While the VUID says "each subresource", only the base mip level is
// actually used. Since we don't have an existing convenience function to iterate
// over all mip levels, just don't bother with non-base levels.
VkImageSubresourceRange &range = view_state->create_info.subresourceRange;
VkImageSubresourceLayers subresource = {range.aspectMask, range.baseMipLevel, range.baseArrayLayer, range.layerCount};
if (image_state) {
skip |= VerifyImageLayout(cb_state, image_state, subresource, imageLayout, VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV,
"vkCmdCopyImage()", "VUID-vkCmdBindShadingRateImageNV-imageLayout-02063",
"VUID-vkCmdBindShadingRateImageNV-imageView-02062", &hit_error);
}
}
}
return skip;
}
void CoreChecks::PreCallRecordCmdBindShadingRateImageNV(VkCommandBuffer commandBuffer, VkImageView imageView,
VkImageLayout imageLayout) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
if (imageView != VK_NULL_HANDLE) {
auto view_state = GetImageViewState(imageView);
AddCommandBufferBindingImageView(cb_state, view_state);
}
}
bool CoreChecks::PreCallValidateCmdSetViewportShadingRatePaletteNV(VkCommandBuffer commandBuffer, uint32_t firstViewport,
uint32_t viewportCount,
const VkShadingRatePaletteNV *pShadingRatePalettes) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetViewportShadingRatePaletteNV()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetViewportShadingRatePaletteNV-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETVIEWPORTSHADINGRATEPALETTENV, "vkCmdSetViewportShadingRatePaletteNV()");
if (!enabled_features.shading_rate_image.shadingRateImage) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-None-02064",
"vkCmdSetViewportShadingRatePaletteNV: The shadingRateImage feature is disabled.");
}
if (cb_state->static_status & CBSTATUS_SHADING_RATE_PALETTE_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-None-02065",
"vkCmdSetViewportShadingRatePaletteNV(): pipeline was created without "
"VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV flag.");
}
for (uint32_t i = 0; i < viewportCount; ++i) {
auto *palette = &pShadingRatePalettes[i];
if (palette->shadingRatePaletteEntryCount == 0 ||
palette->shadingRatePaletteEntryCount > phys_dev_ext_props.shading_rate_image_props.shadingRatePaletteSize) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-VkShadingRatePaletteNV-shadingRatePaletteEntryCount-02071",
"vkCmdSetViewportShadingRatePaletteNV: shadingRatePaletteEntryCount must be between 1 and shadingRatePaletteSize.");
}
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetViewportShadingRatePaletteNV(VkCommandBuffer commandBuffer, uint32_t firstViewport,
uint32_t viewportCount,
const VkShadingRatePaletteNV *pShadingRatePalettes) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
// TODO: We don't have VUIDs for validating that all shading rate palettes have been set.
// cb_state->shadingRatePaletteMask |= ((1u << viewportCount) - 1u) << firstViewport;
cb_state->status |= CBSTATUS_SHADING_RATE_PALETTE_SET;
}
bool CoreChecks::PreCallValidateCmdSetLineWidth(VkCommandBuffer commandBuffer, float lineWidth) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetLineWidth()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetLineWidth-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETLINEWIDTH, "vkCmdSetLineWidth()");
if (cb_state->static_status & CBSTATUS_LINE_WIDTH_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetLineWidth-None-00787",
"vkCmdSetLineWidth called but pipeline was created without VK_DYNAMIC_STATE_LINE_WIDTH flag.");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetLineWidth(VkCommandBuffer commandBuffer, float lineWidth) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->status |= CBSTATUS_LINE_WIDTH_SET;
}
bool CoreChecks::PreCallValidateCmdSetDepthBias(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp,
float depthBiasSlopeFactor) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetDepthBias()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetDepthBias-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETDEPTHBIAS, "vkCmdSetDepthBias()");
if (cb_state->static_status & CBSTATUS_DEPTH_BIAS_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetDepthBias-None-00789",
"vkCmdSetDepthBias(): pipeline was created without VK_DYNAMIC_STATE_DEPTH_BIAS flag..");
}
if ((depthBiasClamp != 0.0) && (!enabled_features.core.depthBiasClamp)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetDepthBias-depthBiasClamp-00790",
"vkCmdSetDepthBias(): the depthBiasClamp device feature is disabled: the depthBiasClamp parameter must "
"be set to 0.0.");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetDepthBias(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp,
float depthBiasSlopeFactor) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->status |= CBSTATUS_DEPTH_BIAS_SET;
}
bool CoreChecks::PreCallValidateCmdSetBlendConstants(VkCommandBuffer commandBuffer, const float blendConstants[4]) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetBlendConstants()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetBlendConstants-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETBLENDCONSTANTS, "vkCmdSetBlendConstants()");
if (cb_state->static_status & CBSTATUS_BLEND_CONSTANTS_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetBlendConstants-None-00612",
"vkCmdSetBlendConstants(): pipeline was created without VK_DYNAMIC_STATE_BLEND_CONSTANTS flag..");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetBlendConstants(VkCommandBuffer commandBuffer, const float blendConstants[4]) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->status |= CBSTATUS_BLEND_CONSTANTS_SET;
}
bool CoreChecks::PreCallValidateCmdSetDepthBounds(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetDepthBounds()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetDepthBounds-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETDEPTHBOUNDS, "vkCmdSetDepthBounds()");
if (cb_state->static_status & CBSTATUS_DEPTH_BOUNDS_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetDepthBounds-None-00599",
"vkCmdSetDepthBounds(): pipeline was created without VK_DYNAMIC_STATE_DEPTH_BOUNDS flag..");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetDepthBounds(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->status |= CBSTATUS_DEPTH_BOUNDS_SET;
}
bool CoreChecks::PreCallValidateCmdSetStencilCompareMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask,
uint32_t compareMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetStencilCompareMask()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetStencilCompareMask-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETSTENCILCOMPAREMASK, "vkCmdSetStencilCompareMask()");
if (cb_state->static_status & CBSTATUS_STENCIL_READ_MASK_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetStencilCompareMask-None-00602",
"vkCmdSetStencilCompareMask(): pipeline was created without VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK flag..");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetStencilCompareMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask,
uint32_t compareMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->status |= CBSTATUS_STENCIL_READ_MASK_SET;
}
bool CoreChecks::PreCallValidateCmdSetStencilWriteMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask,
uint32_t writeMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetStencilWriteMask()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetStencilWriteMask-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETSTENCILWRITEMASK, "vkCmdSetStencilWriteMask()");
if (cb_state->static_status & CBSTATUS_STENCIL_WRITE_MASK_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetStencilWriteMask-None-00603",
"vkCmdSetStencilWriteMask(): pipeline was created without VK_DYNAMIC_STATE_STENCIL_WRITE_MASK flag..");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetStencilWriteMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask,
uint32_t writeMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->status |= CBSTATUS_STENCIL_WRITE_MASK_SET;
}
bool CoreChecks::PreCallValidateCmdSetStencilReference(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask,
uint32_t reference) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetStencilReference()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdSetStencilReference-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETSTENCILREFERENCE, "vkCmdSetStencilReference()");
if (cb_state->static_status & CBSTATUS_STENCIL_REFERENCE_SET) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetStencilReference-None-00604",
"vkCmdSetStencilReference(): pipeline was created without VK_DYNAMIC_STATE_STENCIL_REFERENCE flag..");
}
return skip;
}
void CoreChecks::PreCallRecordCmdSetStencilReference(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask,
uint32_t reference) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->status |= CBSTATUS_STENCIL_REFERENCE_SET;
}
// Update pipeline_layout bind points applying the "Pipeline Layout Compatibility" rules
void CoreChecks::UpdateLastBoundDescriptorSets(CMD_BUFFER_STATE *cb_state, VkPipelineBindPoint pipeline_bind_point,
const PIPELINE_LAYOUT_STATE *pipeline_layout, uint32_t first_set, uint32_t set_count,
const std::vector<cvdescriptorset::DescriptorSet *> descriptor_sets,
uint32_t dynamic_offset_count, const uint32_t *p_dynamic_offsets) {
// Defensive
assert(set_count);
if (0 == set_count) return;
assert(pipeline_layout);
if (!pipeline_layout) return;
uint32_t required_size = first_set + set_count;
const uint32_t last_binding_index = required_size - 1;
assert(last_binding_index < pipeline_layout->compat_for_set.size());
// Some useful shorthand
auto &last_bound = cb_state->lastBound[pipeline_bind_point];
auto &bound_sets = last_bound.boundDescriptorSets;
auto &dynamic_offsets = last_bound.dynamicOffsets;
auto &bound_compat_ids = last_bound.compat_id_for_set;
auto &pipe_compat_ids = pipeline_layout->compat_for_set;
const uint32_t current_size = static_cast<uint32_t>(bound_sets.size());
assert(current_size == dynamic_offsets.size());
assert(current_size == bound_compat_ids.size());
// We need this three times in this function, but nowhere else
auto push_descriptor_cleanup = [&last_bound](const cvdescriptorset::DescriptorSet *ds) -> bool {
if (ds && ds->IsPushDescriptor()) {
assert(ds == last_bound.push_descriptor_set.get());
last_bound.push_descriptor_set = nullptr;
return true;
}
return false;
};
// Clean up the "disturbed" before and after the range to be set
if (required_size < current_size) {
if (bound_compat_ids[last_binding_index] != pipe_compat_ids[last_binding_index]) {
// We're disturbing those after last, we'll shrink below, but first need to check for and cleanup the push_descriptor
for (auto set_idx = required_size; set_idx < current_size; ++set_idx) {
if (push_descriptor_cleanup(bound_sets[set_idx])) break;
}
} else {
// We're not disturbing past last, so leave the upper binding data alone.
required_size = current_size;
}
}
// We resize if we need more set entries or if those past "last" are disturbed
if (required_size != current_size) {
// TODO: put these size tied things in a struct (touches many lines)
bound_sets.resize(required_size);
dynamic_offsets.resize(required_size);
bound_compat_ids.resize(required_size);
}
// For any previously bound sets, need to set them to "invalid" if they were disturbed by this update
for (uint32_t set_idx = 0; set_idx < first_set; ++set_idx) {
if (bound_compat_ids[set_idx] != pipe_compat_ids[set_idx]) {
push_descriptor_cleanup(bound_sets[set_idx]);
bound_sets[set_idx] = nullptr;
dynamic_offsets[set_idx].clear();
bound_compat_ids[set_idx] = pipe_compat_ids[set_idx];
}
}
// Now update the bound sets with the input sets
const uint32_t *input_dynamic_offsets = p_dynamic_offsets; // "read" pointer for dynamic offset data
for (uint32_t input_idx = 0; input_idx < set_count; input_idx++) {
auto set_idx = input_idx + first_set; // set_idx is index within layout, input_idx is index within input descriptor sets
cvdescriptorset::DescriptorSet *descriptor_set = descriptor_sets[input_idx];
// Record binding (or push)
if (descriptor_set != last_bound.push_descriptor_set.get()) {
// Only cleanup the push descriptors if they aren't the currently used set.
push_descriptor_cleanup(bound_sets[set_idx]);
}
bound_sets[set_idx] = descriptor_set;
bound_compat_ids[set_idx] = pipe_compat_ids[set_idx]; // compat ids are canonical *per* set index
if (descriptor_set) {
auto set_dynamic_descriptor_count = descriptor_set->GetDynamicDescriptorCount();
// TODO: Add logic for tracking push_descriptor offsets (here or in caller)
if (set_dynamic_descriptor_count && input_dynamic_offsets) {
const uint32_t *end_offset = input_dynamic_offsets + set_dynamic_descriptor_count;
dynamic_offsets[set_idx] = std::vector<uint32_t>(input_dynamic_offsets, end_offset);
input_dynamic_offsets = end_offset;
assert(input_dynamic_offsets <= (p_dynamic_offsets + dynamic_offset_count));
} else {
dynamic_offsets[set_idx].clear();
}
if (!descriptor_set->IsPushDescriptor()) {
// Can't cache validation of push_descriptors
cb_state->validated_descriptor_sets.insert(descriptor_set);
}
}
}
}
// Update the bound state for the bind point, including the effects of incompatible pipeline layouts
void CoreChecks::PreCallRecordCmdBindDescriptorSets(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout, uint32_t firstSet, uint32_t setCount,
const VkDescriptorSet *pDescriptorSets, uint32_t dynamicOffsetCount,
const uint32_t *pDynamicOffsets) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
auto pipeline_layout = GetPipelineLayout(layout);
std::vector<cvdescriptorset::DescriptorSet *> descriptor_sets;
descriptor_sets.reserve(setCount);
// Construct a list of the descriptors
bool found_non_null = false;
for (uint32_t i = 0; i < setCount; i++) {
cvdescriptorset::DescriptorSet *descriptor_set = GetSetNode(pDescriptorSets[i]);
descriptor_sets.emplace_back(descriptor_set);
found_non_null |= descriptor_set != nullptr;
}
if (found_non_null) { // which implies setCount > 0
UpdateLastBoundDescriptorSets(cb_state, pipelineBindPoint, pipeline_layout, firstSet, setCount, descriptor_sets,
dynamicOffsetCount, pDynamicOffsets);
cb_state->lastBound[pipelineBindPoint].pipeline_layout = layout;
}
}
static bool ValidateDynamicOffsetAlignment(const debug_report_data *report_data, const VkDescriptorSetLayoutBinding *binding,
VkDescriptorType test_type, VkDeviceSize alignment, const uint32_t *pDynamicOffsets,
const char *err_msg, const char *limit_name, uint32_t *offset_idx) {
bool skip = false;
if (binding->descriptorType == test_type) {
const auto end_idx = *offset_idx + binding->descriptorCount;
for (uint32_t current_idx = *offset_idx; current_idx < end_idx; current_idx++) {
if (SafeModulo(pDynamicOffsets[current_idx], alignment) != 0) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, err_msg,
"vkCmdBindDescriptorSets(): pDynamicOffsets[%d] is %d but must be a multiple of device limit %s 0x%" PRIxLEAST64
".",
current_idx, pDynamicOffsets[current_idx], limit_name, alignment);
}
}
*offset_idx = end_idx;
}
return skip;
}
bool CoreChecks::PreCallValidateCmdBindDescriptorSets(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout, uint32_t firstSet, uint32_t setCount,
const VkDescriptorSet *pDescriptorSets, uint32_t dynamicOffsetCount,
const uint32_t *pDynamicOffsets) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = false;
skip |= ValidateCmdQueueFlags(cb_state, "vkCmdBindDescriptorSets()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdBindDescriptorSets-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_BINDDESCRIPTORSETS, "vkCmdBindDescriptorSets()");
// Track total count of dynamic descriptor types to make sure we have an offset for each one
uint32_t total_dynamic_descriptors = 0;
string error_string = "";
uint32_t last_set_index = firstSet + setCount - 1;
if (last_set_index >= cb_state->lastBound[pipelineBindPoint].boundDescriptorSets.size()) {
cb_state->lastBound[pipelineBindPoint].boundDescriptorSets.resize(last_set_index + 1);
cb_state->lastBound[pipelineBindPoint].dynamicOffsets.resize(last_set_index + 1);
cb_state->lastBound[pipelineBindPoint].compat_id_for_set.resize(last_set_index + 1);
}
auto pipeline_layout = GetPipelineLayout(layout);
for (uint32_t set_idx = 0; set_idx < setCount; set_idx++) {
cvdescriptorset::DescriptorSet *descriptor_set = GetSetNode(pDescriptorSets[set_idx]);
if (descriptor_set) {
// Verify that set being bound is compatible with overlapping setLayout of pipelineLayout
if (!VerifySetLayoutCompatibility(descriptor_set, pipeline_layout, set_idx + firstSet, error_string)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
HandleToUint64(pDescriptorSets[set_idx]), "VUID-vkCmdBindDescriptorSets-pDescriptorSets-00358",
"descriptorSet #%u being bound is not compatible with overlapping descriptorSetLayout at index %u of "
"pipelineLayout %s due to: %s.",
set_idx, set_idx + firstSet, report_data->FormatHandle(layout).c_str(), error_string.c_str());
}
auto set_dynamic_descriptor_count = descriptor_set->GetDynamicDescriptorCount();
if (set_dynamic_descriptor_count) {
// First make sure we won't overstep bounds of pDynamicOffsets array
if ((total_dynamic_descriptors + set_dynamic_descriptor_count) > dynamicOffsetCount) {
// Test/report this here, such that we don't run past the end of pDynamicOffsets in the else clause
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
HandleToUint64(pDescriptorSets[set_idx]), "VUID-vkCmdBindDescriptorSets-dynamicOffsetCount-00359",
"descriptorSet #%u (%s) requires %u dynamicOffsets, but only %u dynamicOffsets are left in "
"pDynamicOffsets array. There must be one dynamic offset for each dynamic descriptor being bound.",
set_idx, report_data->FormatHandle(pDescriptorSets[set_idx]).c_str(),
descriptor_set->GetDynamicDescriptorCount(), (dynamicOffsetCount - total_dynamic_descriptors));
// Set the number found to the maximum to prevent duplicate messages, or subsquent descriptor sets from
// testing against the "short tail" we're skipping below.
total_dynamic_descriptors = dynamicOffsetCount;
} else { // Validate dynamic offsets and Dynamic Offset Minimums
uint32_t cur_dyn_offset = total_dynamic_descriptors;
const auto dsl = descriptor_set->GetLayout();
const auto binding_count = dsl->GetBindingCount();
const auto &limits = phys_dev_props.limits;
for (uint32_t binding_idx = 0; binding_idx < binding_count; binding_idx++) {
const auto *binding = dsl->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
skip |= ValidateDynamicOffsetAlignment(report_data, binding, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
limits.minUniformBufferOffsetAlignment, pDynamicOffsets,
"VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01971",
"minUniformBufferOffsetAlignment", &cur_dyn_offset);
skip |= ValidateDynamicOffsetAlignment(report_data, binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC,
limits.minStorageBufferOffsetAlignment, pDynamicOffsets,
"VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01972",
"minStorageBufferOffsetAlignment", &cur_dyn_offset);
}
// Keep running total of dynamic descriptor count to verify at the end
total_dynamic_descriptors += set_dynamic_descriptor_count;
}
}
} else {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
HandleToUint64(pDescriptorSets[set_idx]), kVUID_Core_DrawState_InvalidSet,
"Attempt to bind descriptor set %s that doesn't exist!",
report_data->FormatHandle(pDescriptorSets[set_idx]).c_str());
}
}
// dynamicOffsetCount must equal the total number of dynamic descriptors in the sets being bound
if (total_dynamic_descriptors != dynamicOffsetCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdBindDescriptorSets-dynamicOffsetCount-00359",
"Attempting to bind %u descriptorSets with %u dynamic descriptors, but dynamicOffsetCount is %u. It should "
"exactly match the number of dynamic descriptors.",
setCount, total_dynamic_descriptors, dynamicOffsetCount);
}
return skip;
}
// Validates that the supplied bind point is supported for the command buffer (vis. the command pool)
// Takes array of error codes as some of the VUID's (e.g. vkCmdBindPipeline) are written per bindpoint
// TODO add vkCmdBindPipeline bind_point validation using this call.
bool CoreChecks::ValidatePipelineBindPoint(CMD_BUFFER_STATE *cb_state, VkPipelineBindPoint bind_point, const char *func_name,
const std::map<VkPipelineBindPoint, std::string> &bind_errors) {
bool skip = false;
auto pool = GetCommandPoolState(cb_state->createInfo.commandPool);
if (pool) { // The loss of a pool in a recording cmd is reported in DestroyCommandPool
static const std::map<VkPipelineBindPoint, VkQueueFlags> flag_mask = {
std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, static_cast<VkQueueFlags>(VK_QUEUE_GRAPHICS_BIT)),
std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, static_cast<VkQueueFlags>(VK_QUEUE_COMPUTE_BIT)),
std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_NV,
static_cast<VkQueueFlags>(VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)),
};
const auto &qfp = GetPhysicalDeviceState()->queue_family_properties[pool->queueFamilyIndex];
if (0 == (qfp.queueFlags & flag_mask.at(bind_point))) {
const std::string &error = bind_errors.at(bind_point);
auto cb_u64 = HandleToUint64(cb_state->commandBuffer);
auto cp_u64 = HandleToUint64(cb_state->createInfo.commandPool);
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, cb_u64,
error, "%s: CommandBuffer %s was allocated from VkCommandPool %s that does not support bindpoint %s.",
func_name, report_data->FormatHandle(cb_u64).c_str(), report_data->FormatHandle(cp_u64).c_str(),
string_VkPipelineBindPoint(bind_point));
}
}
return skip;
}
bool CoreChecks::PreCallValidateCmdPushDescriptorSetKHR(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount,
const VkWriteDescriptorSet *pDescriptorWrites) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
const char *func_name = "vkCmdPushDescriptorSetKHR()";
bool skip = false;
skip |= ValidateCmd(cb_state, CMD_PUSHDESCRIPTORSETKHR, func_name);
skip |= ValidateCmdQueueFlags(cb_state, func_name, (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT),
"VUID-vkCmdPushDescriptorSetKHR-commandBuffer-cmdpool");
static const std::map<VkPipelineBindPoint, std::string> bind_errors = {
std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, "VUID-vkCmdPushDescriptorSetKHR-pipelineBindPoint-00363"),
std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, "VUID-vkCmdPushDescriptorSetKHR-pipelineBindPoint-00363"),
std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, "VUID-vkCmdPushDescriptorSetKHR-pipelineBindPoint-00363")};
skip |= ValidatePipelineBindPoint(cb_state, pipelineBindPoint, func_name, bind_errors);
auto layout_data = GetPipelineLayout(layout);
// Validate the set index points to a push descriptor set and is in range
if (layout_data) {
const auto &set_layouts = layout_data->set_layouts;
const auto layout_u64 = HandleToUint64(layout);
if (set < set_layouts.size()) {
const auto dsl = set_layouts[set];
if (dsl) {
if (!dsl->IsPushDescriptor()) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT,
layout_u64, "VUID-vkCmdPushDescriptorSetKHR-set-00365",
"%s: Set index %" PRIu32
" does not match push descriptor set layout index for VkPipelineLayout %s.",
func_name, set, report_data->FormatHandle(layout_u64).c_str());
} else {
// Create an empty proxy in order to use the existing descriptor set update validation
// TODO move the validation (like this) that doesn't need descriptor set state to the DSL object so we
// don't have to do this.
cvdescriptorset::DescriptorSet proxy_ds(VK_NULL_HANDLE, VK_NULL_HANDLE, dsl, 0, this);
skip |= proxy_ds.ValidatePushDescriptorsUpdate(report_data, descriptorWriteCount, pDescriptorWrites, func_name);
}
}
} else {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, layout_u64,
"VUID-vkCmdPushDescriptorSetKHR-set-00364",
"%s: Set index %" PRIu32 " is outside of range for VkPipelineLayout %s (set < %" PRIu32 ").", func_name,
set, report_data->FormatHandle(layout_u64).c_str(), static_cast<uint32_t>(set_layouts.size()));
}
}
return skip;
}
void CoreChecks::RecordCmdPushDescriptorSetState(CMD_BUFFER_STATE *cb_state, VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount,
const VkWriteDescriptorSet *pDescriptorWrites) {
const auto &pipeline_layout = GetPipelineLayout(layout);
// Short circuit invalid updates
if (!pipeline_layout || (set >= pipeline_layout->set_layouts.size()) || !pipeline_layout->set_layouts[set] ||
!pipeline_layout->set_layouts[set]->IsPushDescriptor())
return;
// We need a descriptor set to update the bindings with, compatible with the passed layout
const auto dsl = pipeline_layout->set_layouts[set];
auto &last_bound = cb_state->lastBound[pipelineBindPoint];
auto &push_descriptor_set = last_bound.push_descriptor_set;
// If we are disturbing the current push_desriptor_set clear it
if (!push_descriptor_set || !CompatForSet(set, last_bound.compat_id_for_set, pipeline_layout->compat_for_set)) {
push_descriptor_set.reset(new cvdescriptorset::DescriptorSet(0, 0, dsl, 0, this));
}
std::vector<cvdescriptorset::DescriptorSet *> descriptor_sets = {push_descriptor_set.get()};
UpdateLastBoundDescriptorSets(cb_state, pipelineBindPoint, pipeline_layout, set, 1, descriptor_sets, 0, nullptr);
last_bound.pipeline_layout = layout;
// Now that we have either the new or extant push_descriptor set ... do the write updates against it
push_descriptor_set->PerformPushDescriptorsUpdate(descriptorWriteCount, pDescriptorWrites);
}
void CoreChecks::PreCallRecordCmdPushDescriptorSetKHR(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount,
const VkWriteDescriptorSet *pDescriptorWrites) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
RecordCmdPushDescriptorSetState(cb_state, pipelineBindPoint, layout, set, descriptorWriteCount, pDescriptorWrites);
}
static VkDeviceSize GetIndexAlignment(VkIndexType indexType) {
switch (indexType) {
case VK_INDEX_TYPE_UINT16:
return 2;
case VK_INDEX_TYPE_UINT32:
return 4;
default:
// Not a real index type. Express no alignment requirement here; we expect upper layer
// to have already picked up on the enum being nonsense.
return 1;
}
}
bool CoreChecks::PreCallValidateCmdBindIndexBuffer(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
VkIndexType indexType) {
auto buffer_state = GetBufferState(buffer);
auto cb_node = GetCBState(commandBuffer);
assert(buffer_state);
assert(cb_node);
bool skip =
ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, true, "VUID-vkCmdBindIndexBuffer-buffer-00433",
"vkCmdBindIndexBuffer()", "VK_BUFFER_USAGE_INDEX_BUFFER_BIT");
skip |= ValidateCmdQueueFlags(cb_node, "vkCmdBindIndexBuffer()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdBindIndexBuffer-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_node, CMD_BINDINDEXBUFFER, "vkCmdBindIndexBuffer()");
skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkCmdBindIndexBuffer()", "VUID-vkCmdBindIndexBuffer-buffer-00434");
auto offset_align = GetIndexAlignment(indexType);
if (offset % offset_align) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdBindIndexBuffer-offset-00432",
"vkCmdBindIndexBuffer() offset (0x%" PRIxLEAST64 ") does not fall on alignment (%s) boundary.", offset,
string_VkIndexType(indexType));
}
return skip;
}
void CoreChecks::PreCallRecordCmdBindIndexBuffer(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
VkIndexType indexType) {
auto buffer_state = GetBufferState(buffer);
auto cb_node = GetCBState(commandBuffer);
cb_node->status |= CBSTATUS_INDEX_BUFFER_BOUND;
cb_node->index_buffer_binding.buffer = buffer;
cb_node->index_buffer_binding.size = buffer_state->createInfo.size;
cb_node->index_buffer_binding.offset = offset;
cb_node->index_buffer_binding.index_type = indexType;
}
bool CoreChecks::PreCallValidateCmdBindVertexBuffers(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount,
const VkBuffer *pBuffers, const VkDeviceSize *pOffsets) {
auto cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdBindVertexBuffers()", VK_QUEUE_GRAPHICS_BIT,
"VUID-vkCmdBindVertexBuffers-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_BINDVERTEXBUFFERS, "vkCmdBindVertexBuffers()");
for (uint32_t i = 0; i < bindingCount; ++i) {
auto buffer_state = GetBufferState(pBuffers[i]);
assert(buffer_state);
skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, true,
"VUID-vkCmdBindVertexBuffers-pBuffers-00627", "vkCmdBindVertexBuffers()",
"VK_BUFFER_USAGE_VERTEX_BUFFER_BIT");
skip |=
ValidateMemoryIsBoundToBuffer(buffer_state, "vkCmdBindVertexBuffers()", "VUID-vkCmdBindVertexBuffers-pBuffers-00628");
if (pOffsets[i] >= buffer_state->createInfo.size) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
HandleToUint64(buffer_state->buffer), "VUID-vkCmdBindVertexBuffers-pOffsets-00626",
"vkCmdBindVertexBuffers() offset (0x%" PRIxLEAST64 ") is beyond the end of the buffer.", pOffsets[i]);
}
}
return skip;
}
void CoreChecks::PreCallRecordCmdBindVertexBuffers(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount,
const VkBuffer *pBuffers, const VkDeviceSize *pOffsets) {
auto cb_state = GetCBState(commandBuffer);
uint32_t end = firstBinding + bindingCount;
if (cb_state->current_draw_data.vertex_buffer_bindings.size() < end) {
cb_state->current_draw_data.vertex_buffer_bindings.resize(end);
}
for (uint32_t i = 0; i < bindingCount; ++i) {
auto &vertex_buffer_binding = cb_state->current_draw_data.vertex_buffer_bindings[i + firstBinding];
vertex_buffer_binding.buffer = pBuffers[i];
vertex_buffer_binding.offset = pOffsets[i];
}
}
// Validate that an image's sampleCount matches the requirement for a specific API call
bool CoreChecks::ValidateImageSampleCount(IMAGE_STATE *image_state, VkSampleCountFlagBits sample_count, const char *location,
const std::string &msgCode) {
bool skip = false;
if (image_state->createInfo.samples != sample_count) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
HandleToUint64(image_state->image), msgCode,
"%s for image %s was created with a sample count of %s but must be %s.", location,
report_data->FormatHandle(image_state->image).c_str(),
string_VkSampleCountFlagBits(image_state->createInfo.samples), string_VkSampleCountFlagBits(sample_count));
}
return skip;
}
bool CoreChecks::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
VkDeviceSize dataSize, const void *pData) {
auto cb_state = GetCBState(commandBuffer);
assert(cb_state);
auto dst_buffer_state = GetBufferState(dstBuffer);
assert(dst_buffer_state);
bool skip = false;
skip |= ValidateMemoryIsBoundToBuffer(dst_buffer_state, "vkCmdUpdateBuffer()", "VUID-vkCmdUpdateBuffer-dstBuffer-00035");
// Validate that DST buffer has correct usage flags set
skip |=
ValidateBufferUsageFlags(dst_buffer_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdUpdateBuffer-dstBuffer-00034",
"vkCmdUpdateBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT");
skip |=
ValidateCmdQueueFlags(cb_state, "vkCmdUpdateBuffer()", VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdUpdateBuffer-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_UPDATEBUFFER, "vkCmdUpdateBuffer()");
skip |= InsideRenderPass(cb_state, "vkCmdUpdateBuffer()", "VUID-vkCmdUpdateBuffer-renderpass");
return skip;
}
void CoreChecks::PostCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
VkDeviceSize dataSize, const void *pData) {
auto cb_state = GetCBState(commandBuffer);
auto dst_buffer_state = GetBufferState(dstBuffer);
// Update bindings between buffer and cmd buffer
AddCommandBufferBindingBuffer(cb_state, dst_buffer_state);
}
bool CoreChecks::SetEventStageMask(VkQueue queue, VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
CMD_BUFFER_STATE *pCB = GetCBState(commandBuffer);
if (pCB) {
pCB->eventToStageMap[event] = stageMask;
}
auto queue_data = queueMap.find(queue);
if (queue_data != queueMap.end()) {
queue_data->second.eventToStageMap[event] = stageMask;
}
return false;
}
bool CoreChecks::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdSetEvent()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdSetEvent-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_SETEVENT, "vkCmdSetEvent()");
skip |= InsideRenderPass(cb_state, "vkCmdSetEvent()", "VUID-vkCmdSetEvent-renderpass");
skip |= ValidateStageMaskGsTsEnables(stageMask, "vkCmdSetEvent()", "VUID-vkCmdSetEvent-stageMask-01150",
"VUID-vkCmdSetEvent-stageMask-01151", "VUID-vkCmdSetEvent-stageMask-02107",
"VUID-vkCmdSetEvent-stageMask-02108");
return skip;
}
void CoreChecks::PreCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
auto event_state = GetEventState(event);
if (event_state) {
AddCommandBufferBinding(&event_state->cb_bindings, {HandleToUint64(event), kVulkanObjectTypeEvent}, cb_state);
event_state->cb_bindings.insert(cb_state);
}
cb_state->events.push_back(event);
if (!cb_state->waitedEvents.count(event)) {
cb_state->writeEventsBeforeWait.push_back(event);
}
cb_state->eventUpdates.emplace_back([=](VkQueue q) { return SetEventStageMask(q, commandBuffer, event, stageMask); });
}
bool CoreChecks::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdResetEvent()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdResetEvent-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_RESETEVENT, "vkCmdResetEvent()");
skip |= InsideRenderPass(cb_state, "vkCmdResetEvent()", "VUID-vkCmdResetEvent-renderpass");
skip |= ValidateStageMaskGsTsEnables(stageMask, "vkCmdResetEvent()", "VUID-vkCmdResetEvent-stageMask-01154",
"VUID-vkCmdResetEvent-stageMask-01155", "VUID-vkCmdResetEvent-stageMask-02109",
"VUID-vkCmdResetEvent-stageMask-02110");
return skip;
}
void CoreChecks::PreCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
auto event_state = GetEventState(event);
if (event_state) {
AddCommandBufferBinding(&event_state->cb_bindings, {HandleToUint64(event), kVulkanObjectTypeEvent}, cb_state);
event_state->cb_bindings.insert(cb_state);
}
cb_state->events.push_back(event);
if (!cb_state->waitedEvents.count(event)) {
cb_state->writeEventsBeforeWait.push_back(event);
}
// TODO : Add check for "VUID-vkResetEvent-event-01148"
cb_state->eventUpdates.emplace_back(
[=](VkQueue q) { return SetEventStageMask(q, commandBuffer, event, VkPipelineStageFlags(0)); });
}
// Return input pipeline stage flags, expanded for individual bits if VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT is set
static VkPipelineStageFlags ExpandPipelineStageFlags(const DeviceExtensions &extensions, VkPipelineStageFlags inflags) {
if (~inflags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) return inflags;
return (inflags & ~VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) |
(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT |
(extensions.vk_nv_mesh_shader ? (VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV | VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV) : 0) |
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT |
(extensions.vk_ext_conditional_rendering ? VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT : 0) |
(extensions.vk_ext_transform_feedback ? VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT : 0) |
(extensions.vk_nv_shading_rate_image ? VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV : 0) |
(extensions.vk_ext_fragment_density_map ? VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT : 0));
}
static bool HasNonFramebufferStagePipelineStageFlags(VkPipelineStageFlags inflags) {
return (inflags & ~(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)) != 0;
}
static int GetGraphicsPipelineStageLogicalOrdinal(VkPipelineStageFlagBits flag) {
// Note that the list (and lookup) ignore invalid-for-enabled-extension condition. This should be checked elsewhere
// and would greatly complicate this intentionally simple implementation
// clang-format off
const VkPipelineStageFlagBits ordered_array[] = {
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT,
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT,
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT,
VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT,
// Including the task/mesh shaders here is not technically correct, as they are in a
// separate logical pipeline - but it works for the case this is currently used, and
// fixing it would require significant rework and end up with the code being far more
// verbose for no practical gain.
// However, worth paying attention to this if using this function in a new way.
VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV,
VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV,
VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV,
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT
};
// clang-format on
const int ordered_array_length = sizeof(ordered_array) / sizeof(VkPipelineStageFlagBits);
for (int i = 0; i < ordered_array_length; ++i) {
if (ordered_array[i] == flag) {
return i;
}
}
return -1;
}
// The following two functions technically have O(N^2) complexity, but it's for a value of O that's largely
// stable and also rather tiny - this could definitely be rejigged to work more efficiently, but the impact
// on runtime is currently negligible, so it wouldn't gain very much.
// If we add a lot more graphics pipeline stages, this set of functions should be rewritten to accomodate.
static VkPipelineStageFlagBits GetLogicallyEarliestGraphicsPipelineStage(VkPipelineStageFlags inflags) {
VkPipelineStageFlagBits earliest_bit = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
int earliest_bit_order = GetGraphicsPipelineStageLogicalOrdinal(earliest_bit);
for (std::size_t i = 0; i < sizeof(VkPipelineStageFlagBits); ++i) {
VkPipelineStageFlagBits current_flag = (VkPipelineStageFlagBits)((inflags & 0x1u) << i);
if (current_flag) {
int new_order = GetGraphicsPipelineStageLogicalOrdinal(current_flag);
if (new_order != -1 && new_order < earliest_bit_order) {
earliest_bit_order = new_order;
earliest_bit = current_flag;
}
}
inflags = inflags >> 1;
}
return earliest_bit;
}
static VkPipelineStageFlagBits GetLogicallyLatestGraphicsPipelineStage(VkPipelineStageFlags inflags) {
VkPipelineStageFlagBits latest_bit = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
int latest_bit_order = GetGraphicsPipelineStageLogicalOrdinal(latest_bit);
for (std::size_t i = 0; i < sizeof(VkPipelineStageFlagBits); ++i) {
if (inflags & 0x1u) {
int new_order = GetGraphicsPipelineStageLogicalOrdinal((VkPipelineStageFlagBits)((inflags & 0x1u) << i));
if (new_order != -1 && new_order > latest_bit_order) {
latest_bit_order = new_order;
latest_bit = (VkPipelineStageFlagBits)((inflags & 0x1u) << i);
}
}
inflags = inflags >> 1;
}
return latest_bit;
}
// Verify image barrier image state and that the image is consistent with FB image
bool CoreChecks::ValidateImageBarrierImage(const char *funcName, CMD_BUFFER_STATE const *cb_state, VkFramebuffer framebuffer,
uint32_t active_subpass, const safe_VkSubpassDescription2KHR &sub_desc,
uint64_t rp_handle, uint32_t img_index, const VkImageMemoryBarrier &img_barrier) {
bool skip = false;
const auto &fb_state = GetFramebufferState(framebuffer);
assert(fb_state);
const auto img_bar_image = img_barrier.image;
bool image_match = false;
bool sub_image_found = false; // Do we find a corresponding subpass description
VkImageLayout sub_image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
uint32_t attach_index = 0;
// Verify that a framebuffer image matches barrier image
const auto attachmentCount = fb_state->createInfo.attachmentCount;
for (uint32_t attachment = 0; attachment < attachmentCount; ++attachment) {
auto view_state = GetAttachmentImageViewState(fb_state, attachment);
if (view_state && (img_bar_image == view_state->create_info.image)) {
image_match = true;
attach_index = attachment;
break;
}
}
if (image_match) { // Make sure subpass is referring to matching attachment
if (sub_desc.pDepthStencilAttachment && sub_desc.pDepthStencilAttachment->attachment == attach_index) {
sub_image_layout = sub_desc.pDepthStencilAttachment->layout;
sub_image_found = true;
} else if (device_extensions.vk_khr_depth_stencil_resolve) {
const auto *resolve = lvl_find_in_chain<VkSubpassDescriptionDepthStencilResolveKHR>(sub_desc.pNext);
if (resolve && resolve->pDepthStencilResolveAttachment &&
resolve->pDepthStencilResolveAttachment->attachment == attach_index) {
sub_image_layout = resolve->pDepthStencilResolveAttachment->layout;
sub_image_found = true;
}
} else {
for (uint32_t j = 0; j < sub_desc.colorAttachmentCount; ++j) {
if (sub_desc.pColorAttachments && sub_desc.pColorAttachments[j].attachment == attach_index) {
sub_image_layout = sub_desc.pColorAttachments[j].layout;
sub_image_found = true;
break;
} else if (sub_desc.pResolveAttachments && sub_desc.pResolveAttachments[j].attachment == attach_index) {
sub_image_layout = sub_desc.pResolveAttachments[j].layout;
sub_image_found = true;
break;
}
}
}
if (!sub_image_found) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-image-02635",
"%s: Barrier pImageMemoryBarriers[%d].image (%s) is not referenced by the VkSubpassDescription for "
"active subpass (%d) of current renderPass (%s).",
funcName, img_index, report_data->FormatHandle(img_bar_image).c_str(), active_subpass,
report_data->FormatHandle(rp_handle).c_str());
}
} else { // !image_match
auto const fb_handle = HandleToUint64(fb_state->framebuffer);
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT, fb_handle,
"VUID-vkCmdPipelineBarrier-image-02635",
"%s: Barrier pImageMemoryBarriers[%d].image (%s) does not match an image from the current framebuffer (%s).", funcName,
img_index, report_data->FormatHandle(img_bar_image).c_str(), report_data->FormatHandle(fb_handle).c_str());
}
if (img_barrier.oldLayout != img_barrier.newLayout) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-oldLayout-01181",
"%s: As the Image Barrier for image %s is being executed within a render pass instance, oldLayout must "
"equal newLayout yet they are %s and %s.",
funcName, report_data->FormatHandle(img_barrier.image).c_str(), string_VkImageLayout(img_barrier.oldLayout),
string_VkImageLayout(img_barrier.newLayout));
} else {
if (sub_image_found && sub_image_layout != img_barrier.oldLayout) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-oldLayout-02636",
"%s: Barrier pImageMemoryBarriers[%d].image (%s) is referenced by the VkSubpassDescription for active "
"subpass (%d) of current renderPass (%s) as having layout %s, but image barrier has layout %s.",
funcName, img_index, report_data->FormatHandle(img_bar_image).c_str(), active_subpass,
report_data->FormatHandle(rp_handle).c_str(), string_VkImageLayout(sub_image_layout),
string_VkImageLayout(img_barrier.oldLayout));
}
}
return skip;
}
// Validate image barriers within a renderPass
bool CoreChecks::ValidateRenderPassImageBarriers(const char *funcName, CMD_BUFFER_STATE *cb_state, uint32_t active_subpass,
const safe_VkSubpassDescription2KHR &sub_desc, uint64_t rp_handle,
const safe_VkSubpassDependency2KHR *dependencies,
const std::vector<uint32_t> &self_dependencies, uint32_t image_mem_barrier_count,
const VkImageMemoryBarrier *image_barriers) {
bool skip = false;
for (uint32_t i = 0; i < image_mem_barrier_count; ++i) {
const auto &img_barrier = image_barriers[i];
const auto &img_src_access_mask = img_barrier.srcAccessMask;
const auto &img_dst_access_mask = img_barrier.dstAccessMask;
bool access_mask_match = false;
for (const auto self_dep_index : self_dependencies) {
const auto &sub_dep = dependencies[self_dep_index];
access_mask_match = (img_src_access_mask == (sub_dep.srcAccessMask & img_src_access_mask)) &&
(img_dst_access_mask == (sub_dep.dstAccessMask & img_dst_access_mask));
if (access_mask_match) break;
}
if (!access_mask_match) {
std::stringstream self_dep_ss;
stream_join(self_dep_ss, ", ", self_dependencies);
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: Barrier pImageMemoryBarriers[%d].srcAccessMask(0x%X) is not a subset of VkSubpassDependency "
"srcAccessMask of subpass %d of renderPass %s. Candidate VkSubpassDependency are pDependencies entries [%s].",
funcName, i, img_src_access_mask, active_subpass, report_data->FormatHandle(rp_handle).c_str(),
self_dep_ss.str().c_str());
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: Barrier pImageMemoryBarriers[%d].dstAccessMask(0x%X) is not a subset of VkSubpassDependency "
"dstAccessMask of subpass %d of renderPass %s. Candidate VkSubpassDependency are pDependencies entries [%s].",
funcName, i, img_dst_access_mask, active_subpass, report_data->FormatHandle(rp_handle).c_str(),
self_dep_ss.str().c_str());
}
if (VK_QUEUE_FAMILY_IGNORED != img_barrier.srcQueueFamilyIndex ||
VK_QUEUE_FAMILY_IGNORED != img_barrier.dstQueueFamilyIndex) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-srcQueueFamilyIndex-01182",
"%s: Barrier pImageMemoryBarriers[%d].srcQueueFamilyIndex is %d and "
"pImageMemoryBarriers[%d].dstQueueFamilyIndex is %d but both must be VK_QUEUE_FAMILY_IGNORED.",
funcName, i, img_barrier.srcQueueFamilyIndex, i, img_barrier.dstQueueFamilyIndex);
}
// Secondary CBs can have null framebuffer so queue up validation in that case 'til FB is known
if (VK_NULL_HANDLE == cb_state->activeFramebuffer) {
assert(VK_COMMAND_BUFFER_LEVEL_SECONDARY == cb_state->createInfo.level);
// Secondary CB case w/o FB specified delay validation
cb_state->cmd_execute_commands_functions.emplace_back([=](CMD_BUFFER_STATE *primary_cb, VkFramebuffer fb) {
return ValidateImageBarrierImage(funcName, cb_state, fb, active_subpass, sub_desc, rp_handle, i, img_barrier);
});
} else {
skip |= ValidateImageBarrierImage(funcName, cb_state, cb_state->activeFramebuffer, active_subpass, sub_desc, rp_handle,
i, img_barrier);
}
}
return skip;
}
// Validate VUs for Pipeline Barriers that are within a renderPass
// Pre: cb_state->activeRenderPass must be a pointer to valid renderPass state
bool CoreChecks::ValidateRenderPassPipelineBarriers(const char *funcName, CMD_BUFFER_STATE *cb_state,
VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask,
VkDependencyFlags dependency_flags, uint32_t mem_barrier_count,
const VkMemoryBarrier *mem_barriers, uint32_t buffer_mem_barrier_count,
const VkBufferMemoryBarrier *buffer_mem_barriers,
uint32_t image_mem_barrier_count, const VkImageMemoryBarrier *image_barriers) {
bool skip = false;
const auto rp_state = cb_state->activeRenderPass;
const auto active_subpass = cb_state->activeSubpass;
auto rp_handle = HandleToUint64(rp_state->renderPass);
const auto &self_dependencies = rp_state->self_dependencies[active_subpass];
const auto &dependencies = rp_state->createInfo.pDependencies;
if (self_dependencies.size() == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: Barriers cannot be set during subpass %d of renderPass %s with no self-dependency specified.",
funcName, active_subpass, report_data->FormatHandle(rp_handle).c_str());
} else {
// Grab ref to current subpassDescription up-front for use below
const auto &sub_desc = rp_state->createInfo.pSubpasses[active_subpass];
// Look for matching mask in any self-dependency
bool stage_mask_match = false;
for (const auto self_dep_index : self_dependencies) {
const auto &sub_dep = dependencies[self_dep_index];
const auto &sub_src_stage_mask = ExpandPipelineStageFlags(device_extensions, sub_dep.srcStageMask);
const auto &sub_dst_stage_mask = ExpandPipelineStageFlags(device_extensions, sub_dep.dstStageMask);
stage_mask_match = ((sub_src_stage_mask == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
(src_stage_mask == (sub_src_stage_mask & src_stage_mask))) &&
((sub_dst_stage_mask == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
(dst_stage_mask == (sub_dst_stage_mask & dst_stage_mask)));
if (stage_mask_match) break;
}
if (!stage_mask_match) {
std::stringstream self_dep_ss;
stream_join(self_dep_ss, ", ", self_dependencies);
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: Barrier srcStageMask(0x%X) is not a subset of VkSubpassDependency srcStageMask of any "
"self-dependency of subpass %d of renderPass %s for which dstStageMask is also a subset. "
"Candidate VkSubpassDependency are pDependencies entries [%s].",
funcName, src_stage_mask, active_subpass, report_data->FormatHandle(rp_handle).c_str(),
self_dep_ss.str().c_str());
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: Barrier dstStageMask(0x%X) is not a subset of VkSubpassDependency dstStageMask of any "
"self-dependency of subpass %d of renderPass %s for which srcStageMask is also a subset. "
"Candidate VkSubpassDependency are pDependencies entries [%s].",
funcName, dst_stage_mask, active_subpass, report_data->FormatHandle(rp_handle).c_str(),
self_dep_ss.str().c_str());
}
if (0 != buffer_mem_barrier_count) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-bufferMemoryBarrierCount-01178",
"%s: bufferMemoryBarrierCount is non-zero (%d) for subpass %d of renderPass %s.", funcName,
buffer_mem_barrier_count, active_subpass, report_data->FormatHandle(rp_handle).c_str());
}
for (uint32_t i = 0; i < mem_barrier_count; ++i) {
const auto &mb_src_access_mask = mem_barriers[i].srcAccessMask;
const auto &mb_dst_access_mask = mem_barriers[i].dstAccessMask;
bool access_mask_match = false;
for (const auto self_dep_index : self_dependencies) {
const auto &sub_dep = dependencies[self_dep_index];
access_mask_match = (mb_src_access_mask == (sub_dep.srcAccessMask & mb_src_access_mask)) &&
(mb_dst_access_mask == (sub_dep.dstAccessMask & mb_dst_access_mask));
if (access_mask_match) break;
}
if (!access_mask_match) {
std::stringstream self_dep_ss;
stream_join(self_dep_ss, ", ", self_dependencies);
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: Barrier pMemoryBarriers[%d].srcAccessMask(0x%X) is not a subset of VkSubpassDependency srcAccessMask "
"for any self-dependency of subpass %d of renderPass %s for which dstAccessMask is also a subset. "
"Candidate VkSubpassDependency are pDependencies entries [%s].",
funcName, i, mb_src_access_mask, active_subpass, report_data->FormatHandle(rp_handle).c_str(),
self_dep_ss.str().c_str());
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: Barrier pMemoryBarriers[%d].dstAccessMask(0x%X) is not a subset of VkSubpassDependency dstAccessMask "
"for any self-dependency of subpass %d of renderPass %s for which srcAccessMask is also a subset. "
"Candidate VkSubpassDependency are pDependencies entries [%s].",
funcName, i, mb_dst_access_mask, active_subpass, report_data->FormatHandle(rp_handle).c_str(),
self_dep_ss.str().c_str());
}
}
skip |= ValidateRenderPassImageBarriers(funcName, cb_state, active_subpass, sub_desc, rp_handle, dependencies,
self_dependencies, image_mem_barrier_count, image_barriers);
bool flag_match = false;
for (const auto self_dep_index : self_dependencies) {
const auto &sub_dep = dependencies[self_dep_index];
flag_match = sub_dep.dependencyFlags == dependency_flags;
if (flag_match) break;
}
if (!flag_match) {
std::stringstream self_dep_ss;
stream_join(self_dep_ss, ", ", self_dependencies);
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle,
"VUID-vkCmdPipelineBarrier-pDependencies-02285",
"%s: dependencyFlags param (0x%X) does not equal VkSubpassDependency dependencyFlags value for any "
"self-dependency of subpass %d of renderPass %s. Candidate VkSubpassDependency are pDependencies entries [%s].",
funcName, dependency_flags, cb_state->activeSubpass, report_data->FormatHandle(rp_handle).c_str(),
self_dep_ss.str().c_str());
}
}
return skip;
}
// Array to mask individual accessMask to corresponding stageMask
// accessMask active bit position (0-31) maps to index
const static VkPipelineStageFlags AccessMaskToPipeStage[28] = {
// VK_ACCESS_INDIRECT_COMMAND_READ_BIT = 0
VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
// VK_ACCESS_INDEX_READ_BIT = 1
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
// VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 2
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
// VK_ACCESS_UNIFORM_READ_BIT = 3
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV |
VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV,
// VK_ACCESS_INPUT_ATTACHMENT_READ_BIT = 4
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
// VK_ACCESS_SHADER_READ_BIT = 5
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV |
VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV,
// VK_ACCESS_SHADER_WRITE_BIT = 6
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV |
VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV,
// VK_ACCESS_COLOR_ATTACHMENT_READ_BIT = 7
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
// VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT = 8
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
// VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT = 9
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
// VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT = 10
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
// VK_ACCESS_TRANSFER_READ_BIT = 11
VK_PIPELINE_STAGE_TRANSFER_BIT,
// VK_ACCESS_TRANSFER_WRITE_BIT = 12
VK_PIPELINE_STAGE_TRANSFER_BIT,
// VK_ACCESS_HOST_READ_BIT = 13
VK_PIPELINE_STAGE_HOST_BIT,
// VK_ACCESS_HOST_WRITE_BIT = 14
VK_PIPELINE_STAGE_HOST_BIT,
// VK_ACCESS_MEMORY_READ_BIT = 15
VK_ACCESS_FLAG_BITS_MAX_ENUM, // Always match
// VK_ACCESS_MEMORY_WRITE_BIT = 16
VK_ACCESS_FLAG_BITS_MAX_ENUM, // Always match
// VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX = 17
VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX,
// VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX = 18
VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX,
// VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT = 19
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
// VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT = 20
VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT,
// VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV = 21
VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV | VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV,
// VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV = 22
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV,
// VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV = 23
VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV,
// VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT = 24
VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT,
// VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT = 25
VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT,
// VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT = 26
VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
// VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT = 27
VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT,
};
// Verify that all bits of access_mask are supported by the src_stage_mask
static bool ValidateAccessMaskPipelineStage(const DeviceExtensions &extensions, VkAccessFlags access_mask,
VkPipelineStageFlags stage_mask) {
// Early out if all commands set, or access_mask NULL
if ((stage_mask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) || (0 == access_mask)) return true;
stage_mask = ExpandPipelineStageFlags(extensions, stage_mask);
int index = 0;
// for each of the set bits in access_mask, make sure that supporting stage mask bit(s) are set
while (access_mask) {
index = (u_ffs(access_mask) - 1);
assert(index >= 0);
// Must have "!= 0" compare to prevent warning from MSVC
if ((AccessMaskToPipeStage[index] & stage_mask) == 0) return false; // early out
access_mask &= ~(1 << index); // Mask off bit that's been checked
}
return true;
}
namespace barrier_queue_families {
enum VuIndex {
kSrcOrDstMustBeIgnore,
kSpecialOrIgnoreOnly,
kSrcIgnoreRequiresDstIgnore,
kDstValidOrSpecialIfNotIgnore,
kSrcValidOrSpecialIfNotIgnore,
kSrcAndDestMustBeIgnore,
kBothIgnoreOrBothValid,
kSubmitQueueMustMatchSrcOrDst
};
static const char *vu_summary[] = {"Source or destination queue family must be ignored.",
"Source or destination queue family must be special or ignored.",
"Destination queue family must be ignored if source queue family is.",
"Destination queue family must be valid, ignored, or special.",
"Source queue family must be valid, ignored, or special.",
"Source and destination queue family must both be ignored.",
"Source and destination queue family must both be ignore or both valid.",
"Source or destination queue family must match submit queue family, if not ignored."};
static const std::string image_error_codes[] = {
"VUID-VkImageMemoryBarrier-image-01381", // kSrcOrDstMustBeIgnore
"VUID-VkImageMemoryBarrier-image-01766", // kSpecialOrIgnoreOnly
"VUID-VkImageMemoryBarrier-image-01201", // kSrcIgnoreRequiresDstIgnore
"VUID-VkImageMemoryBarrier-image-01768", // kDstValidOrSpecialIfNotIgnore
"VUID-VkImageMemoryBarrier-image-01767", // kSrcValidOrSpecialIfNotIgnore
"VUID-VkImageMemoryBarrier-image-01199", // kSrcAndDestMustBeIgnore
"VUID-VkImageMemoryBarrier-image-01200", // kBothIgnoreOrBothValid
"VUID-VkImageMemoryBarrier-image-01205", // kSubmitQueueMustMatchSrcOrDst
};
static const std::string buffer_error_codes[] = {
"VUID-VkBufferMemoryBarrier-buffer-01191", // kSrcOrDstMustBeIgnore
"VUID-VkBufferMemoryBarrier-buffer-01763", // kSpecialOrIgnoreOnly
"VUID-VkBufferMemoryBarrier-buffer-01193", // kSrcIgnoreRequiresDstIgnore
"VUID-VkBufferMemoryBarrier-buffer-01765", // kDstValidOrSpecialIfNotIgnore
"VUID-VkBufferMemoryBarrier-buffer-01764", // kSrcValidOrSpecialIfNotIgnore
"VUID-VkBufferMemoryBarrier-buffer-01190", // kSrcAndDestMustBeIgnore
"VUID-VkBufferMemoryBarrier-buffer-01192", // kBothIgnoreOrBothValid
"VUID-VkBufferMemoryBarrier-buffer-01196", // kSubmitQueueMustMatchSrcOrDst
};
class ValidatorState {
public:
ValidatorState(const CoreChecks *device_data, const char *func_name, const CMD_BUFFER_STATE *cb_state,
const uint64_t barrier_handle64, const VkSharingMode sharing_mode, const VulkanObjectType object_type,
const std::string *val_codes)
: report_data_(device_data->report_data),
func_name_(func_name),
cb_handle64_(HandleToUint64(cb_state->commandBuffer)),
barrier_handle64_(barrier_handle64),
sharing_mode_(sharing_mode),
object_type_(object_type),
val_codes_(val_codes),
limit_(static_cast<uint32_t>(device_data->physical_device_state->queue_family_properties.size())),
mem_ext_(device_data->device_extensions.vk_khr_external_memory) {}
// Create a validator state from an image state... reducing the image specific to the generic version.
ValidatorState(const CoreChecks *device_data, const char *func_name, const CMD_BUFFER_STATE *cb_state,
const VkImageMemoryBarrier *barrier, const IMAGE_STATE *state)
: ValidatorState(device_data, func_name, cb_state, HandleToUint64(barrier->image), state->createInfo.sharingMode,
kVulkanObjectTypeImage, image_error_codes) {}
// Create a validator state from an buffer state... reducing the buffer specific to the generic version.
ValidatorState(const CoreChecks *device_data, const char *func_name, const CMD_BUFFER_STATE *cb_state,
const VkBufferMemoryBarrier *barrier, const BUFFER_STATE *state)
: ValidatorState(device_data, func_name, cb_state, HandleToUint64(barrier->buffer), state->createInfo.sharingMode,
kVulkanObjectTypeImage, buffer_error_codes) {}
// Log the messages using boilerplate from object state, and Vu specific information from the template arg
// One and two family versions, in the single family version, Vu holds the name of the passed parameter
bool LogMsg(VuIndex vu_index, uint32_t family, const char *param_name) const {
const std::string &val_code = val_codes_[vu_index];
const char *annotation = GetFamilyAnnotation(family);
return log_msg(report_data_, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, cb_handle64_,
val_code, "%s: Barrier using %s %s created with sharingMode %s, has %s %u%s. %s", func_name_,
GetTypeString(), report_data_->FormatHandle(barrier_handle64_).c_str(), GetModeString(), param_name, family,
annotation, vu_summary[vu_index]);
}
bool LogMsg(VuIndex vu_index, uint32_t src_family, uint32_t dst_family) const {
const std::string &val_code = val_codes_[vu_index];
const char *src_annotation = GetFamilyAnnotation(src_family);
const char *dst_annotation = GetFamilyAnnotation(dst_family);
return log_msg(
report_data_, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, cb_handle64_, val_code,
"%s: Barrier using %s %s created with sharingMode %s, has srcQueueFamilyIndex %u%s and dstQueueFamilyIndex %u%s. %s",
func_name_, GetTypeString(), report_data_->FormatHandle(barrier_handle64_).c_str(), GetModeString(), src_family,
src_annotation, dst_family, dst_annotation, vu_summary[vu_index]);
}
// This abstract Vu can only be tested at submit time, thus we need a callback from the closure containing the needed
// data. Note that the mem_barrier is copied to the closure as the lambda lifespan exceed the guarantees of validity for
// application input.
static bool ValidateAtQueueSubmit(const VkQueue queue, const CoreChecks *device_data, uint32_t src_family, uint32_t dst_family,
const ValidatorState &val) {
auto queue_data_it = device_data->queueMap.find(queue);
if (queue_data_it == device_data->queueMap.end()) return false;
uint32_t queue_family = queue_data_it->second.queueFamilyIndex;
if ((src_family != queue_family) && (dst_family != queue_family)) {
const std::string &val_code = val.val_codes_[kSubmitQueueMustMatchSrcOrDst];
const char *src_annotation = val.GetFamilyAnnotation(src_family);
const char *dst_annotation = val.GetFamilyAnnotation(dst_family);
return log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT,
HandleToUint64(queue), val_code,
"%s: Barrier submitted to queue with family index %u, using %s %s created with sharingMode %s, has "
"srcQueueFamilyIndex %u%s and dstQueueFamilyIndex %u%s. %s",
"vkQueueSubmit", queue_family, val.GetTypeString(),
device_data->report_data->FormatHandle(val.barrier_handle64_).c_str(), val.GetModeString(), src_family,
src_annotation, dst_family, dst_annotation, vu_summary[kSubmitQueueMustMatchSrcOrDst]);
}
return false;
}
// Logical helpers for semantic clarity
inline bool KhrExternalMem() const { return mem_ext_; }
inline bool IsValid(uint32_t queue_family) const { return (queue_family < limit_); }
inline bool IsValidOrSpecial(uint32_t queue_family) const {
return IsValid(queue_family) || (mem_ext_ && IsSpecial(queue_family));
}
inline bool IsIgnored(uint32_t queue_family) const { return queue_family == VK_QUEUE_FAMILY_IGNORED; }
// Helpers for LogMsg (and log_msg)
const char *GetModeString() const { return string_VkSharingMode(sharing_mode_); }
// Descriptive text for the various types of queue family index
const char *GetFamilyAnnotation(uint32_t family) const {
const char *external = " (VK_QUEUE_FAMILY_EXTERNAL_KHR)";
const char *foreign = " (VK_QUEUE_FAMILY_FOREIGN_EXT)";
const char *ignored = " (VK_QUEUE_FAMILY_IGNORED)";
const char *valid = " (VALID)";
const char *invalid = " (INVALID)";
switch (family) {
case VK_QUEUE_FAMILY_EXTERNAL_KHR:
return external;
case VK_QUEUE_FAMILY_FOREIGN_EXT:
return foreign;
case VK_QUEUE_FAMILY_IGNORED:
return ignored;
default:
if (IsValid(family)) {
return valid;
}
return invalid;
};
}
const char *GetTypeString() const { return object_string[object_type_]; }
VkSharingMode GetSharingMode() const { return sharing_mode_; }
protected:
const debug_report_data *const report_data_;
const char *const func_name_;
const uint64_t cb_handle64_;
const uint64_t barrier_handle64_;
const VkSharingMode sharing_mode_;
const VulkanObjectType object_type_;
const std::string *val_codes_;
const uint32_t limit_;
const bool mem_ext_;
};
bool Validate(const CoreChecks *device_data, const char *func_name, CMD_BUFFER_STATE *cb_state, const ValidatorState &val,
const uint32_t src_queue_family, const uint32_t dst_queue_family) {
bool skip = false;
const bool mode_concurrent = val.GetSharingMode() == VK_SHARING_MODE_CONCURRENT;
const bool src_ignored = val.IsIgnored(src_queue_family);
const bool dst_ignored = val.IsIgnored(dst_queue_family);
if (val.KhrExternalMem()) {
if (mode_concurrent) {
if (!(src_ignored || dst_ignored)) {
skip |= val.LogMsg(kSrcOrDstMustBeIgnore, src_queue_family, dst_queue_family);
}
if ((src_ignored && !(dst_ignored || IsSpecial(dst_queue_family))) ||
(dst_ignored && !(src_ignored || IsSpecial(src_queue_family)))) {
skip |= val.LogMsg(kSpecialOrIgnoreOnly, src_queue_family, dst_queue_family);
}
} else {
// VK_SHARING_MODE_EXCLUSIVE
if (src_ignored && !dst_ignored) {
skip |= val.LogMsg(kSrcIgnoreRequiresDstIgnore, src_queue_family, dst_queue_family);
}
if (!dst_ignored && !val.IsValidOrSpecial(dst_queue_family)) {
skip |= val.LogMsg(kDstValidOrSpecialIfNotIgnore, dst_queue_family, "dstQueueFamilyIndex");
}
if (!src_ignored && !val.IsValidOrSpecial(src_queue_family)) {
skip |= val.LogMsg(kSrcValidOrSpecialIfNotIgnore, src_queue_family, "srcQueueFamilyIndex");
}
}
} else {
// No memory extension
if (mode_concurrent) {
if (!src_ignored || !dst_ignored) {
skip |= val.LogMsg(kSrcAndDestMustBeIgnore, src_queue_family, dst_queue_family);
}
} else {
// VK_SHARING_MODE_EXCLUSIVE
if (!((src_ignored && dst_ignored) || (val.IsValid(src_queue_family) && val.IsValid(dst_queue_family)))) {
skip |= val.LogMsg(kBothIgnoreOrBothValid, src_queue_family, dst_queue_family);
}
}
}
if (!mode_concurrent && !src_ignored && !dst_ignored) {
// Only enqueue submit time check if it is needed. If more submit time checks are added, change the criteria
// TODO create a better named list, or rename the submit time lists to something that matches the broader usage...
// Note: if we want to create a semantic that separates state lookup, validation, and state update this should go
// to a local queue of update_state_actions or something.
cb_state->eventUpdates.emplace_back([device_data, src_queue_family, dst_queue_family, val](VkQueue queue) {
return ValidatorState::ValidateAtQueueSubmit(queue, device_data, src_queue_family, dst_queue_family, val);
});
}
return skip;
}
} // namespace barrier_queue_families
// Type specific wrapper for image barriers
bool CoreChecks::ValidateBarrierQueueFamilies(const char *func_name, CMD_BUFFER_STATE *cb_state,
const VkImageMemoryBarrier *barrier, const IMAGE_STATE *state_data) {
// State data is required
if (!state_data) {
return false;
}
// Create the validator state from the image state
barrier_queue_families::ValidatorState val(this, func_name, cb_state, barrier, state_data);
const uint32_t src_queue_family = barrier->srcQueueFamilyIndex;
const uint32_t dst_queue_family = barrier->dstQueueFamilyIndex;
return barrier_queue_families::Validate(this, func_name, cb_state, val, src_queue_family, dst_queue_family);
}
// Type specific wrapper for buffer barriers
bool CoreChecks::ValidateBarrierQueueFamilies(const char *func_name, CMD_BUFFER_STATE *cb_state,
const VkBufferMemoryBarrier *barrier, const BUFFER_STATE *state_data) {
// State data is required
if (!state_data) {
return false;
}
// Create the validator state from the buffer state
barrier_queue_families::ValidatorState val(this, func_name, cb_state, barrier, state_data);
const uint32_t src_queue_family = barrier->srcQueueFamilyIndex;
const uint32_t dst_queue_family = barrier->dstQueueFamilyIndex;
return barrier_queue_families::Validate(this, func_name, cb_state, val, src_queue_family, dst_queue_family);
}
bool CoreChecks::ValidateBarriers(const char *funcName, CMD_BUFFER_STATE *cb_state, VkPipelineStageFlags src_stage_mask,
VkPipelineStageFlags dst_stage_mask, uint32_t memBarrierCount,
const VkMemoryBarrier *pMemBarriers, uint32_t bufferBarrierCount,
const VkBufferMemoryBarrier *pBufferMemBarriers, uint32_t imageMemBarrierCount,
const VkImageMemoryBarrier *pImageMemBarriers) {
bool skip = false;
for (uint32_t i = 0; i < memBarrierCount; ++i) {
const auto &mem_barrier = pMemBarriers[i];
if (!ValidateAccessMaskPipelineStage(device_extensions, mem_barrier.srcAccessMask, src_stage_mask)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01184",
"%s: pMemBarriers[%d].srcAccessMask (0x%X) is not supported by srcStageMask (0x%X).", funcName, i,
mem_barrier.srcAccessMask, src_stage_mask);
}
if (!ValidateAccessMaskPipelineStage(device_extensions, mem_barrier.dstAccessMask, dst_stage_mask)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01185",
"%s: pMemBarriers[%d].dstAccessMask (0x%X) is not supported by dstStageMask (0x%X).", funcName, i,
mem_barrier.dstAccessMask, dst_stage_mask);
}
}
for (uint32_t i = 0; i < imageMemBarrierCount; ++i) {
auto mem_barrier = &pImageMemBarriers[i];
if (!ValidateAccessMaskPipelineStage(device_extensions, mem_barrier->srcAccessMask, src_stage_mask)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01184",
"%s: pImageMemBarriers[%d].srcAccessMask (0x%X) is not supported by srcStageMask (0x%X).", funcName, i,
mem_barrier->srcAccessMask, src_stage_mask);
}
if (!ValidateAccessMaskPipelineStage(device_extensions, mem_barrier->dstAccessMask, dst_stage_mask)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01185",
"%s: pImageMemBarriers[%d].dstAccessMask (0x%X) is not supported by dstStageMask (0x%X).", funcName, i,
mem_barrier->dstAccessMask, dst_stage_mask);
}
auto image_data = GetImageState(mem_barrier->image);
skip |= ValidateBarrierQueueFamilies(funcName, cb_state, mem_barrier, image_data);
if (mem_barrier->newLayout == VK_IMAGE_LAYOUT_UNDEFINED || mem_barrier->newLayout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-VkImageMemoryBarrier-newLayout-01198",
"%s: Image Layout cannot be transitioned to UNDEFINED or PREINITIALIZED.", funcName);
}
if (image_data) {
// There is no VUID for this, but there is blanket text:
// "Non-sparse resources must be bound completely and contiguously to a single VkDeviceMemory object before
// recording commands in a command buffer."
// TODO: Update this when VUID is defined
skip |= ValidateMemoryIsBoundToImage(image_data, funcName, kVUIDUndefined);
auto aspect_mask = mem_barrier->subresourceRange.aspectMask;
skip |= ValidateImageAspectMask(image_data->image, image_data->createInfo.format, aspect_mask, funcName);
std::string param_name = "pImageMemoryBarriers[" + std::to_string(i) + "].subresourceRange";
skip |= ValidateImageBarrierSubresourceRange(image_data, mem_barrier->subresourceRange, funcName, param_name.c_str());
}
}
for (uint32_t i = 0; i < bufferBarrierCount; ++i) {
auto mem_barrier = &pBufferMemBarriers[i];
if (!mem_barrier) continue;
if (!ValidateAccessMaskPipelineStage(device_extensions, mem_barrier->srcAccessMask, src_stage_mask)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01184",
"%s: pBufferMemBarriers[%d].srcAccessMask (0x%X) is not supported by srcStageMask (0x%X).", funcName, i,
mem_barrier->srcAccessMask, src_stage_mask);
}
if (!ValidateAccessMaskPipelineStage(device_extensions, mem_barrier->dstAccessMask, dst_stage_mask)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01185",
"%s: pBufferMemBarriers[%d].dstAccessMask (0x%X) is not supported by dstStageMask (0x%X).", funcName, i,
mem_barrier->dstAccessMask, dst_stage_mask);
}
// Validate buffer barrier queue family indices
auto buffer_state = GetBufferState(mem_barrier->buffer);
skip |= ValidateBarrierQueueFamilies(funcName, cb_state, mem_barrier, buffer_state);
if (buffer_state) {
// There is no VUID for this, but there is blanket text:
// "Non-sparse resources must be bound completely and contiguously to a single VkDeviceMemory object before
// recording commands in a command buffer"
// TODO: Update this when VUID is defined
skip |= ValidateMemoryIsBoundToBuffer(buffer_state, funcName, kVUIDUndefined);
auto buffer_size = buffer_state->createInfo.size;
if (mem_barrier->offset >= buffer_size) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-VkBufferMemoryBarrier-offset-01187",
"%s: Buffer Barrier %s has offset 0x%" PRIx64 " which is not less than total size 0x%" PRIx64 ".",
funcName, report_data->FormatHandle(mem_barrier->buffer).c_str(),
HandleToUint64(mem_barrier->offset), HandleToUint64(buffer_size));
} else if (mem_barrier->size != VK_WHOLE_SIZE && (mem_barrier->offset + mem_barrier->size > buffer_size)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-VkBufferMemoryBarrier-size-01189",
"%s: Buffer Barrier %s has offset 0x%" PRIx64 " and size 0x%" PRIx64
" whose sum is greater than total size 0x%" PRIx64 ".",
funcName, report_data->FormatHandle(mem_barrier->buffer).c_str(), HandleToUint64(mem_barrier->offset),
HandleToUint64(mem_barrier->size), HandleToUint64(buffer_size));
}
}
}
skip |= ValidateBarriersQFOTransferUniqueness(funcName, cb_state, bufferBarrierCount, pBufferMemBarriers, imageMemBarrierCount,
pImageMemBarriers);
return skip;
}
bool CoreChecks::ValidateEventStageMask(VkQueue queue, CMD_BUFFER_STATE *pCB, uint32_t eventCount, size_t firstEventIndex,
VkPipelineStageFlags sourceStageMask) {
bool skip = false;
VkPipelineStageFlags stageMask = 0;
for (uint32_t i = 0; i < eventCount; ++i) {
auto event = pCB->events[firstEventIndex + i];
auto queue_data = queueMap.find(queue);
if (queue_data == queueMap.end()) return false;
auto event_data = queue_data->second.eventToStageMap.find(event);
if (event_data != queue_data->second.eventToStageMap.end()) {
stageMask |= event_data->second;
} else {
auto global_event_data = GetEventState(event);
if (!global_event_data) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT,
HandleToUint64(event), kVUID_Core_DrawState_InvalidEvent,
"Event %s cannot be waited on if it has never been set.", report_data->FormatHandle(event).c_str());
} else {
stageMask |= global_event_data->stageMask;
}
}
}
// TODO: Need to validate that host_bit is only set if set event is called
// but set event can be called at any time.
if (sourceStageMask != stageMask && sourceStageMask != (stageMask | VK_PIPELINE_STAGE_HOST_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), "VUID-vkCmdWaitEvents-srcStageMask-parameter",
"Submitting cmdbuffer with call to VkCmdWaitEvents using srcStageMask 0x%X which must be the bitwise OR of "
"the stageMask parameters used in calls to vkCmdSetEvent and VK_PIPELINE_STAGE_HOST_BIT if used with "
"vkSetEvent but instead is 0x%X.",
sourceStageMask, stageMask);
}
return skip;
}
// Note that we only check bits that HAVE required queueflags -- don't care entries are skipped
static std::unordered_map<VkPipelineStageFlags, VkQueueFlags> supported_pipeline_stages_table = {
{VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT},
{VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT},
{VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_QUEUE_GRAPHICS_BIT},
{VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_QUEUE_COMPUTE_BIT},
{VK_PIPELINE_STAGE_TRANSFER_BIT, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT},
{VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_QUEUE_GRAPHICS_BIT}};
static const VkPipelineStageFlags stage_flag_bit_array[] = {VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX,
VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT,
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT,
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT};
bool CoreChecks::CheckStageMaskQueueCompatibility(VkCommandBuffer command_buffer, VkPipelineStageFlags stage_mask,
VkQueueFlags queue_flags, const char *function, const char *src_or_dest,
const char *error_code) {
bool skip = false;
// Lookup each bit in the stagemask and check for overlap between its table bits and queue_flags
for (const auto &item : stage_flag_bit_array) {
if (stage_mask & item) {
if ((supported_pipeline_stages_table[item] & queue_flags) == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(command_buffer), error_code,
"%s(): %s flag %s is not compatible with the queue family properties of this command buffer.",
function, src_or_dest, string_VkPipelineStageFlagBits(static_cast<VkPipelineStageFlagBits>(item)));
}
}
}
return skip;
}
// Check if all barriers are of a given operation type.
template <typename Barrier, typename OpCheck>
bool AllTransferOp(const COMMAND_POOL_STATE *pool, OpCheck &op_check, uint32_t count, const Barrier *barriers) {
if (!pool) return false;
for (uint32_t b = 0; b < count; b++) {
if (!op_check(pool, barriers + b)) return false;
}
return true;
}
// Look at the barriers to see if we they are all release or all acquire, the result impacts queue properties validation
BarrierOperationsType CoreChecks::ComputeBarrierOperationsType(CMD_BUFFER_STATE *cb_state, uint32_t buffer_barrier_count,
const VkBufferMemoryBarrier *buffer_barriers,
uint32_t image_barrier_count,
const VkImageMemoryBarrier *image_barriers) {
auto pool = GetCommandPoolState(cb_state->createInfo.commandPool);
BarrierOperationsType op_type = kGeneral;
// Look at the barrier details only if they exist
// Note: AllTransferOp returns true for count == 0
if ((buffer_barrier_count + image_barrier_count) != 0) {
if (AllTransferOp(pool, TempIsReleaseOp<VkBufferMemoryBarrier>, buffer_barrier_count, buffer_barriers) &&
AllTransferOp(pool, TempIsReleaseOp<VkImageMemoryBarrier>, image_barrier_count, image_barriers)) {
op_type = kAllRelease;
} else if (AllTransferOp(pool, IsAcquireOp<VkBufferMemoryBarrier>, buffer_barrier_count, buffer_barriers) &&
AllTransferOp(pool, IsAcquireOp<VkImageMemoryBarrier>, image_barrier_count, image_barriers)) {
op_type = kAllAcquire;
}
}
return op_type;
}
bool CoreChecks::ValidateStageMasksAgainstQueueCapabilities(CMD_BUFFER_STATE const *cb_state,
VkPipelineStageFlags source_stage_mask,
VkPipelineStageFlags dest_stage_mask,
BarrierOperationsType barrier_op_type, const char *function,
const char *error_code) {
bool skip = false;
uint32_t queue_family_index = commandPoolMap[cb_state->createInfo.commandPool].get()->queueFamilyIndex;
auto physical_device_state = GetPhysicalDeviceState();
// Any pipeline stage included in srcStageMask or dstStageMask must be supported by the capabilities of the queue family
// specified by the queueFamilyIndex member of the VkCommandPoolCreateInfo structure that was used to create the VkCommandPool
// that commandBuffer was allocated from, as specified in the table of supported pipeline stages.
if (queue_family_index < physical_device_state->queue_family_properties.size()) {
VkQueueFlags specified_queue_flags = physical_device_state->queue_family_properties[queue_family_index].queueFlags;
// Only check the source stage mask if any barriers aren't "acquire ownership"
if ((barrier_op_type != kAllAcquire) && (source_stage_mask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) == 0) {
skip |= CheckStageMaskQueueCompatibility(cb_state->commandBuffer, source_stage_mask, specified_queue_flags, function,
"srcStageMask", error_code);
}
// Only check the dest stage mask if any barriers aren't "release ownership"
if ((barrier_op_type != kAllRelease) && (dest_stage_mask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) == 0) {
skip |= CheckStageMaskQueueCompatibility(cb_state->commandBuffer, dest_stage_mask, specified_queue_flags, function,
"dstStageMask", error_code);
}
}
return skip;
}
bool CoreChecks::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
VkPipelineStageFlags sourceStageMask, VkPipelineStageFlags dstStageMask,
uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
auto barrier_op_type = ComputeBarrierOperationsType(cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers,
imageMemoryBarrierCount, pImageMemoryBarriers);
bool skip = ValidateStageMasksAgainstQueueCapabilities(cb_state, sourceStageMask, dstStageMask, barrier_op_type,
"vkCmdWaitEvents", "VUID-vkCmdWaitEvents-srcStageMask-01164");
skip |= ValidateStageMaskGsTsEnables(sourceStageMask, "vkCmdWaitEvents()", "VUID-vkCmdWaitEvents-srcStageMask-01159",
"VUID-vkCmdWaitEvents-srcStageMask-01161", "VUID-vkCmdWaitEvents-srcStageMask-02111",
"VUID-vkCmdWaitEvents-srcStageMask-02112");
skip |= ValidateStageMaskGsTsEnables(dstStageMask, "vkCmdWaitEvents()", "VUID-vkCmdWaitEvents-dstStageMask-01160",
"VUID-vkCmdWaitEvents-dstStageMask-01162", "VUID-vkCmdWaitEvents-dstStageMask-02113",
"VUID-vkCmdWaitEvents-dstStageMask-02114");
skip |= ValidateCmdQueueFlags(cb_state, "vkCmdWaitEvents()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdWaitEvents-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_WAITEVENTS, "vkCmdWaitEvents()");
skip |= ValidateBarriersToImages(cb_state, imageMemoryBarrierCount, pImageMemoryBarriers, "vkCmdWaitEvents()");
skip |= ValidateBarriers("vkCmdWaitEvents()", cb_state, sourceStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers,
bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
return skip;
}
void CoreChecks::PreCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
VkPipelineStageFlags sourceStageMask, VkPipelineStageFlags dstStageMask,
uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
auto first_event_index = cb_state->events.size();
for (uint32_t i = 0; i < eventCount; ++i) {
auto event_state = GetEventState(pEvents[i]);
if (event_state) {
AddCommandBufferBinding(&event_state->cb_bindings, {HandleToUint64(pEvents[i]), kVulkanObjectTypeEvent}, cb_state);
event_state->cb_bindings.insert(cb_state);
}
cb_state->waitedEvents.insert(pEvents[i]);
cb_state->events.push_back(pEvents[i]);
}
cb_state->eventUpdates.emplace_back(
[=](VkQueue q) { return ValidateEventStageMask(q, cb_state, eventCount, first_event_index, sourceStageMask); });
TransitionImageLayouts(cb_state, imageMemoryBarrierCount, pImageMemoryBarriers);
if (enabled.gpu_validation) {
GpuPreCallValidateCmdWaitEvents(sourceStageMask);
}
}
void CoreChecks::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
VkPipelineStageFlags sourceStageMask, VkPipelineStageFlags dstStageMask,
uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
RecordBarriersQFOTransfers(cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
pImageMemoryBarriers);
}
bool CoreChecks::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const VkBufferMemoryBarrier *pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const VkImageMemoryBarrier *pImageMemoryBarriers) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = false;
auto barrier_op_type = ComputeBarrierOperationsType(cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers,
imageMemoryBarrierCount, pImageMemoryBarriers);
skip |= ValidateStageMasksAgainstQueueCapabilities(cb_state, srcStageMask, dstStageMask, barrier_op_type,
"vkCmdPipelineBarrier", "VUID-vkCmdPipelineBarrier-srcStageMask-01183");
skip |= ValidateCmdQueueFlags(cb_state, "vkCmdPipelineBarrier()",
VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdPipelineBarrier-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_PIPELINEBARRIER, "vkCmdPipelineBarrier()");
skip |=
ValidateStageMaskGsTsEnables(srcStageMask, "vkCmdPipelineBarrier()", "VUID-vkCmdPipelineBarrier-srcStageMask-01168",
"VUID-vkCmdPipelineBarrier-srcStageMask-01170", "VUID-vkCmdPipelineBarrier-srcStageMask-02115",
"VUID-vkCmdPipelineBarrier-srcStageMask-02116");
skip |=
ValidateStageMaskGsTsEnables(dstStageMask, "vkCmdPipelineBarrier()", "VUID-vkCmdPipelineBarrier-dstStageMask-01169",
"VUID-vkCmdPipelineBarrier-dstStageMask-01171", "VUID-vkCmdPipelineBarrier-dstStageMask-02117",
"VUID-vkCmdPipelineBarrier-dstStageMask-02118");
if (cb_state->activeRenderPass) {
skip |= ValidateRenderPassPipelineBarriers("vkCmdPipelineBarrier()", cb_state, srcStageMask, dstStageMask, dependencyFlags,
memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
if (skip) return true; // Early return to avoid redundant errors from below calls
}
skip |= ValidateBarriersToImages(cb_state, imageMemoryBarrierCount, pImageMemoryBarriers, "vkCmdPipelineBarrier()");
skip |= ValidateBarriers("vkCmdPipelineBarrier()", cb_state, srcStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers,
bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
return skip;
}
void CoreChecks::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const VkBufferMemoryBarrier *pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const VkImageMemoryBarrier *pImageMemoryBarriers) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
RecordBarriersQFOTransfers(cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
pImageMemoryBarriers);
TransitionImageLayouts(cb_state, imageMemoryBarrierCount, pImageMemoryBarriers);
}
bool CoreChecks::SetQueryState(VkQueue queue, VkCommandBuffer commandBuffer, QueryObject object, bool value) {
CMD_BUFFER_STATE *pCB = GetCBState(commandBuffer);
if (pCB) {
pCB->queryToStateMap[object] = value;
}
auto queue_data = queueMap.find(queue);
if (queue_data != queueMap.end()) {
queue_data->second.queryToStateMap[object] = value;
}
return false;
}
bool CoreChecks::ValidateBeginQuery(const CMD_BUFFER_STATE *cb_state, const QueryObject &query_obj, VkFlags flags, CMD_TYPE cmd,
const char *cmd_name, const char *vuid_queue_flags, const char *vuid_queue_feedback,
const char *vuid_queue_occlusion, const char *vuid_precise, const char *vuid_query_count) {
bool skip = false;
const auto &query_pool_ci = GetQueryPoolState(query_obj.pool)->createInfo;
// There are tighter queue constraints to test for certain query pools
if (query_pool_ci.queryType == VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT) {
skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT, vuid_queue_feedback);
}
if (query_pool_ci.queryType == VK_QUERY_TYPE_OCCLUSION) {
skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT, vuid_queue_occlusion);
}
skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, vuid_queue_flags);
if (flags & VK_QUERY_CONTROL_PRECISE_BIT) {
if (!enabled_features.core.occlusionQueryPrecise) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), vuid_precise,
"%s: VK_QUERY_CONTROL_PRECISE_BIT provided, but precise occlusion queries not enabled on the device.",
cmd_name);
}
if (query_pool_ci.queryType != VK_QUERY_TYPE_OCCLUSION) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), vuid_precise,
"%s: VK_QUERY_CONTROL_PRECISE_BIT provided, but pool query type is not VK_QUERY_TYPE_OCCLUSION", cmd_name);
}
}
if (query_obj.query >= query_pool_ci.queryCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), vuid_query_count,
"%s: Query index %" PRIu32 " must be less than query count %" PRIu32 " of query pool %s.", cmd_name,
query_obj.query, query_pool_ci.queryCount, report_data->FormatHandle(query_obj.pool).c_str());
}
skip |= ValidateCmd(cb_state, cmd, cmd_name);
return skip;
}
void CoreChecks::RecordBeginQuery(CMD_BUFFER_STATE *cb_state, const QueryObject &query_obj) {
cb_state->activeQueries.insert(query_obj);
cb_state->startedQueries.insert(query_obj);
AddCommandBufferBinding(&GetQueryPoolState(query_obj.pool)->cb_bindings,
{HandleToUint64(query_obj.pool), kVulkanObjectTypeQueryPool}, cb_state);
}
bool CoreChecks::PreCallValidateCmdBeginQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot, VkFlags flags) {
if (disabled.query_validation) return false;
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
QueryObject query_obj(queryPool, slot);
return ValidateBeginQuery(cb_state, query_obj, flags, CMD_BEGINQUERY, "vkCmdBeginQuery()",
"VUID-vkCmdBeginQuery-commandBuffer-cmdpool", "VUID-vkCmdBeginQuery-queryType-02327",
"VUID-vkCmdBeginQuery-queryType-00803", "VUID-vkCmdBeginQuery-queryType-00800",
"VUID-vkCmdBeginQuery-query-00802");
}
void CoreChecks::PostCallRecordCmdBeginQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot, VkFlags flags) {
QueryObject query = {queryPool, slot};
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
RecordBeginQuery(cb_state, query);
}
bool CoreChecks::ValidateCmdEndQuery(const CMD_BUFFER_STATE *cb_state, const QueryObject &query_obj, CMD_TYPE cmd,
const char *cmd_name, const char *vuid_queue_flags, const char *vuid_active_queries) {
bool skip = false;
if (!cb_state->activeQueries.count(query_obj)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), vuid_active_queries,
"%s: Ending a query before it was started: queryPool %s, index %d.", cmd_name,
report_data->FormatHandle(query_obj.pool).c_str(), query_obj.query);
}
skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, vuid_queue_flags);
skip |= ValidateCmd(cb_state, cmd, cmd_name);
return skip;
}
bool CoreChecks::PreCallValidateCmdEndQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot) {
if (disabled.query_validation) return false;
QueryObject query_obj = {queryPool, slot};
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
return ValidateCmdEndQuery(cb_state, query_obj, CMD_ENDQUERY, "vkCmdEndQuery()", "VUID-vkCmdEndQuery-commandBuffer-cmdpool",
"VUID-vkCmdEndQuery-None-01923");
}
void CoreChecks::RecordCmdEndQuery(CMD_BUFFER_STATE *cb_state, const QueryObject &query_obj) {
cb_state->activeQueries.erase(query_obj);
cb_state->queryUpdates.emplace_back([=](VkQueue q) { return SetQueryState(q, cb_state->commandBuffer, query_obj, true); });
AddCommandBufferBinding(&GetQueryPoolState(query_obj.pool)->cb_bindings,
{HandleToUint64(query_obj.pool), kVulkanObjectTypeQueryPool}, cb_state);
}
void CoreChecks::PostCallRecordCmdEndQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot) {
QueryObject query_obj = {queryPool, slot};
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
RecordCmdEndQuery(cb_state, query_obj);
}
bool CoreChecks::PreCallValidateCmdResetQueryPool(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
uint32_t queryCount) {
if (disabled.query_validation) return false;
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
bool skip = InsideRenderPass(cb_state, "vkCmdResetQueryPool()", "VUID-vkCmdResetQueryPool-renderpass");
skip |= ValidateCmd(cb_state, CMD_RESETQUERYPOOL, "VkCmdResetQueryPool()");
skip |= ValidateCmdQueueFlags(cb_state, "VkCmdResetQueryPool()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdResetQueryPool-commandBuffer-cmdpool");
return skip;
}
void CoreChecks::PostCallRecordCmdResetQueryPool(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
uint32_t queryCount) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
for (uint32_t i = 0; i < queryCount; i++) {
QueryObject query = {queryPool, firstQuery + i};
cb_state->waitedEventsBeforeQueryReset[query] = cb_state->waitedEvents;
cb_state->queryUpdates.emplace_back([=](VkQueue q) { return SetQueryState(q, commandBuffer, query, false); });
}
AddCommandBufferBinding(&GetQueryPoolState(queryPool)->cb_bindings, {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool},
cb_state);
}
bool CoreChecks::IsQueryInvalid(QUEUE_STATE *queue_data, VkQueryPool queryPool, uint32_t queryIndex) {
QueryObject query = {queryPool, queryIndex};
auto query_data = queue_data->queryToStateMap.find(query);
if (query_data != queue_data->queryToStateMap.end()) {
if (!query_data->second) return true;
} else {
auto it = queryToStateMap.find(query);
if (it == queryToStateMap.end() || !it->second) return true;
}
return false;
}
bool CoreChecks::ValidateQuery(VkQueue queue, CMD_BUFFER_STATE *pCB, VkQueryPool queryPool, uint32_t firstQuery,
uint32_t queryCount) {
bool skip = false;
auto queue_data = GetQueueState(queue);
if (!queue_data) return false;
for (uint32_t i = 0; i < queryCount; i++) {
if (IsQueryInvalid(queue_data, queryPool, firstQuery + i)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidQuery,
"Requesting a copy from query to buffer with invalid query: queryPool %s, index %d",
report_data->FormatHandle(queryPool).c_str(), firstQuery + i);
}
}
return skip;
}
bool CoreChecks::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
VkDeviceSize stride, VkQueryResultFlags flags) {
if (disabled.query_validation) return false;
auto cb_state = GetCBState(commandBuffer);
auto dst_buff_state = GetBufferState(dstBuffer);
assert(cb_state);
assert(dst_buff_state);
bool skip = ValidateMemoryIsBoundToBuffer(dst_buff_state, "vkCmdCopyQueryPoolResults()",
"VUID-vkCmdCopyQueryPoolResults-dstBuffer-00826");
// Validate that DST buffer has correct usage flags set
skip |= ValidateBufferUsageFlags(dst_buff_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true,
"VUID-vkCmdCopyQueryPoolResults-dstBuffer-00825", "vkCmdCopyQueryPoolResults()",
"VK_BUFFER_USAGE_TRANSFER_DST_BIT");
skip |= ValidateCmdQueueFlags(cb_state, "vkCmdCopyQueryPoolResults()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdCopyQueryPoolResults-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_COPYQUERYPOOLRESULTS, "vkCmdCopyQueryPoolResults()");
skip |= InsideRenderPass(cb_state, "vkCmdCopyQueryPoolResults()", "VUID-vkCmdCopyQueryPoolResults-renderpass");
return skip;
}
void CoreChecks::PostCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
VkDeviceSize stride, VkQueryResultFlags flags) {
auto cb_state = GetCBState(commandBuffer);
auto dst_buff_state = GetBufferState(dstBuffer);
AddCommandBufferBindingBuffer(cb_state, dst_buff_state);
cb_state->queryUpdates.emplace_back([=](VkQueue q) { return ValidateQuery(q, cb_state, queryPool, firstQuery, queryCount); });
AddCommandBufferBinding(&GetQueryPoolState(queryPool)->cb_bindings, {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool},
cb_state);
}
bool CoreChecks::PreCallValidateCmdPushConstants(VkCommandBuffer commandBuffer, VkPipelineLayout layout,
VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size,
const void *pValues) {
bool skip = false;
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
skip |= ValidateCmdQueueFlags(cb_state, "vkCmdPushConstants()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdPushConstants-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_PUSHCONSTANTS, "vkCmdPushConstants()");
skip |= ValidatePushConstantRange(offset, size, "vkCmdPushConstants()");
if (0 == stageFlags) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdPushConstants-stageFlags-requiredbitmask",
"vkCmdPushConstants() call has no stageFlags set.");
}
// Check if pipeline_layout VkPushConstantRange(s) overlapping offset, size have stageFlags set for each stage in the command
// stageFlags argument, *and* that the command stageFlags argument has bits set for the stageFlags in each overlapping range.
if (!skip) {
const auto &ranges = *GetPipelineLayout(layout)->push_constant_ranges;
VkShaderStageFlags found_stages = 0;
for (const auto &range : ranges) {
if ((offset >= range.offset) && (offset + size <= range.offset + range.size)) {
VkShaderStageFlags matching_stages = range.stageFlags & stageFlags;
if (matching_stages != range.stageFlags) {
// "VUID-vkCmdPushConstants-offset-01796" VUID-vkCmdPushConstants-offset-01796
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdPushConstants-offset-01796",
"vkCmdPushConstants(): stageFlags (0x%" PRIx32 ", offset (%" PRIu32 "), and size (%" PRIu32
"), must contain all stages in overlapping VkPushConstantRange stageFlags (0x%" PRIx32
"), offset (%" PRIu32 "), and size (%" PRIu32 ") in pipeline layout %s.",
(uint32_t)stageFlags, offset, size, (uint32_t)range.stageFlags, range.offset, range.size,
report_data->FormatHandle(layout).c_str());
}
// Accumulate all stages we've found
found_stages = matching_stages | found_stages;
}
}
if (found_stages != stageFlags) {
// "VUID-vkCmdPushConstants-offset-01795" VUID-vkCmdPushConstants-offset-01795
uint32_t missing_stages = ~found_stages & stageFlags;
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdPushConstants-offset-01795",
"vkCmdPushConstants(): stageFlags = 0x%" PRIx32
", VkPushConstantRange in pipeline layout %s overlapping offset = %d and size = %d, do not contain "
"stageFlags 0x%" PRIx32 ".",
(uint32_t)stageFlags, report_data->FormatHandle(layout).c_str(), offset, size, missing_stages);
}
}
return skip;
}
bool CoreChecks::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
VkQueryPool queryPool, uint32_t slot) {
if (disabled.query_validation) return false;
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = ValidateCmdQueueFlags(cb_state, "vkCmdWriteTimestamp()",
VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT,
"VUID-vkCmdWriteTimestamp-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_WRITETIMESTAMP, "vkCmdWriteTimestamp()");
return skip;
}
void CoreChecks::PostCallRecordCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
VkQueryPool queryPool, uint32_t slot) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
QueryObject query = {queryPool, slot};
cb_state->queryUpdates.emplace_back([=](VkQueue q) { return SetQueryState(q, commandBuffer, query, true); });
}
bool CoreChecks::MatchUsage(uint32_t count, const VkAttachmentReference2KHR *attachments, const VkFramebufferCreateInfo *fbci,
VkImageUsageFlagBits usage_flag, const char *error_code) {
bool skip = false;
for (uint32_t attach = 0; attach < count; attach++) {
if (attachments[attach].attachment != VK_ATTACHMENT_UNUSED) {
// Attachment counts are verified elsewhere, but prevent an invalid access
if (attachments[attach].attachment < fbci->attachmentCount) {
const VkImageView *image_view = &fbci->pAttachments[attachments[attach].attachment];
auto view_state = GetImageViewState(*image_view);
if (view_state) {
const VkImageCreateInfo *ici = &GetImageState(view_state->create_info.image)->createInfo;
if (ici != nullptr) {
if ((ici->usage & usage_flag) == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
error_code,
"vkCreateFramebuffer: Framebuffer Attachment (%d) conflicts with the image's "
"IMAGE_USAGE flags (%s).",
attachments[attach].attachment, string_VkImageUsageFlagBits(usage_flag));
}
}
}
}
}
}
return skip;
}
// Validate VkFramebufferCreateInfo which includes:
// 1. attachmentCount equals renderPass attachmentCount
// 2. corresponding framebuffer and renderpass attachments have matching formats
// 3. corresponding framebuffer and renderpass attachments have matching sample counts
// 4. fb attachments only have a single mip level
// 5. fb attachment dimensions are each at least as large as the fb
// 6. fb attachments use idenity swizzle
// 7. fb attachments used by renderPass for color/input/ds have correct usage bit set
// 8. fb dimensions are within physical device limits
bool CoreChecks::ValidateFramebufferCreateInfo(const VkFramebufferCreateInfo *pCreateInfo) {
bool skip = false;
auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
if (rp_state) {
const VkRenderPassCreateInfo2KHR *rpci = rp_state->createInfo.ptr();
if (rpci->attachmentCount != pCreateInfo->attachmentCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(pCreateInfo->renderPass), "VUID-VkFramebufferCreateInfo-attachmentCount-00876",
"vkCreateFramebuffer(): VkFramebufferCreateInfo attachmentCount of %u does not match attachmentCount "
"of %u of renderPass (%s) being used to create Framebuffer.",
pCreateInfo->attachmentCount, rpci->attachmentCount,
report_data->FormatHandle(pCreateInfo->renderPass).c_str());
} else {
// attachmentCounts match, so make sure corresponding attachment details line up
const VkImageView *image_views = pCreateInfo->pAttachments;
for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
auto view_state = GetImageViewState(image_views[i]);
auto &ivci = view_state->create_info;
if (ivci.format != rpci->pAttachments[i].format) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(pCreateInfo->renderPass), "VUID-VkFramebufferCreateInfo-pAttachments-00880",
"vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has format of %s that does not "
"match the format of %s used by the corresponding attachment for renderPass (%s).",
i, string_VkFormat(ivci.format), string_VkFormat(rpci->pAttachments[i].format),
report_data->FormatHandle(pCreateInfo->renderPass).c_str());
}
const VkImageCreateInfo *ici = &GetImageState(ivci.image)->createInfo;
if (ici->samples != rpci->pAttachments[i].samples) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(pCreateInfo->renderPass), "VUID-VkFramebufferCreateInfo-pAttachments-00881",
"vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has %s samples that do not match the %s "
"samples used by the corresponding attachment for renderPass (%s).",
i, string_VkSampleCountFlagBits(ici->samples), string_VkSampleCountFlagBits(rpci->pAttachments[i].samples),
report_data->FormatHandle(pCreateInfo->renderPass).c_str());
}
// Verify that view only has a single mip level
if (ivci.subresourceRange.levelCount != 1) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-pAttachments-00883",
"vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has mip levelCount of %u but "
"only a single mip level (levelCount == 1) is allowed when creating a Framebuffer.",
i, ivci.subresourceRange.levelCount);
}
const uint32_t mip_level = ivci.subresourceRange.baseMipLevel;
uint32_t mip_width = max(1u, ici->extent.width >> mip_level);
uint32_t mip_height = max(1u, ici->extent.height >> mip_level);
if ((ivci.subresourceRange.layerCount < pCreateInfo->layers) || (mip_width < pCreateInfo->width) ||
(mip_height < pCreateInfo->height)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-pAttachments-00882",
"vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level %u has dimensions "
"smaller than the corresponding framebuffer dimensions. Here are the respective dimensions for "
"attachment #%u, framebuffer:\n"
"width: %u, %u\n"
"height: %u, %u\n"
"layerCount: %u, %u\n",
i, ivci.subresourceRange.baseMipLevel, i, mip_width, pCreateInfo->width, mip_height,
pCreateInfo->height, ivci.subresourceRange.layerCount, pCreateInfo->layers);
}
if (((ivci.components.r != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.r != VK_COMPONENT_SWIZZLE_R)) ||
((ivci.components.g != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.g != VK_COMPONENT_SWIZZLE_G)) ||
((ivci.components.b != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.b != VK_COMPONENT_SWIZZLE_B)) ||
((ivci.components.a != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.a != VK_COMPONENT_SWIZZLE_A))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-pAttachments-00884",
"vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has non-identy swizzle. All "
"framebuffer attachments must have been created with the identity swizzle. Here are the actual "
"swizzle values:\n"
"r swizzle = %s\n"
"g swizzle = %s\n"
"b swizzle = %s\n"
"a swizzle = %s\n",
i, string_VkComponentSwizzle(ivci.components.r), string_VkComponentSwizzle(ivci.components.g),
string_VkComponentSwizzle(ivci.components.b), string_VkComponentSwizzle(ivci.components.a));
}
}
}
// Verify correct attachment usage flags
for (uint32_t subpass = 0; subpass < rpci->subpassCount; subpass++) {
// Verify input attachments:
skip |= MatchUsage(rpci->pSubpasses[subpass].inputAttachmentCount, rpci->pSubpasses[subpass].pInputAttachments,
pCreateInfo, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-00879");
// Verify color attachments:
skip |= MatchUsage(rpci->pSubpasses[subpass].colorAttachmentCount, rpci->pSubpasses[subpass].pColorAttachments,
pCreateInfo, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-00877");
// Verify depth/stencil attachments:
if (rpci->pSubpasses[subpass].pDepthStencilAttachment != nullptr) {
skip |= MatchUsage(1, rpci->pSubpasses[subpass].pDepthStencilAttachment, pCreateInfo,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-02633");
}
}
}
// Verify FB dimensions are within physical device limits
if (pCreateInfo->width > phys_dev_props.limits.maxFramebufferWidth) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-width-00886",
"vkCreateFramebuffer(): Requested VkFramebufferCreateInfo width exceeds physical device limits. Requested "
"width: %u, device max: %u\n",
pCreateInfo->width, phys_dev_props.limits.maxFramebufferWidth);
}
if (pCreateInfo->height > phys_dev_props.limits.maxFramebufferHeight) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-height-00888",
"vkCreateFramebuffer(): Requested VkFramebufferCreateInfo height exceeds physical device limits. Requested "
"height: %u, device max: %u\n",
pCreateInfo->height, phys_dev_props.limits.maxFramebufferHeight);
}
if (pCreateInfo->layers > phys_dev_props.limits.maxFramebufferLayers) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-layers-00890",
"vkCreateFramebuffer(): Requested VkFramebufferCreateInfo layers exceeds physical device limits. Requested "
"layers: %u, device max: %u\n",
pCreateInfo->layers, phys_dev_props.limits.maxFramebufferLayers);
}
// Verify FB dimensions are greater than zero
if (pCreateInfo->width <= 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-width-00885",
"vkCreateFramebuffer(): Requested VkFramebufferCreateInfo width must be greater than zero.");
}
if (pCreateInfo->height <= 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-height-00887",
"vkCreateFramebuffer(): Requested VkFramebufferCreateInfo height must be greater than zero.");
}
if (pCreateInfo->layers <= 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkFramebufferCreateInfo-layers-00889",
"vkCreateFramebuffer(): Requested VkFramebufferCreateInfo layers must be greater than zero.");
}
return skip;
}
bool CoreChecks::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkFramebuffer *pFramebuffer) {
// TODO : Verify that renderPass FB is created with is compatible with FB
bool skip = false;
skip |= ValidateFramebufferCreateInfo(pCreateInfo);
return skip;
}
void CoreChecks::PostCallRecordCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkFramebuffer *pFramebuffer,
VkResult result) {
if (VK_SUCCESS != result) return;
// Shadow create info and store in map
std::unique_ptr<FRAMEBUFFER_STATE> fb_state(
new FRAMEBUFFER_STATE(*pFramebuffer, pCreateInfo, GetRenderPassStateSharedPtr(pCreateInfo->renderPass)));
for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
VkImageView view = pCreateInfo->pAttachments[i];
auto view_state = GetImageViewState(view);
if (!view_state) {
continue;
}
}
frameBufferMap[*pFramebuffer] = std::move(fb_state);
}
static bool FindDependency(const uint32_t index, const uint32_t dependent, const std::vector<DAGNode> &subpass_to_node,
std::unordered_set<uint32_t> &processed_nodes) {
// If we have already checked this node we have not found a dependency path so return false.
if (processed_nodes.count(index)) return false;
processed_nodes.insert(index);
const DAGNode &node = subpass_to_node[index];
// Look for a dependency path. If one exists return true else recurse on the previous nodes.
if (std::find(node.prev.begin(), node.prev.end(), dependent) == node.prev.end()) {
for (auto elem : node.prev) {
if (FindDependency(elem, dependent, subpass_to_node, processed_nodes)) return true;
}
} else {
return true;
}
return false;
}
bool CoreChecks::CheckDependencyExists(const uint32_t subpass, const std::vector<uint32_t> &dependent_subpasses,
const std::vector<DAGNode> &subpass_to_node, bool &skip) {
bool result = true;
// Loop through all subpasses that share the same attachment and make sure a dependency exists
for (uint32_t k = 0; k < dependent_subpasses.size(); ++k) {
if (static_cast<uint32_t>(subpass) == dependent_subpasses[k]) continue;
const DAGNode &node = subpass_to_node[subpass];
// Check for a specified dependency between the two nodes. If one exists we are done.
auto prev_elem = std::find(node.prev.begin(), node.prev.end(), dependent_subpasses[k]);
auto next_elem = std::find(node.next.begin(), node.next.end(), dependent_subpasses[k]);
if (prev_elem == node.prev.end() && next_elem == node.next.end()) {
// If no dependency exits an implicit dependency still might. If not, throw an error.
std::unordered_set<uint32_t> processed_nodes;
if (!(FindDependency(subpass, dependent_subpasses[k], subpass_to_node, processed_nodes) ||
FindDependency(dependent_subpasses[k], subpass, subpass_to_node, processed_nodes))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_InvalidRenderpass,
"A dependency between subpasses %d and %d must exist but one is not specified.", subpass,
dependent_subpasses[k]);
result = false;
}
}
}
return result;
}
bool CoreChecks::CheckPreserved(const VkRenderPassCreateInfo2KHR *pCreateInfo, const int index, const uint32_t attachment,
const std::vector<DAGNode> &subpass_to_node, int depth, bool &skip) {
const DAGNode &node = subpass_to_node[index];
// If this node writes to the attachment return true as next nodes need to preserve the attachment.
const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[index];
for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
if (attachment == subpass.pColorAttachments[j].attachment) return true;
}
for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
if (attachment == subpass.pInputAttachments[j].attachment) return true;
}
if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
if (attachment == subpass.pDepthStencilAttachment->attachment) return true;
}
bool result = false;
// Loop through previous nodes and see if any of them write to the attachment.
for (auto elem : node.prev) {
result |= CheckPreserved(pCreateInfo, elem, attachment, subpass_to_node, depth + 1, skip);
}
// If the attachment was written to by a previous node than this node needs to preserve it.
if (result && depth > 0) {
bool has_preserved = false;
for (uint32_t j = 0; j < subpass.preserveAttachmentCount; ++j) {
if (subpass.pPreserveAttachments[j] == attachment) {
has_preserved = true;
break;
}
}
if (!has_preserved) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_InvalidRenderpass,
"Attachment %d is used by a later subpass and must be preserved in subpass %d.", attachment, index);
}
}
return result;
}
template <class T>
bool IsRangeOverlapping(T offset1, T size1, T offset2, T size2) {
return (((offset1 + size1) > offset2) && ((offset1 + size1) < (offset2 + size2))) ||
((offset1 > offset2) && (offset1 < (offset2 + size2)));
}
bool IsRegionOverlapping(VkImageSubresourceRange range1, VkImageSubresourceRange range2) {
return (IsRangeOverlapping(range1.baseMipLevel, range1.levelCount, range2.baseMipLevel, range2.levelCount) &&
IsRangeOverlapping(range1.baseArrayLayer, range1.layerCount, range2.baseArrayLayer, range2.layerCount));
}
bool CoreChecks::ValidateDependencies(FRAMEBUFFER_STATE const *framebuffer, RENDER_PASS_STATE const *renderPass) {
bool skip = false;
auto const pFramebufferInfo = framebuffer->createInfo.ptr();
auto const pCreateInfo = renderPass->createInfo.ptr();
auto const &subpass_to_node = renderPass->subpassToNode;
std::vector<std::vector<uint32_t>> output_attachment_to_subpass(pCreateInfo->attachmentCount);
std::vector<std::vector<uint32_t>> input_attachment_to_subpass(pCreateInfo->attachmentCount);
std::vector<std::vector<uint32_t>> overlapping_attachments(pCreateInfo->attachmentCount);
// Find overlapping attachments
for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
for (uint32_t j = i + 1; j < pCreateInfo->attachmentCount; ++j) {
VkImageView viewi = pFramebufferInfo->pAttachments[i];
VkImageView viewj = pFramebufferInfo->pAttachments[j];
if (viewi == viewj) {
overlapping_attachments[i].push_back(j);
overlapping_attachments[j].push_back(i);
continue;
}
auto view_state_i = GetImageViewState(viewi);
auto view_state_j = GetImageViewState(viewj);
if (!view_state_i || !view_state_j) {
continue;
}
auto view_ci_i = view_state_i->create_info;
auto view_ci_j = view_state_j->create_info;
if (view_ci_i.image == view_ci_j.image && IsRegionOverlapping(view_ci_i.subresourceRange, view_ci_j.subresourceRange)) {
overlapping_attachments[i].push_back(j);
overlapping_attachments[j].push_back(i);
continue;
}
auto image_data_i = GetImageState(view_ci_i.image);
auto image_data_j = GetImageState(view_ci_j.image);
if (!image_data_i || !image_data_j) {
continue;
}
if (image_data_i->binding.mem == image_data_j->binding.mem &&
IsRangeOverlapping(image_data_i->binding.offset, image_data_i->binding.size, image_data_j->binding.offset,
image_data_j->binding.size)) {
overlapping_attachments[i].push_back(j);
overlapping_attachments[j].push_back(i);
}
}
}
// Find for each attachment the subpasses that use them.
unordered_set<uint32_t> attachmentIndices;
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i];
attachmentIndices.clear();
for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
uint32_t attachment = subpass.pInputAttachments[j].attachment;
if (attachment == VK_ATTACHMENT_UNUSED) continue;
input_attachment_to_subpass[attachment].push_back(i);
for (auto overlapping_attachment : overlapping_attachments[attachment]) {
input_attachment_to_subpass[overlapping_attachment].push_back(i);
}
}
for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
uint32_t attachment = subpass.pColorAttachments[j].attachment;
if (attachment == VK_ATTACHMENT_UNUSED) continue;
output_attachment_to_subpass[attachment].push_back(i);
for (auto overlapping_attachment : overlapping_attachments[attachment]) {
output_attachment_to_subpass[overlapping_attachment].push_back(i);
}
attachmentIndices.insert(attachment);
}
if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
uint32_t attachment = subpass.pDepthStencilAttachment->attachment;
output_attachment_to_subpass[attachment].push_back(i);
for (auto overlapping_attachment : overlapping_attachments[attachment]) {
output_attachment_to_subpass[overlapping_attachment].push_back(i);
}
if (attachmentIndices.count(attachment)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_InvalidRenderpass,
"Cannot use same attachment (%u) as both color and depth output in same subpass (%u).", attachment, i);
}
}
}
// If there is a dependency needed make sure one exists
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i];
// If the attachment is an input then all subpasses that output must have a dependency relationship
for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
uint32_t attachment = subpass.pInputAttachments[j].attachment;
if (attachment == VK_ATTACHMENT_UNUSED) continue;
CheckDependencyExists(i, output_attachment_to_subpass[attachment], subpass_to_node, skip);
}
// If the attachment is an output then all subpasses that use the attachment must have a dependency relationship
for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
uint32_t attachment = subpass.pColorAttachments[j].attachment;
if (attachment == VK_ATTACHMENT_UNUSED) continue;
CheckDependencyExists(i, output_attachment_to_subpass[attachment], subpass_to_node, skip);
CheckDependencyExists(i, input_attachment_to_subpass[attachment], subpass_to_node, skip);
}
if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
const uint32_t &attachment = subpass.pDepthStencilAttachment->attachment;
CheckDependencyExists(i, output_attachment_to_subpass[attachment], subpass_to_node, skip);
CheckDependencyExists(i, input_attachment_to_subpass[attachment], subpass_to_node, skip);
}
}
// Loop through implicit dependencies, if this pass reads make sure the attachment is preserved for all passes after it was
// written.
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i];
for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
CheckPreserved(pCreateInfo, i, subpass.pInputAttachments[j].attachment, subpass_to_node, 0, skip);
}
}
return skip;
}
void CoreChecks::RecordRenderPassDAG(RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2KHR *pCreateInfo,
RENDER_PASS_STATE *render_pass) {
auto &subpass_to_node = render_pass->subpassToNode;
subpass_to_node.resize(pCreateInfo->subpassCount);
auto &self_dependencies = render_pass->self_dependencies;
self_dependencies.resize(pCreateInfo->subpassCount);
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
subpass_to_node[i].pass = i;
self_dependencies[i].clear();
}
for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) {
const VkSubpassDependency2KHR &dependency = pCreateInfo->pDependencies[i];
if ((dependency.srcSubpass != VK_SUBPASS_EXTERNAL) && (dependency.dstSubpass != VK_SUBPASS_EXTERNAL)) {
if (dependency.srcSubpass == dependency.dstSubpass) {
self_dependencies[dependency.srcSubpass].push_back(i);
} else {
subpass_to_node[dependency.dstSubpass].prev.push_back(dependency.srcSubpass);
subpass_to_node[dependency.srcSubpass].next.push_back(dependency.dstSubpass);
}
}
}
}
bool CoreChecks::ValidateRenderPassDAG(RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2KHR *pCreateInfo,
RENDER_PASS_STATE *render_pass) {
// Shorthand...
auto &subpass_to_node = render_pass->subpassToNode;
subpass_to_node.resize(pCreateInfo->subpassCount);
auto &self_dependencies = render_pass->self_dependencies;
self_dependencies.resize(pCreateInfo->subpassCount);
bool skip = false;
const char *vuid;
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
subpass_to_node[i].pass = i;
self_dependencies[i].clear();
}
for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) {
const VkSubpassDependency2KHR &dependency = pCreateInfo->pDependencies[i];
VkPipelineStageFlags exclude_graphics_pipeline_stages =
~(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | ExpandPipelineStageFlags(device_extensions, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT));
VkPipelineStageFlagBits latest_src_stage = GetLogicallyLatestGraphicsPipelineStage(dependency.srcStageMask);
VkPipelineStageFlagBits earliest_dst_stage = GetLogicallyEarliestGraphicsPipelineStage(dependency.dstStageMask);
// This VU is actually generalised to *any* pipeline - not just graphics - but only graphics render passes are
// currently supported by the spec - so only that pipeline is checked here.
// If that is ever relaxed, this check should be extended to cover those pipelines.
if (dependency.srcSubpass == dependency.dstSubpass && (dependency.srcStageMask & exclude_graphics_pipeline_stages) != 0u &&
(dependency.dstStageMask & exclude_graphics_pipeline_stages) != 0u) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-02244" : "VUID-VkSubpassDependency-srcSubpass-01989";
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u is a self-dependency, but specifies stage masks that contain stages not in the GRAPHICS pipeline.",
i);
} else if (dependency.srcSubpass != VK_SUBPASS_EXTERNAL && (dependency.srcStageMask & VK_PIPELINE_STAGE_HOST_BIT)) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-03078" : "VUID-VkSubpassDependency-srcSubpass-00858";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a dependency from subpass %u, but includes HOST_BIT in the source stage mask.",
i, dependency.srcSubpass);
} else if (dependency.dstSubpass != VK_SUBPASS_EXTERNAL && (dependency.dstStageMask & VK_PIPELINE_STAGE_HOST_BIT)) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-dstSubpass-03079" : "VUID-VkSubpassDependency-dstSubpass-00859";
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a dependency to subpass %u, but includes HOST_BIT in the destination stage mask.",
i, dependency.dstSubpass);
}
// These next two VUs are actually generalised to *any* pipeline - not just graphics - but only graphics render passes are
// currently supported by the spec - so only that pipeline is checked here.
// If that is ever relaxed, these next two checks should be extended to cover those pipelines.
else if (dependency.srcSubpass != VK_SUBPASS_EXTERNAL &&
pCreateInfo->pSubpasses[dependency.srcSubpass].pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS &&
(dependency.srcStageMask & exclude_graphics_pipeline_stages) != 0u) {
vuid =
use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-pDependencies-03054" : "VUID-VkRenderPassCreateInfo-pDependencies-00837";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a source stage mask that contains stages not in the GRAPHICS pipeline as used "
"by the source subpass %u.",
i, dependency.srcSubpass);
} else if (dependency.dstSubpass != VK_SUBPASS_EXTERNAL &&
pCreateInfo->pSubpasses[dependency.dstSubpass].pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS &&
(dependency.dstStageMask & exclude_graphics_pipeline_stages) != 0u) {
vuid =
use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-pDependencies-03055" : "VUID-VkRenderPassCreateInfo-pDependencies-00838";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a destination stage mask that contains stages not in the GRAPHICS pipeline as "
"used by the destination subpass %u.",
i, dependency.dstSubpass);
}
// The first subpass here serves as a good proxy for "is multiview enabled" - since all view masks need to be non-zero if
// any are, which enables multiview.
else if (use_rp2 && (dependency.dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) &&
(pCreateInfo->pSubpasses[0].viewMask == 0)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkRenderPassCreateInfo2KHR-viewMask-03059",
"Dependency %u specifies the VK_DEPENDENCY_VIEW_LOCAL_BIT, but multiview is not enabled for this render pass.", i);
} else if (use_rp2 && !(dependency.dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) && dependency.viewOffset != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDependency2KHR-dependencyFlags-03092",
"Dependency %u specifies the VK_DEPENDENCY_VIEW_LOCAL_BIT, but also specifies a view offset of %u.", i,
dependency.viewOffset);
} else if (dependency.srcSubpass == VK_SUBPASS_EXTERNAL || dependency.dstSubpass == VK_SUBPASS_EXTERNAL) {
if (dependency.srcSubpass == dependency.dstSubpass) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-03085" : "VUID-VkSubpassDependency-srcSubpass-00865";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"The src and dst subpasses in dependency %u are both external.", i);
} else if (dependency.dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) {
if (dependency.srcSubpass == VK_SUBPASS_EXTERNAL) {
vuid = "VUID-VkSubpassDependency-dependencyFlags-02520";
} else { // dependency.dstSubpass == VK_SUBPASS_EXTERNAL
vuid = "VUID-VkSubpassDependency-dependencyFlags-02521";
}
if (use_rp2) {
// Create render pass 2 distinguishes between source and destination external dependencies.
if (dependency.srcSubpass == VK_SUBPASS_EXTERNAL) {
vuid = "VUID-VkSubpassDependency2KHR-dependencyFlags-03090";
} else {
vuid = "VUID-VkSubpassDependency2KHR-dependencyFlags-03091";
}
}
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies an external dependency but also specifies VK_DEPENDENCY_VIEW_LOCAL_BIT.", i);
}
} else if (dependency.srcSubpass > dependency.dstSubpass) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-03084" : "VUID-VkSubpassDependency-srcSubpass-00864";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a dependency from a later subpass (%u) to an earlier subpass (%u), which is "
"disallowed to prevent cyclic dependencies.",
i, dependency.srcSubpass, dependency.dstSubpass);
} else if (dependency.srcSubpass == dependency.dstSubpass) {
if (dependency.viewOffset != 0) {
vuid = use_rp2 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkRenderPassCreateInfo-pNext-01930";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a self-dependency but has a non-zero view offset of %u", i,
dependency.viewOffset);
} else if ((dependency.dependencyFlags | VK_DEPENDENCY_VIEW_LOCAL_BIT) != dependency.dependencyFlags &&
pCreateInfo->pSubpasses[dependency.srcSubpass].viewMask > 1) {
vuid =
use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-pDependencies-03060" : "VUID-VkSubpassDependency-srcSubpass-00872";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a self-dependency for subpass %u with a non-zero view mask, but does not "
"specify VK_DEPENDENCY_VIEW_LOCAL_BIT.",
i, dependency.srcSubpass);
} else if ((HasNonFramebufferStagePipelineStageFlags(dependency.srcStageMask) ||
HasNonFramebufferStagePipelineStageFlags(dependency.dstStageMask)) &&
(GetGraphicsPipelineStageLogicalOrdinal(latest_src_stage) >
GetGraphicsPipelineStageLogicalOrdinal(earliest_dst_stage))) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-03087" : "VUID-VkSubpassDependency-srcSubpass-00867";
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"Dependency %u specifies a self-dependency from logically-later stage (%s) to a logically-earlier stage (%s).",
i, string_VkPipelineStageFlagBits(latest_src_stage), string_VkPipelineStageFlagBits(earliest_dst_stage));
} else {
self_dependencies[dependency.srcSubpass].push_back(i);
}
} else {
subpass_to_node[dependency.dstSubpass].prev.push_back(dependency.srcSubpass);
subpass_to_node[dependency.srcSubpass].next.push_back(dependency.dstSubpass);
}
}
return skip;
}
bool CoreChecks::ValidateAttachmentIndex(RenderPassCreateVersion rp_version, uint32_t attachment, uint32_t attachment_count,
const char *type) {
bool skip = false;
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()";
if (attachment >= attachment_count && attachment != VK_ATTACHMENT_UNUSED) {
const char *vuid =
use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-attachment-03051" : "VUID-VkRenderPassCreateInfo-attachment-00834";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: %s attachment %d must be less than the total number of attachments %d.", type, function_name,
attachment, attachment_count);
}
return skip;
}
enum AttachmentType {
ATTACHMENT_COLOR = 1,
ATTACHMENT_DEPTH = 2,
ATTACHMENT_INPUT = 4,
ATTACHMENT_PRESERVE = 8,
ATTACHMENT_RESOLVE = 16,
};
char const *StringAttachmentType(uint8_t type) {
switch (type) {
case ATTACHMENT_COLOR:
return "color";
case ATTACHMENT_DEPTH:
return "depth";
case ATTACHMENT_INPUT:
return "input";
case ATTACHMENT_PRESERVE:
return "preserve";
case ATTACHMENT_RESOLVE:
return "resolve";
default:
return "(multiple)";
}
}
bool CoreChecks::AddAttachmentUse(RenderPassCreateVersion rp_version, uint32_t subpass, std::vector<uint8_t> &attachment_uses,
std::vector<VkImageLayout> &attachment_layouts, uint32_t attachment, uint8_t new_use,
VkImageLayout new_layout) {
if (attachment >= attachment_uses.size()) return false; /* out of range, but already reported */
bool skip = false;
auto &uses = attachment_uses[attachment];
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
const char *vuid;
const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()";
if (uses & new_use) {
if (attachment_layouts[attachment] != new_layout) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-layout-02528" : "VUID-VkSubpassDescription-layout-02519";
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: subpass %u already uses attachment %u with a different image layout (%s vs %s).", function_name, subpass,
attachment, string_VkImageLayout(attachment_layouts[attachment]), string_VkImageLayout(new_layout));
}
} else if (uses & ~ATTACHMENT_INPUT || (uses && (new_use == ATTACHMENT_RESOLVE || new_use == ATTACHMENT_PRESERVE))) {
/* Note: input attachments are assumed to be done first. */
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pPreserveAttachments-03074"
: "VUID-VkSubpassDescription-pPreserveAttachments-00854";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: subpass %u uses attachment %u as both %s and %s attachment.", function_name, subpass, attachment,
StringAttachmentType(uses), StringAttachmentType(new_use));
} else {
attachment_layouts[attachment] = new_layout;
uses |= new_use;
}
return skip;
}
bool CoreChecks::ValidateRenderpassAttachmentUsage(RenderPassCreateVersion rp_version,
const VkRenderPassCreateInfo2KHR *pCreateInfo) {
bool skip = false;
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
const char *vuid;
const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()";
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i];
std::vector<uint8_t> attachment_uses(pCreateInfo->attachmentCount);
std::vector<VkImageLayout> attachment_layouts(pCreateInfo->attachmentCount);
if (subpass.pipelineBindPoint != VK_PIPELINE_BIND_POINT_GRAPHICS) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pipelineBindPoint-03062"
: "VUID-VkSubpassDescription-pipelineBindPoint-00844";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Pipeline bind point for subpass %d must be VK_PIPELINE_BIND_POINT_GRAPHICS.", function_name, i);
}
for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
auto const &attachment_ref = subpass.pInputAttachments[j];
if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) {
skip |= ValidateAttachmentIndex(rp_version, attachment_ref.attachment, pCreateInfo->attachmentCount, "Input");
if (attachment_ref.aspectMask & VK_IMAGE_ASPECT_METADATA_BIT) {
vuid =
use_rp2 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkInputAttachmentAspectReference-aspectMask-01964";
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Aspect mask for input attachment reference %d in subpass %d includes VK_IMAGE_ASPECT_METADATA_BIT.",
function_name, i, j);
}
if (attachment_ref.attachment < pCreateInfo->attachmentCount) {
skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment_ref.attachment,
ATTACHMENT_INPUT, attachment_ref.layout);
vuid = use_rp2 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkRenderPassCreateInfo-pNext-01963";
skip |= ValidateImageAspectMask(VK_NULL_HANDLE, pCreateInfo->pAttachments[attachment_ref.attachment].format,
attachment_ref.aspectMask, function_name, vuid);
}
}
if (rp_version == RENDER_PASS_VERSION_2) {
// These are validated automatically as part of parameter validation for create renderpass 1
// as they are in a struct that only applies to input attachments - not so for v2.
// Check for 0
if (attachment_ref.aspectMask == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescription2KHR-aspectMask-03176",
"%s: Input attachment (%d) aspect mask must not be 0.", function_name, j);
} else {
const VkImageAspectFlags valid_bits =
(VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT |
VK_IMAGE_ASPECT_METADATA_BIT | VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT |
VK_IMAGE_ASPECT_PLANE_2_BIT);
// Check for valid aspect mask bits
if (attachment_ref.aspectMask & ~valid_bits) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescription2KHR-aspectMask-03175",
"%s: Input attachment (%d) aspect mask (0x%" PRIx32 ")is invalid.", function_name, j,
attachment_ref.aspectMask);
}
}
}
}
for (uint32_t j = 0; j < subpass.preserveAttachmentCount; ++j) {
uint32_t attachment = subpass.pPreserveAttachments[j];
if (attachment == VK_ATTACHMENT_UNUSED) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-attachment-03073" : "VUID-VkSubpassDescription-attachment-00853";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Preserve attachment (%d) must not be VK_ATTACHMENT_UNUSED.", function_name, j);
} else {
skip |= ValidateAttachmentIndex(rp_version, attachment, pCreateInfo->attachmentCount, "Preserve");
if (attachment < pCreateInfo->attachmentCount) {
skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment, ATTACHMENT_PRESERVE,
VkImageLayout(0) /* preserve doesn't have any layout */);
}
}
}
bool subpass_performs_resolve = false;
for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
if (subpass.pResolveAttachments) {
auto const &attachment_ref = subpass.pResolveAttachments[j];
if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) {
skip |= ValidateAttachmentIndex(rp_version, attachment_ref.attachment, pCreateInfo->attachmentCount, "Resolve");
if (attachment_ref.attachment < pCreateInfo->attachmentCount) {
skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment_ref.attachment,
ATTACHMENT_RESOLVE, attachment_ref.layout);
subpass_performs_resolve = true;
if (pCreateInfo->pAttachments[attachment_ref.attachment].samples != VK_SAMPLE_COUNT_1_BIT) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pResolveAttachments-03067"
: "VUID-VkSubpassDescription-pResolveAttachments-00849";
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Subpass %u requests multisample resolve into attachment %u, which must "
"have VK_SAMPLE_COUNT_1_BIT but has %s.",
function_name, i, attachment_ref.attachment,
string_VkSampleCountFlagBits(pCreateInfo->pAttachments[attachment_ref.attachment].samples));
}
}
}
}
}
if (subpass.pDepthStencilAttachment) {
if (subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
skip |= ValidateAttachmentIndex(rp_version, subpass.pDepthStencilAttachment->attachment,
pCreateInfo->attachmentCount, "Depth");
if (subpass.pDepthStencilAttachment->attachment < pCreateInfo->attachmentCount) {
skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts,
subpass.pDepthStencilAttachment->attachment, ATTACHMENT_DEPTH,
subpass.pDepthStencilAttachment->layout);
}
}
}
uint32_t last_sample_count_attachment = VK_ATTACHMENT_UNUSED;
for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
auto const &attachment_ref = subpass.pColorAttachments[j];
skip |= ValidateAttachmentIndex(rp_version, attachment_ref.attachment, pCreateInfo->attachmentCount, "Color");
if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED && attachment_ref.attachment < pCreateInfo->attachmentCount) {
skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment_ref.attachment,
ATTACHMENT_COLOR, attachment_ref.layout);
VkSampleCountFlagBits current_sample_count = pCreateInfo->pAttachments[attachment_ref.attachment].samples;
if (last_sample_count_attachment != VK_ATTACHMENT_UNUSED) {
VkSampleCountFlagBits last_sample_count =
pCreateInfo->pAttachments[subpass.pColorAttachments[last_sample_count_attachment].attachment].samples;
if (current_sample_count != last_sample_count) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pColorAttachments-03069"
: "VUID-VkSubpassDescription-pColorAttachments-01417";
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Subpass %u attempts to render to color attachments with inconsistent sample counts."
"Color attachment ref %u has sample count %s, whereas previous color attachment ref %u has "
"sample count %s.",
function_name, i, j, string_VkSampleCountFlagBits(current_sample_count),
last_sample_count_attachment, string_VkSampleCountFlagBits(last_sample_count));
}
}
last_sample_count_attachment = j;
if (subpass_performs_resolve && current_sample_count == VK_SAMPLE_COUNT_1_BIT) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pResolveAttachments-03066"
: "VUID-VkSubpassDescription-pResolveAttachments-00848";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Subpass %u requests multisample resolve from attachment %u which has "
"VK_SAMPLE_COUNT_1_BIT.",
function_name, i, attachment_ref.attachment);
}
if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED &&
subpass.pDepthStencilAttachment->attachment < pCreateInfo->attachmentCount) {
const auto depth_stencil_sample_count =
pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].samples;
if (device_extensions.vk_amd_mixed_attachment_samples) {
if (pCreateInfo->pAttachments[attachment_ref.attachment].samples > depth_stencil_sample_count) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pColorAttachments-03070"
: "VUID-VkSubpassDescription-pColorAttachments-01506";
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Subpass %u pColorAttachments[%u] has %s which is larger than "
"depth/stencil attachment %s.",
function_name, i, j,
string_VkSampleCountFlagBits(pCreateInfo->pAttachments[attachment_ref.attachment].samples),
string_VkSampleCountFlagBits(depth_stencil_sample_count));
break;
}
}
if (!device_extensions.vk_amd_mixed_attachment_samples && !device_extensions.vk_nv_framebuffer_mixed_samples &&
current_sample_count != depth_stencil_sample_count) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pDepthStencilAttachment-03071"
: "VUID-VkSubpassDescription-pDepthStencilAttachment-01418";
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Subpass %u attempts to render to use a depth/stencil attachment with sample count that differs "
"from color attachment %u."
"The depth attachment ref has sample count %s, whereas color attachment ref %u has sample count %s.",
function_name, i, j, string_VkSampleCountFlagBits(depth_stencil_sample_count), j,
string_VkSampleCountFlagBits(current_sample_count));
break;
}
}
}
if (subpass_performs_resolve && subpass.pResolveAttachments[j].attachment != VK_ATTACHMENT_UNUSED &&
subpass.pResolveAttachments[j].attachment < pCreateInfo->attachmentCount) {
if (attachment_ref.attachment == VK_ATTACHMENT_UNUSED) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pResolveAttachments-03065"
: "VUID-VkSubpassDescription-pResolveAttachments-00847";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Subpass %u requests multisample resolve from attachment %u which has "
"attachment=VK_ATTACHMENT_UNUSED.",
function_name, i, attachment_ref.attachment);
} else {
const auto &color_desc = pCreateInfo->pAttachments[attachment_ref.attachment];
const auto &resolve_desc = pCreateInfo->pAttachments[subpass.pResolveAttachments[j].attachment];
if (color_desc.format != resolve_desc.format) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pResolveAttachments-03068"
: "VUID-VkSubpassDescription-pResolveAttachments-00850";
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: Subpass %u pColorAttachments[%u] resolves to an attachment with a "
"different format. color format: %u, resolve format: %u.",
function_name, i, j, color_desc.format, resolve_desc.format);
}
}
}
}
}
return skip;
}
static void MarkAttachmentFirstUse(RENDER_PASS_STATE *render_pass, uint32_t index, bool is_read) {
if (index == VK_ATTACHMENT_UNUSED) return;
if (!render_pass->attachment_first_read.count(index)) render_pass->attachment_first_read[index] = is_read;
}
bool CoreChecks::ValidateCreateRenderPass(VkDevice device, RenderPassCreateVersion rp_version,
const VkRenderPassCreateInfo2KHR *pCreateInfo, RENDER_PASS_STATE *render_pass) {
bool skip = false;
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
const char *vuid;
const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()";
// TODO: As part of wrapping up the mem_tracker/core_validation merge the following routine should be consolidated with
// ValidateLayouts.
skip |= ValidateRenderpassAttachmentUsage(rp_version, pCreateInfo);
render_pass->renderPass = VK_NULL_HANDLE;
skip |= ValidateRenderPassDAG(rp_version, pCreateInfo, render_pass);
// Validate multiview correlation and view masks
bool viewMaskZero = false;
bool viewMaskNonZero = false;
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i];
if (subpass.viewMask != 0) {
viewMaskNonZero = true;
} else {
viewMaskZero = true;
}
if ((subpass.flags & VK_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX) != 0 &&
(subpass.flags & VK_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX) == 0) {
vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-flags-03076" : "VUID-VkSubpassDescription-flags-00856";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: The flags parameter of subpass description %u includes "
"VK_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX but does not also include "
"VK_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX.",
function_name, i);
}
}
if (rp_version == RENDER_PASS_VERSION_2) {
if (viewMaskNonZero && viewMaskZero) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkRenderPassCreateInfo2KHR-viewMask-03058",
"%s: Some view masks are non-zero whilst others are zero.", function_name);
}
if (viewMaskZero && pCreateInfo->correlatedViewMaskCount != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkRenderPassCreateInfo2KHR-viewMask-03057",
"%s: Multiview is not enabled but correlation masks are still provided", function_name);
}
}
uint32_t aggregated_cvms = 0;
for (uint32_t i = 0; i < pCreateInfo->correlatedViewMaskCount; ++i) {
if (aggregated_cvms & pCreateInfo->pCorrelatedViewMasks[i]) {
vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-pCorrelatedViewMasks-03056"
: "VUID-VkRenderPassMultiviewCreateInfo-pCorrelationMasks-00841";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: pCorrelatedViewMasks[%u] contains a previously appearing view bit.", function_name, i);
}
aggregated_cvms |= pCreateInfo->pCorrelatedViewMasks[i];
}
for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) {
auto const &dependency = pCreateInfo->pDependencies[i];
if (rp_version == RENDER_PASS_VERSION_2) {
skip |= ValidateStageMaskGsTsEnables(
dependency.srcStageMask, function_name, "VUID-VkSubpassDependency2KHR-srcStageMask-03080",
"VUID-VkSubpassDependency2KHR-srcStageMask-03082", "VUID-VkSubpassDependency2KHR-srcStageMask-02103",
"VUID-VkSubpassDependency2KHR-srcStageMask-02104");
skip |= ValidateStageMaskGsTsEnables(
dependency.dstStageMask, function_name, "VUID-VkSubpassDependency2KHR-dstStageMask-03081",
"VUID-VkSubpassDependency2KHR-dstStageMask-03083", "VUID-VkSubpassDependency2KHR-dstStageMask-02105",
"VUID-VkSubpassDependency2KHR-dstStageMask-02106");
} else {
skip |= ValidateStageMaskGsTsEnables(
dependency.srcStageMask, function_name, "VUID-VkSubpassDependency-srcStageMask-00860",
"VUID-VkSubpassDependency-srcStageMask-00862", "VUID-VkSubpassDependency-srcStageMask-02099",
"VUID-VkSubpassDependency-srcStageMask-02100");
skip |= ValidateStageMaskGsTsEnables(
dependency.dstStageMask, function_name, "VUID-VkSubpassDependency-dstStageMask-00861",
"VUID-VkSubpassDependency-dstStageMask-00863", "VUID-VkSubpassDependency-dstStageMask-02101",
"VUID-VkSubpassDependency-dstStageMask-02102");
}
if (!ValidateAccessMaskPipelineStage(device_extensions, dependency.srcAccessMask, dependency.srcStageMask)) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcAccessMask-03088" : "VUID-VkSubpassDependency-srcAccessMask-00868";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: pDependencies[%u].srcAccessMask (0x%" PRIx32 ") is not supported by srcStageMask (0x%" PRIx32 ").",
function_name, i, dependency.srcAccessMask, dependency.srcStageMask);
}
if (!ValidateAccessMaskPipelineStage(device_extensions, dependency.dstAccessMask, dependency.dstStageMask)) {
vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-dstAccessMask-03089" : "VUID-VkSubpassDependency-dstAccessMask-00869";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid,
"%s: pDependencies[%u].dstAccessMask (0x%" PRIx32 ") is not supported by dstStageMask (0x%" PRIx32 ").",
function_name, i, dependency.dstAccessMask, dependency.dstStageMask);
}
}
if (!skip) {
skip |= ValidateLayouts(rp_version, device, pCreateInfo);
}
return skip;
}
bool CoreChecks::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass) {
bool skip = false;
// Handle extension structs from KHR_multiview and KHR_maintenance2 that can only be validated for RP1 (indices out of bounds)
const VkRenderPassMultiviewCreateInfo *pMultiviewInfo = lvl_find_in_chain<VkRenderPassMultiviewCreateInfo>(pCreateInfo->pNext);
if (pMultiviewInfo) {
if (pMultiviewInfo->subpassCount && pMultiviewInfo->subpassCount != pCreateInfo->subpassCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkRenderPassCreateInfo-pNext-01928",
"Subpass count is %u but multiview info has a subpass count of %u.", pCreateInfo->subpassCount,
pMultiviewInfo->subpassCount);
} else if (pMultiviewInfo->dependencyCount && pMultiviewInfo->dependencyCount != pCreateInfo->dependencyCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkRenderPassCreateInfo-pNext-01929",
"Dependency count is %u but multiview info has a dependency count of %u.", pCreateInfo->dependencyCount,
pMultiviewInfo->dependencyCount);
}
}
const VkRenderPassInputAttachmentAspectCreateInfo *pInputAttachmentAspectInfo =
lvl_find_in_chain<VkRenderPassInputAttachmentAspectCreateInfo>(pCreateInfo->pNext);
if (pInputAttachmentAspectInfo) {
for (uint32_t i = 0; i < pInputAttachmentAspectInfo->aspectReferenceCount; ++i) {
uint32_t subpass = pInputAttachmentAspectInfo->pAspectReferences[i].subpass;
uint32_t attachment = pInputAttachmentAspectInfo->pAspectReferences[i].inputAttachmentIndex;
if (subpass >= pCreateInfo->subpassCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkRenderPassCreateInfo-pNext-01926",
"Subpass index %u specified by input attachment aspect info %u is greater than the subpass "
"count of %u for this render pass.",
subpass, i, pCreateInfo->subpassCount);
} else if (pCreateInfo->pSubpasses && attachment >= pCreateInfo->pSubpasses[subpass].inputAttachmentCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkRenderPassCreateInfo-pNext-01927",
"Input attachment index %u specified by input attachment aspect info %u is greater than the "
"input attachment count of %u for this subpass.",
attachment, i, pCreateInfo->pSubpasses[subpass].inputAttachmentCount);
}
}
}
if (!skip) {
auto render_pass = std::unique_ptr<RENDER_PASS_STATE>(new RENDER_PASS_STATE(pCreateInfo));
skip |= ValidateCreateRenderPass(device, RENDER_PASS_VERSION_1, render_pass->createInfo.ptr(), render_pass.get());
}
return skip;
}
void CoreChecks::RecordCreateRenderPassState(RenderPassCreateVersion rp_version, std::shared_ptr<RENDER_PASS_STATE> &render_pass,
VkRenderPass *pRenderPass) {
render_pass->renderPass = *pRenderPass;
auto create_info = render_pass->createInfo.ptr();
RecordRenderPassDAG(RENDER_PASS_VERSION_1, create_info, render_pass.get());
for (uint32_t i = 0; i < create_info->subpassCount; ++i) {
const VkSubpassDescription2KHR &subpass = create_info->pSubpasses[i];
for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) {
MarkAttachmentFirstUse(render_pass.get(), subpass.pColorAttachments[j].attachment, false);
// resolve attachments are considered to be written
if (subpass.pResolveAttachments) {
MarkAttachmentFirstUse(render_pass.get(), subpass.pResolveAttachments[j].attachment, false);
}
}
if (subpass.pDepthStencilAttachment) {
MarkAttachmentFirstUse(render_pass.get(), subpass.pDepthStencilAttachment->attachment, false);
}
for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) {
MarkAttachmentFirstUse(render_pass.get(), subpass.pInputAttachments[j].attachment, true);
}
}
// Even though render_pass is an rvalue-ref parameter, still must move s.t. move assignment is invoked.
renderPassMap[*pRenderPass] = std::move(render_pass);
}
// Style note:
// Use of rvalue reference exceeds reccommended usage of rvalue refs in google style guide, but intentionally forces caller to move
// or copy. This is clearer than passing a pointer to shared_ptr and avoids the atomic increment/decrement of shared_ptr copy
// construction or assignment.
void CoreChecks::PostCallRecordCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass,
VkResult result) {
if (VK_SUCCESS != result) return;
auto render_pass_state = std::make_shared<RENDER_PASS_STATE>(pCreateInfo);
RecordCreateRenderPassState(RENDER_PASS_VERSION_1, render_pass_state, pRenderPass);
}
void CoreChecks::PostCallRecordCreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2KHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass,
VkResult result) {
if (VK_SUCCESS != result) return;
auto render_pass_state = std::make_shared<RENDER_PASS_STATE>(pCreateInfo);
RecordCreateRenderPassState(RENDER_PASS_VERSION_2, render_pass_state, pRenderPass);
}
static bool ValidateDepthStencilResolve(const debug_report_data *report_data,
const VkPhysicalDeviceDepthStencilResolvePropertiesKHR &depth_stencil_resolve_props,
const VkRenderPassCreateInfo2KHR *pCreateInfo) {
bool skip = false;
// If the pNext list of VkSubpassDescription2KHR includes a VkSubpassDescriptionDepthStencilResolveKHR structure,
// then that structure describes depth/stencil resolve operations for the subpass.
for (uint32_t i = 0; i < pCreateInfo->subpassCount; i++) {
VkSubpassDescription2KHR subpass = pCreateInfo->pSubpasses[i];
const auto *resolve = lvl_find_in_chain<VkSubpassDescriptionDepthStencilResolveKHR>(subpass.pNext);
if (resolve == nullptr) {
continue;
}
if (resolve->pDepthStencilResolveAttachment != nullptr &&
resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) {
if (subpass.pDepthStencilAttachment->attachment == VK_ATTACHMENT_UNUSED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03177",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with resolve attachment %u, but pDepthStencilAttachment=VK_ATTACHMENT_UNUSED.",
i, resolve->pDepthStencilResolveAttachment->attachment);
}
if (resolve->depthResolveMode == VK_RESOLVE_MODE_NONE_KHR && resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE_KHR) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03178",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with resolve attachment %u, but both depth and stencil resolve modes are "
"VK_RESOLVE_MODE_NONE_KHR.",
i, resolve->pDepthStencilResolveAttachment->attachment);
}
}
if (resolve->pDepthStencilResolveAttachment != nullptr &&
pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].samples == VK_SAMPLE_COUNT_1_BIT) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03179",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with resolve attachment %u. However pDepthStencilAttachment has sample count=VK_SAMPLE_COUNT_1_BIT.",
i, resolve->pDepthStencilResolveAttachment->attachment);
}
if (pCreateInfo->pAttachments[resolve->pDepthStencilResolveAttachment->attachment].samples != VK_SAMPLE_COUNT_1_BIT) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03180",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with resolve attachment %u which has sample count=VK_SAMPLE_COUNT_1_BIT.",
i, resolve->pDepthStencilResolveAttachment->attachment);
}
VkFormat pDepthStencilAttachmentFormat = pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].format;
VkFormat pDepthStencilResolveAttachmentFormat =
pCreateInfo->pAttachments[resolve->pDepthStencilResolveAttachment->attachment].format;
if ((FormatDepthSize(pDepthStencilAttachmentFormat) != FormatDepthSize(pDepthStencilResolveAttachmentFormat)) ||
(FormatDepthNumericalType(pDepthStencilAttachmentFormat) !=
FormatDepthNumericalType(pDepthStencilResolveAttachmentFormat))) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03181",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with resolve attachment %u which has a depth component (size %u). The depth component "
"of pDepthStencilAttachment must have the same number of bits (currently %u) and the same numerical type.",
i, resolve->pDepthStencilResolveAttachment->attachment,
FormatDepthSize(pDepthStencilResolveAttachmentFormat), FormatDepthSize(pDepthStencilAttachmentFormat));
}
if ((FormatStencilSize(pDepthStencilAttachmentFormat) != FormatStencilSize(pDepthStencilResolveAttachmentFormat)) ||
(FormatStencilNumericalType(pDepthStencilAttachmentFormat) !=
FormatStencilNumericalType(pDepthStencilResolveAttachmentFormat))) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03182",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with resolve attachment %u which has a stencil component (size %u). The stencil component "
"of pDepthStencilAttachment must have the same number of bits (currently %u) and the same numerical type.",
i, resolve->pDepthStencilResolveAttachment->attachment,
FormatStencilSize(pDepthStencilResolveAttachmentFormat), FormatStencilSize(pDepthStencilAttachmentFormat));
}
if (!(resolve->depthResolveMode == VK_RESOLVE_MODE_NONE_KHR ||
resolve->depthResolveMode & depth_stencil_resolve_props.supportedDepthResolveModes)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-depthResolveMode-03183",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with invalid depthResolveMode=%u.",
i, resolve->depthResolveMode);
}
if (!(resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE_KHR ||
resolve->stencilResolveMode & depth_stencil_resolve_props.supportedStencilResolveModes)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-stencilResolveMode-03184",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure with invalid stencilResolveMode=%u.",
i, resolve->stencilResolveMode);
}
if (FormatIsDepthAndStencil(pDepthStencilResolveAttachmentFormat) &&
depth_stencil_resolve_props.independentResolve == VK_FALSE &&
depth_stencil_resolve_props.independentResolveNone == VK_FALSE &&
!(resolve->depthResolveMode == resolve->stencilResolveMode)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03185",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure. The values of depthResolveMode (%u) and stencilResolveMode (%u) must be identical.",
i, resolve->depthResolveMode, resolve->stencilResolveMode);
}
if (FormatIsDepthAndStencil(pDepthStencilResolveAttachmentFormat) &&
depth_stencil_resolve_props.independentResolve == VK_FALSE &&
depth_stencil_resolve_props.independentResolveNone == VK_TRUE &&
!(resolve->depthResolveMode == resolve->stencilResolveMode || resolve->depthResolveMode == VK_RESOLVE_MODE_NONE_KHR ||
resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE_KHR)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03186",
"vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR "
"structure. The values of depthResolveMode (%u) and stencilResolveMode (%u) must be identical, or "
"one of them must be %u.",
i, resolve->depthResolveMode, resolve->stencilResolveMode, VK_RESOLVE_MODE_NONE_KHR);
}
}
return skip;
}
bool CoreChecks::PreCallValidateCreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2KHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass) {
bool skip = false;
if (device_extensions.vk_khr_depth_stencil_resolve) {
skip |= ValidateDepthStencilResolve(report_data, phys_dev_ext_props.depth_stencil_resolve_props, pCreateInfo);
}
auto render_pass = std::make_shared<RENDER_PASS_STATE>(pCreateInfo);
skip |= ValidateCreateRenderPass(device, RENDER_PASS_VERSION_2, render_pass->createInfo.ptr(), render_pass.get());
return skip;
}
bool CoreChecks::ValidatePrimaryCommandBuffer(const CMD_BUFFER_STATE *pCB, char const *cmd_name, const char *error_code) {
bool skip = false;
if (pCB->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), error_code, "Cannot execute command %s on a secondary command buffer.",
cmd_name);
}
return skip;
}
bool CoreChecks::VerifyRenderAreaBounds(const VkRenderPassBeginInfo *pRenderPassBegin) {
bool skip = false;
const safe_VkFramebufferCreateInfo *pFramebufferInfo = &GetFramebufferState(pRenderPassBegin->framebuffer)->createInfo;
if (pRenderPassBegin->renderArea.offset.x < 0 ||
(pRenderPassBegin->renderArea.offset.x + pRenderPassBegin->renderArea.extent.width) > pFramebufferInfo->width ||
pRenderPassBegin->renderArea.offset.y < 0 ||
(pRenderPassBegin->renderArea.offset.y + pRenderPassBegin->renderArea.extent.height) > pFramebufferInfo->height) {
skip |= static_cast<bool>(log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_DrawState_InvalidRenderArea,
"Cannot execute a render pass with renderArea not within the bound of the framebuffer. RenderArea: x %d, y %d, width "
"%d, height %d. Framebuffer: width %d, height %d.",
pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y, pRenderPassBegin->renderArea.extent.width,
pRenderPassBegin->renderArea.extent.height, pFramebufferInfo->width, pFramebufferInfo->height));
}
return skip;
}
// If this is a stencil format, make sure the stencil[Load|Store]Op flag is checked, while if it is a depth/color attachment the
// [load|store]Op flag must be checked
// TODO: The memory valid flag in DEVICE_MEMORY_STATE should probably be split to track the validity of stencil memory separately.
template <typename T>
static bool FormatSpecificLoadAndStoreOpSettings(VkFormat format, T color_depth_op, T stencil_op, T op) {
if (color_depth_op != op && stencil_op != op) {
return false;
}
bool check_color_depth_load_op = !FormatIsStencilOnly(format);
bool check_stencil_load_op = FormatIsDepthAndStencil(format) || !check_color_depth_load_op;
return ((check_color_depth_load_op && (color_depth_op == op)) || (check_stencil_load_op && (stencil_op == op)));
}
bool CoreChecks::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
const VkRenderPassBeginInfo *pRenderPassBegin) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
auto render_pass_state = pRenderPassBegin ? GetRenderPassState(pRenderPassBegin->renderPass) : nullptr;
auto framebuffer = pRenderPassBegin ? GetFramebufferState(pRenderPassBegin->framebuffer) : nullptr;
bool skip = false;
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
const char *vuid;
const char *const function_name = use_rp2 ? "vkCmdBeginRenderPass2KHR()" : "vkCmdBeginRenderPass()";
if (render_pass_state) {
uint32_t clear_op_size = 0; // Make sure pClearValues is at least as large as last LOAD_OP_CLEAR
// Handle extension struct from EXT_sample_locations
const VkRenderPassSampleLocationsBeginInfoEXT *pSampleLocationsBeginInfo =
lvl_find_in_chain<VkRenderPassSampleLocationsBeginInfoEXT>(pRenderPassBegin->pNext);
if (pSampleLocationsBeginInfo) {
for (uint32_t i = 0; i < pSampleLocationsBeginInfo->attachmentInitialSampleLocationsCount; ++i) {
if (pSampleLocationsBeginInfo->pAttachmentInitialSampleLocations[i].attachmentIndex >=
render_pass_state->createInfo.attachmentCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkAttachmentSampleLocationsEXT-attachmentIndex-01531",
"Attachment index %u specified by attachment sample locations %u is greater than the "
"attachment count of %u for the render pass being begun.",
pSampleLocationsBeginInfo->pAttachmentInitialSampleLocations[i].attachmentIndex, i,
render_pass_state->createInfo.attachmentCount);
}
}
for (uint32_t i = 0; i < pSampleLocationsBeginInfo->postSubpassSampleLocationsCount; ++i) {
if (pSampleLocationsBeginInfo->pPostSubpassSampleLocations[i].subpassIndex >=
render_pass_state->createInfo.subpassCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkSubpassSampleLocationsEXT-subpassIndex-01532",
"Subpass index %u specified by subpass sample locations %u is greater than the subpass count "
"of %u for the render pass being begun.",
pSampleLocationsBeginInfo->pPostSubpassSampleLocations[i].subpassIndex, i,
render_pass_state->createInfo.subpassCount);
}
}
}
for (uint32_t i = 0; i < render_pass_state->createInfo.attachmentCount; ++i) {
auto pAttachment = &render_pass_state->createInfo.pAttachments[i];
if (FormatSpecificLoadAndStoreOpSettings(pAttachment->format, pAttachment->loadOp, pAttachment->stencilLoadOp,
VK_ATTACHMENT_LOAD_OP_CLEAR)) {
clear_op_size = static_cast<uint32_t>(i) + 1;
}
}
if (clear_op_size > pRenderPassBegin->clearValueCount) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(render_pass_state->renderPass), "VUID-VkRenderPassBeginInfo-clearValueCount-00902",
"In %s the VkRenderPassBeginInfo struct has a clearValueCount of %u but there "
"must be at least %u entries in pClearValues array to account for the highest index attachment in "
"renderPass %s that uses VK_ATTACHMENT_LOAD_OP_CLEAR is %u. Note that the pClearValues array is indexed by "
"attachment number so even if some pClearValues entries between 0 and %u correspond to attachments "
"that aren't cleared they will be ignored.",
function_name, pRenderPassBegin->clearValueCount, clear_op_size,
report_data->FormatHandle(render_pass_state->renderPass).c_str(), clear_op_size, clear_op_size - 1);
}
skip |= VerifyRenderAreaBounds(pRenderPassBegin);
skip |= VerifyFramebufferAndRenderPassLayouts(rp_version, cb_state, pRenderPassBegin,
GetFramebufferState(pRenderPassBegin->framebuffer));
if (framebuffer->rp_state->renderPass != render_pass_state->renderPass) {
skip |= ValidateRenderPassCompatibility("render pass", render_pass_state, "framebuffer", framebuffer->rp_state.get(),
function_name, "VUID-VkRenderPassBeginInfo-renderPass-00904");
}
vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-renderpass" : "VUID-vkCmdBeginRenderPass-renderpass";
skip |= InsideRenderPass(cb_state, function_name, vuid);
skip |= ValidateDependencies(framebuffer, render_pass_state);
vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-bufferlevel" : "VUID-vkCmdBeginRenderPass-bufferlevel";
skip |= ValidatePrimaryCommandBuffer(cb_state, function_name, vuid);
vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-commandBuffer-cmdpool" : "VUID-vkCmdBeginRenderPass-commandBuffer-cmdpool";
skip |= ValidateCmdQueueFlags(cb_state, function_name, VK_QUEUE_GRAPHICS_BIT, vuid);
const CMD_TYPE cmd_type = use_rp2 ? CMD_BEGINRENDERPASS2KHR : CMD_BEGINRENDERPASS;
skip |= ValidateCmd(cb_state, cmd_type, function_name);
}
auto chained_device_group_struct = lvl_find_in_chain<VkDeviceGroupRenderPassBeginInfo>(pRenderPassBegin->pNext);
if (chained_device_group_struct) {
skip |= ValidateDeviceMaskToPhysicalDeviceCount(
chained_device_group_struct->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(pRenderPassBegin->renderPass), "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00905");
skip |= ValidateDeviceMaskToZero(chained_device_group_struct->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(pRenderPassBegin->renderPass),
"VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00906");
skip |= ValidateDeviceMaskToCommandBuffer(
cb_state, chained_device_group_struct->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(pRenderPassBegin->renderPass), "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00907");
if (chained_device_group_struct->deviceRenderAreaCount != 0 &&
chained_device_group_struct->deviceRenderAreaCount != physical_device_count) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
HandleToUint64(pRenderPassBegin->renderPass),
"VUID-VkDeviceGroupRenderPassBeginInfo-deviceRenderAreaCount-00908",
"deviceRenderAreaCount[%" PRIu32 "] is invaild. Physical device count is %" PRIu32 ".",
chained_device_group_struct->deviceRenderAreaCount, physical_device_count);
}
}
return skip;
}
bool CoreChecks::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
VkSubpassContents contents) {
bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
return skip;
}
bool CoreChecks::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
const VkSubpassBeginInfoKHR *pSubpassBeginInfo) {
bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
return skip;
}
void CoreChecks::RecordCmdBeginRenderPassState(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
const VkSubpassContents contents) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
auto render_pass_state = pRenderPassBegin ? GetRenderPassState(pRenderPassBegin->renderPass) : nullptr;
auto framebuffer = pRenderPassBegin ? GetFramebufferState(pRenderPassBegin->framebuffer) : nullptr;
if (render_pass_state) {
cb_state->activeFramebuffer = pRenderPassBegin->framebuffer;
cb_state->activeRenderPass = render_pass_state;
// This is a shallow copy as that is all that is needed for now
cb_state->activeRenderPassBeginInfo = *pRenderPassBegin;
cb_state->activeSubpass = 0;
cb_state->activeSubpassContents = contents;
cb_state->framebuffers.insert(pRenderPassBegin->framebuffer);
// Connect this framebuffer and its children to this cmdBuffer
AddFramebufferBinding(cb_state, framebuffer);
// Connect this RP to cmdBuffer
AddCommandBufferBinding(&render_pass_state->cb_bindings,
{HandleToUint64(render_pass_state->renderPass), kVulkanObjectTypeRenderPass}, cb_state);
// transition attachments to the correct layouts for beginning of renderPass and first subpass
TransitionBeginRenderPassLayouts(cb_state, render_pass_state, framebuffer);
auto chained_device_group_struct = lvl_find_in_chain<VkDeviceGroupRenderPassBeginInfo>(pRenderPassBegin->pNext);
if (chained_device_group_struct) {
cb_state->active_render_pass_device_mask = chained_device_group_struct->deviceMask;
} else {
cb_state->active_render_pass_device_mask = cb_state->initial_device_mask;
}
}
}
void CoreChecks::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
VkSubpassContents contents) {
RecordCmdBeginRenderPassState(commandBuffer, pRenderPassBegin, contents);
}
void CoreChecks::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
const VkSubpassBeginInfoKHR *pSubpassBeginInfo) {
RecordCmdBeginRenderPassState(commandBuffer, pRenderPassBegin, pSubpassBeginInfo->contents);
}
bool CoreChecks::ValidateCmdNextSubpass(RenderPassCreateVersion rp_version, VkCommandBuffer commandBuffer) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = false;
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
const char *vuid;
const char *const function_name = use_rp2 ? "vkCmdNextSubpass2KHR()" : "vkCmdNextSubpass()";
vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-bufferlevel" : "VUID-vkCmdNextSubpass-bufferlevel";
skip |= ValidatePrimaryCommandBuffer(cb_state, function_name, vuid);
vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-commandBuffer-cmdpool" : "VUID-vkCmdNextSubpass-commandBuffer-cmdpool";
skip |= ValidateCmdQueueFlags(cb_state, function_name, VK_QUEUE_GRAPHICS_BIT, vuid);
const CMD_TYPE cmd_type = use_rp2 ? CMD_NEXTSUBPASS2KHR : CMD_NEXTSUBPASS;
skip |= ValidateCmd(cb_state, cmd_type, function_name);
vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-renderpass" : "VUID-vkCmdNextSubpass-renderpass";
skip |= OutsideRenderPass(cb_state, function_name, vuid);
auto subpassCount = cb_state->activeRenderPass->createInfo.subpassCount;
if (cb_state->activeSubpass == subpassCount - 1) {
vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-None-03102" : "VUID-vkCmdNextSubpass-None-00909";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), vuid, "%s: Attempted to advance beyond final subpass.", function_name);
}
return skip;
}
bool CoreChecks::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
return ValidateCmdNextSubpass(RENDER_PASS_VERSION_1, commandBuffer);
}
bool CoreChecks::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfoKHR *pSubpassBeginInfo,
const VkSubpassEndInfoKHR *pSubpassEndInfo) {
return ValidateCmdNextSubpass(RENDER_PASS_VERSION_2, commandBuffer);
}
void CoreChecks::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->activeSubpass++;
cb_state->activeSubpassContents = contents;
TransitionSubpassLayouts(cb_state, cb_state->activeRenderPass, cb_state->activeSubpass,
GetFramebufferState(cb_state->activeRenderPassBeginInfo.framebuffer));
}
void CoreChecks::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
RecordCmdNextSubpass(commandBuffer, contents);
}
void CoreChecks::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfoKHR *pSubpassBeginInfo,
const VkSubpassEndInfoKHR *pSubpassEndInfo) {
RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo->contents);
}
bool CoreChecks::ValidateCmdEndRenderPass(RenderPassCreateVersion rp_version, VkCommandBuffer commandBuffer) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = false;
const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2);
const char *vuid;
const char *const function_name = use_rp2 ? "vkCmdEndRenderPass2KHR()" : "vkCmdEndRenderPass()";
RENDER_PASS_STATE *rp_state = cb_state->activeRenderPass;
if (rp_state) {
if (cb_state->activeSubpass != rp_state->createInfo.subpassCount - 1) {
vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-None-03103" : "VUID-vkCmdEndRenderPass-None-00910";
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), vuid, "%s: Called before reaching final subpass.", function_name);
}
}
vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-renderpass" : "VUID-vkCmdEndRenderPass-renderpass";
skip |= OutsideRenderPass(cb_state, function_name, vuid);
vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-bufferlevel" : "VUID-vkCmdEndRenderPass-bufferlevel";
skip |= ValidatePrimaryCommandBuffer(cb_state, function_name, vuid);
vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-commandBuffer-cmdpool" : "VUID-vkCmdEndRenderPass-commandBuffer-cmdpool";
skip |= ValidateCmdQueueFlags(cb_state, function_name, VK_QUEUE_GRAPHICS_BIT, vuid);
const CMD_TYPE cmd_type = use_rp2 ? CMD_ENDRENDERPASS2KHR : CMD_ENDRENDERPASS;
skip |= ValidateCmd(cb_state, cmd_type, function_name);
return skip;
}
bool CoreChecks::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) {
bool skip = ValidateCmdEndRenderPass(RENDER_PASS_VERSION_1, commandBuffer);
return skip;
}
bool CoreChecks::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassEndInfo) {
bool skip = ValidateCmdEndRenderPass(RENDER_PASS_VERSION_2, commandBuffer);
return skip;
}
void CoreChecks::RecordCmdEndRenderPassState(VkCommandBuffer commandBuffer) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
FRAMEBUFFER_STATE *framebuffer = GetFramebufferState(cb_state->activeFramebuffer);
TransitionFinalSubpassLayouts(cb_state, &cb_state->activeRenderPassBeginInfo, framebuffer);
cb_state->activeRenderPass = nullptr;
cb_state->activeSubpass = 0;
cb_state->activeFramebuffer = VK_NULL_HANDLE;
}
void CoreChecks::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) { RecordCmdEndRenderPassState(commandBuffer); }
void CoreChecks::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassEndInfo) {
RecordCmdEndRenderPassState(commandBuffer);
}
bool CoreChecks::ValidateFramebuffer(VkCommandBuffer primaryBuffer, const CMD_BUFFER_STATE *pCB, VkCommandBuffer secondaryBuffer,
const CMD_BUFFER_STATE *pSubCB, const char *caller) {
bool skip = false;
if (!pSubCB->beginInfo.pInheritanceInfo) {
return skip;
}
VkFramebuffer primary_fb = pCB->activeFramebuffer;
VkFramebuffer secondary_fb = pSubCB->beginInfo.pInheritanceInfo->framebuffer;
if (secondary_fb != VK_NULL_HANDLE) {
if (primary_fb != secondary_fb) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(primaryBuffer), "VUID-vkCmdExecuteCommands-pCommandBuffers-00099",
"vkCmdExecuteCommands() called w/ invalid secondary command buffer %s which has a framebuffer %s"
" that is not the same as the primary command buffer's current active framebuffer %s.",
report_data->FormatHandle(secondaryBuffer).c_str(), report_data->FormatHandle(secondary_fb).c_str(),
report_data->FormatHandle(primary_fb).c_str());
}
auto fb = GetFramebufferState(secondary_fb);
if (!fb) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(primaryBuffer), kVUID_Core_DrawState_InvalidSecondaryCommandBuffer,
"vkCmdExecuteCommands() called w/ invalid Cmd Buffer %s which has invalid framebuffer %s.",
report_data->FormatHandle(secondaryBuffer).c_str(), report_data->FormatHandle(secondary_fb).c_str());
return skip;
}
}
return skip;
}
bool CoreChecks::ValidateSecondaryCommandBufferState(CMD_BUFFER_STATE *pCB, CMD_BUFFER_STATE *pSubCB) {
bool skip = false;
unordered_set<int> activeTypes;
if (!disabled.query_validation) {
for (auto queryObject : pCB->activeQueries) {
auto query_pool_state = GetQueryPoolState(queryObject.pool);
if (query_pool_state) {
if (query_pool_state->createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS &&
pSubCB->beginInfo.pInheritanceInfo) {
VkQueryPipelineStatisticFlags cmdBufStatistics = pSubCB->beginInfo.pInheritanceInfo->pipelineStatistics;
if ((cmdBufStatistics & query_pool_state->createInfo.pipelineStatistics) != cmdBufStatistics) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), "VUID-vkCmdExecuteCommands-commandBuffer-00104",
"vkCmdExecuteCommands() called w/ invalid Cmd Buffer %s which has invalid active query pool %s"
". Pipeline statistics is being queried so the command buffer must have all bits set on the queryPool.",
report_data->FormatHandle(pCB->commandBuffer).c_str(),
report_data->FormatHandle(queryObject.pool).c_str());
}
}
activeTypes.insert(query_pool_state->createInfo.queryType);
}
}
for (auto queryObject : pSubCB->startedQueries) {
auto query_pool_state = GetQueryPoolState(queryObject.pool);
if (query_pool_state && activeTypes.count(query_pool_state->createInfo.queryType)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidSecondaryCommandBuffer,
"vkCmdExecuteCommands() called w/ invalid Cmd Buffer %s which has invalid active query pool %s"
" of type %d but a query of that type has been started on secondary Cmd Buffer %s.",
report_data->FormatHandle(pCB->commandBuffer).c_str(),
report_data->FormatHandle(queryObject.pool).c_str(), query_pool_state->createInfo.queryType,
report_data->FormatHandle(pSubCB->commandBuffer).c_str());
}
}
}
auto primary_pool = GetCommandPoolState(pCB->createInfo.commandPool);
auto secondary_pool = GetCommandPoolState(pSubCB->createInfo.commandPool);
if (primary_pool && secondary_pool && (primary_pool->queueFamilyIndex != secondary_pool->queueFamilyIndex)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pSubCB->commandBuffer), kVUID_Core_DrawState_InvalidQueueFamily,
"vkCmdExecuteCommands(): Primary command buffer %s created in queue family %d has secondary command buffer "
"%s created in queue family %d.",
report_data->FormatHandle(pCB->commandBuffer).c_str(), primary_pool->queueFamilyIndex,
report_data->FormatHandle(pSubCB->commandBuffer).c_str(), secondary_pool->queueFamilyIndex);
}
return skip;
}
bool CoreChecks::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBuffersCount,
const VkCommandBuffer *pCommandBuffers) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
bool skip = false;
CMD_BUFFER_STATE *sub_cb_state = NULL;
std::unordered_set<CMD_BUFFER_STATE *> linked_command_buffers = cb_state->linkedCommandBuffers;
for (uint32_t i = 0; i < commandBuffersCount; i++) {
sub_cb_state = GetCBState(pCommandBuffers[i]);
assert(sub_cb_state);
if (VK_COMMAND_BUFFER_LEVEL_PRIMARY == sub_cb_state->createInfo.level) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCommandBuffers[i]), "VUID-vkCmdExecuteCommands-pCommandBuffers-00088",
"vkCmdExecuteCommands() called w/ Primary Cmd Buffer %s in element %u of pCommandBuffers array. All "
"cmd buffers in pCommandBuffers array must be secondary.",
report_data->FormatHandle(pCommandBuffers[i]).c_str(), i);
} else if (VK_COMMAND_BUFFER_LEVEL_SECONDARY == sub_cb_state->createInfo.level) {
if (sub_cb_state->beginInfo.pInheritanceInfo != nullptr) {
auto secondary_rp_state = GetRenderPassState(sub_cb_state->beginInfo.pInheritanceInfo->renderPass);
if (cb_state->activeRenderPass &&
!(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCommandBuffers[i]), "VUID-vkCmdExecuteCommands-pCommandBuffers-00096",
"vkCmdExecuteCommands(): Secondary Command Buffer (%s) is executed within a render pass (%s) "
"instance scope, but the Secondary Command Buffer does not have the "
"VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT set in VkCommandBufferBeginInfo::flags when "
"the vkBeginCommandBuffer() was called.",
report_data->FormatHandle(pCommandBuffers[i]).c_str(),
report_data->FormatHandle(cb_state->activeRenderPass->renderPass).c_str());
} else if (!cb_state->activeRenderPass &&
(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCommandBuffers[i]), "VUID-vkCmdExecuteCommands-pCommandBuffers-00100",
"vkCmdExecuteCommands(): Secondary Command Buffer (%s) is executed outside a render pass "
"instance scope, but the Secondary Command Buffer does have the "
"VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT set in VkCommandBufferBeginInfo::flags when "
"the vkBeginCommandBuffer() was called.",
report_data->FormatHandle(pCommandBuffers[i]).c_str());
} else if (cb_state->activeRenderPass &&
(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
// Make sure render pass is compatible with parent command buffer pass if has continue
if (cb_state->activeRenderPass->renderPass != secondary_rp_state->renderPass) {
skip |= ValidateRenderPassCompatibility(
"primary command buffer", cb_state->activeRenderPass, "secondary command buffer", secondary_rp_state,
"vkCmdExecuteCommands()", "VUID-vkCmdExecuteCommands-pInheritanceInfo-00098");
}
// If framebuffer for secondary CB is not NULL, then it must match active FB from primaryCB
skip |=
ValidateFramebuffer(commandBuffer, cb_state, pCommandBuffers[i], sub_cb_state, "vkCmdExecuteCommands()");
if (!sub_cb_state->cmd_execute_commands_functions.empty()) {
// Inherit primary's activeFramebuffer and while running validate functions
for (auto &function : sub_cb_state->cmd_execute_commands_functions) {
skip |= function(cb_state, cb_state->activeFramebuffer);
}
}
}
}
}
// TODO(mlentine): Move more logic into this method
skip |= ValidateSecondaryCommandBufferState(cb_state, sub_cb_state);
skip |= ValidateCommandBufferState(sub_cb_state, "vkCmdExecuteCommands()", 0,
"VUID-vkCmdExecuteCommands-pCommandBuffers-00089");
if (!(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) {
if (sub_cb_state->in_use.load() || linked_command_buffers.count(sub_cb_state)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdExecuteCommands-pCommandBuffers-00090",
"Attempt to simultaneously execute command buffer %s without VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set!",
report_data->FormatHandle(cb_state->commandBuffer).c_str());
}
if (cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
// Warn that non-simultaneous secondary cmd buffer renders primary non-simultaneous
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCommandBuffers[i]), kVUID_Core_DrawState_InvalidCommandBufferSimultaneousUse,
"vkCmdExecuteCommands(): Secondary Command Buffer (%s) does not have "
"VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set and will cause primary "
"command buffer (%s) to be treated as if it does not have "
"VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set, even though it does.",
report_data->FormatHandle(pCommandBuffers[i]).c_str(),
report_data->FormatHandle(cb_state->commandBuffer).c_str());
}
}
if (!cb_state->activeQueries.empty() && !enabled_features.core.inheritedQueries) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCommandBuffers[i]), "VUID-vkCmdExecuteCommands-commandBuffer-00101",
"vkCmdExecuteCommands(): Secondary Command Buffer (%s) cannot be submitted with a query in flight and "
"inherited queries not supported on this device.",
report_data->FormatHandle(pCommandBuffers[i]).c_str());
}
// Validate initial layout uses vs. the primary cmd buffer state
// Novel Valid usage: "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001"
// initial layout usage of secondary command buffers resources must match parent command buffer
const auto *const_cb_state = static_cast<const CMD_BUFFER_STATE *>(cb_state);
for (const auto &sub_layout_map_entry : sub_cb_state->image_layout_map) {
const auto image = sub_layout_map_entry.first;
const auto *image_state = GetImageState(image);
if (!image_state) continue; // Can't set layouts of a dead image
const auto *cb_subres_map = GetImageSubresourceLayoutMap(const_cb_state, image);
// Const getter can be null in which case we have nothing to check against for this image...
if (!cb_subres_map) continue;
const auto &sub_cb_subres_map = sub_layout_map_entry.second;
// Validate the initial_uses, that they match the current state of the primary cb, or absent a current state,
// that the match any initial_layout.
for (auto it_init = sub_cb_subres_map->BeginInitialUse(); !it_init.AtEnd(); ++it_init) {
const auto &sub_layout = (*it_init).layout;
if (VK_IMAGE_LAYOUT_UNDEFINED == sub_layout) continue; // secondary doesn't care about current or initial
const auto &subresource = (*it_init).subresource;
// Look up the current layout (if any)
VkImageLayout cb_layout = cb_subres_map->GetSubresourceLayout(subresource);
const char *layout_type = "current";
if (cb_layout == kInvalidLayout) {
// Find initial layout (if any)
cb_layout = cb_subres_map->GetSubresourceInitialLayout(subresource);
layout_type = "initial";
}
if ((cb_layout != kInvalidLayout) && (cb_layout != sub_layout)) {
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(pCommandBuffers[i]), "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001",
"%s: Executed secondary command buffer using image %s (subresource: aspectMask 0x%X array layer %u, "
"mip level %u) which expects layout %s--instead, image %s layout is %s.",
"vkCmdExecuteCommands():", report_data->FormatHandle(image).c_str(), subresource.aspectMask,
subresource.arrayLayer, subresource.mipLevel, string_VkImageLayout(sub_layout), layout_type,
string_VkImageLayout(cb_layout));
}
}
}
linked_command_buffers.insert(sub_cb_state);
}
skip |= ValidatePrimaryCommandBuffer(cb_state, "vkCmdExecuteCommands()", "VUID-vkCmdExecuteCommands-bufferlevel");
skip |= ValidateCmdQueueFlags(cb_state, "vkCmdExecuteCommands()",
VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
"VUID-vkCmdExecuteCommands-commandBuffer-cmdpool");
skip |= ValidateCmd(cb_state, CMD_EXECUTECOMMANDS, "vkCmdExecuteCommands()");
return skip;
}
void CoreChecks::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBuffersCount,
const VkCommandBuffer *pCommandBuffers) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
CMD_BUFFER_STATE *sub_cb_state = NULL;
for (uint32_t i = 0; i < commandBuffersCount; i++) {
sub_cb_state = GetCBState(pCommandBuffers[i]);
assert(sub_cb_state);
if (!(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) {
if (cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
// TODO: Because this is a state change, clearing the VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT needs to be moved
// from the validation step to the recording step
cb_state->beginInfo.flags &= ~VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
}
}
// Propagate inital layout and current layout state to the primary cmd buffer
for (const auto &sub_layout_map_entry : sub_cb_state->image_layout_map) {
const auto image = sub_layout_map_entry.first;
const auto *image_state = GetImageState(image);
if (!image_state) continue; // Can't set layouts of a dead image
auto *cb_subres_map = GetImageSubresourceLayoutMap(cb_state, *image_state);
const auto *sub_cb_subres_map = sub_layout_map_entry.second.get();
assert(cb_subres_map && sub_cb_subres_map); // Non const get and map traversal should never be null
cb_subres_map->UpdateFrom(*sub_cb_subres_map);
}
sub_cb_state->primaryCommandBuffer = cb_state->commandBuffer;
cb_state->linkedCommandBuffers.insert(sub_cb_state);
sub_cb_state->linkedCommandBuffers.insert(cb_state);
for (auto &function : sub_cb_state->queryUpdates) {
cb_state->queryUpdates.push_back(function);
}
for (auto &function : sub_cb_state->queue_submit_functions) {
cb_state->queue_submit_functions.push_back(function);
}
}
}
bool CoreChecks::PreCallValidateMapMemory(VkDevice device, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size,
VkFlags flags, void **ppData) {
bool skip = false;
DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem);
if (mem_info) {
auto end_offset = (VK_WHOLE_SIZE == size) ? mem_info->alloc_info.allocationSize - 1 : offset + size - 1;
skip |= ValidateMapImageLayouts(device, mem_info, offset, end_offset);
if ((phys_dev_mem_props.memoryTypes[mem_info->alloc_info.memoryTypeIndex].propertyFlags &
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), "VUID-vkMapMemory-memory-00682",
"Mapping Memory without VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT set: mem obj %s.",
report_data->FormatHandle(mem).c_str());
}
}
skip |= ValidateMapMemRange(mem, offset, size);
return skip;
}
void CoreChecks::PostCallRecordMapMemory(VkDevice device, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size, VkFlags flags,
void **ppData, VkResult result) {
if (VK_SUCCESS != result) return;
// TODO : What's the point of this range? See comment on creating new "bound_range" above, which may replace this
StoreMemRanges(mem, offset, size);
InitializeAndTrackMemory(mem, offset, size, ppData);
}
bool CoreChecks::PreCallValidateUnmapMemory(VkDevice device, VkDeviceMemory mem) {
bool skip = false;
auto mem_info = GetDevMemState(mem);
if (mem_info && !mem_info->mem_range.size) {
// Valid Usage: memory must currently be mapped
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), "VUID-vkUnmapMemory-memory-00689",
"Unmapping Memory without memory being mapped: mem obj %s.", report_data->FormatHandle(mem).c_str());
}
return skip;
}
void CoreChecks::PreCallRecordUnmapMemory(VkDevice device, VkDeviceMemory mem) {
auto mem_info = GetDevMemState(mem);
mem_info->mem_range.size = 0;
if (mem_info->shadow_copy) {
free(mem_info->shadow_copy_base);
mem_info->shadow_copy_base = 0;
mem_info->shadow_copy = 0;
}
}
bool CoreChecks::ValidateMemoryIsMapped(const char *funcName, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) {
bool skip = false;
for (uint32_t i = 0; i < memRangeCount; ++i) {
auto mem_info = GetDevMemState(pMemRanges[i].memory);
if (mem_info) {
if (pMemRanges[i].size == VK_WHOLE_SIZE) {
if (mem_info->mem_range.offset > pMemRanges[i].offset) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(pMemRanges[i].memory), "VUID-VkMappedMemoryRange-size-00686",
"%s: Flush/Invalidate offset (" PRINTF_SIZE_T_SPECIFIER
") is less than Memory Object's offset (" PRINTF_SIZE_T_SPECIFIER ").",
funcName, static_cast<size_t>(pMemRanges[i].offset),
static_cast<size_t>(mem_info->mem_range.offset));
}
} else {
const uint64_t data_end = (mem_info->mem_range.size == VK_WHOLE_SIZE)
? mem_info->alloc_info.allocationSize
: (mem_info->mem_range.offset + mem_info->mem_range.size);
if ((mem_info->mem_range.offset > pMemRanges[i].offset) ||
(data_end < (pMemRanges[i].offset + pMemRanges[i].size))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(pMemRanges[i].memory), "VUID-VkMappedMemoryRange-size-00685",
"%s: Flush/Invalidate size or offset (" PRINTF_SIZE_T_SPECIFIER ", " PRINTF_SIZE_T_SPECIFIER
") exceed the Memory Object's upper-bound (" PRINTF_SIZE_T_SPECIFIER ").",
funcName, static_cast<size_t>(pMemRanges[i].offset + pMemRanges[i].size),
static_cast<size_t>(pMemRanges[i].offset), static_cast<size_t>(data_end));
}
}
}
}
return skip;
}
bool CoreChecks::ValidateAndCopyNoncoherentMemoryToDriver(uint32_t mem_range_count, const VkMappedMemoryRange *mem_ranges) {
bool skip = false;
for (uint32_t i = 0; i < mem_range_count; ++i) {
auto mem_info = GetDevMemState(mem_ranges[i].memory);
if (mem_info) {
if (mem_info->shadow_copy) {
VkDeviceSize size = (mem_info->mem_range.size != VK_WHOLE_SIZE)
? mem_info->mem_range.size
: (mem_info->alloc_info.allocationSize - mem_info->mem_range.offset);
char *data = static_cast<char *>(mem_info->shadow_copy);
for (uint64_t j = 0; j < mem_info->shadow_pad_size; ++j) {
if (data[j] != NoncoherentMemoryFillValue) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem_ranges[i].memory), kVUID_Core_MemTrack_InvalidMap,
"Memory underflow was detected on mem obj %s.",
report_data->FormatHandle(mem_ranges[i].memory).c_str());
}
}
for (uint64_t j = (size + mem_info->shadow_pad_size); j < (2 * mem_info->shadow_pad_size + size); ++j) {
if (data[j] != NoncoherentMemoryFillValue) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem_ranges[i].memory), kVUID_Core_MemTrack_InvalidMap,
"Memory overflow was detected on mem obj %s.",
report_data->FormatHandle(mem_ranges[i].memory).c_str());
}
}
memcpy(mem_info->p_driver_data, static_cast<void *>(data + mem_info->shadow_pad_size), (size_t)(size));
}
}
}
return skip;
}
void CoreChecks::CopyNoncoherentMemoryFromDriver(uint32_t mem_range_count, const VkMappedMemoryRange *mem_ranges) {
for (uint32_t i = 0; i < mem_range_count; ++i) {
auto mem_info = GetDevMemState(mem_ranges[i].memory);
if (mem_info && mem_info->shadow_copy) {
VkDeviceSize size = (mem_info->mem_range.size != VK_WHOLE_SIZE)
? mem_info->mem_range.size
: (mem_info->alloc_info.allocationSize - mem_ranges[i].offset);
char *data = static_cast<char *>(mem_info->shadow_copy);
memcpy(data + mem_info->shadow_pad_size, mem_info->p_driver_data, (size_t)(size));
}
}
}
bool CoreChecks::ValidateMappedMemoryRangeDeviceLimits(const char *func_name, uint32_t mem_range_count,
const VkMappedMemoryRange *mem_ranges) {
bool skip = false;
for (uint32_t i = 0; i < mem_range_count; ++i) {
uint64_t atom_size = phys_dev_props.limits.nonCoherentAtomSize;
if (SafeModulo(mem_ranges[i].offset, atom_size) != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem_ranges->memory), "VUID-VkMappedMemoryRange-offset-00687",
"%s: Offset in pMemRanges[%d] is 0x%" PRIxLEAST64
", which is not a multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize (0x%" PRIxLEAST64 ").",
func_name, i, mem_ranges[i].offset, atom_size);
}
auto mem_info = GetDevMemState(mem_ranges[i].memory);
if ((mem_ranges[i].size != VK_WHOLE_SIZE) &&
(mem_ranges[i].size + mem_ranges[i].offset != mem_info->alloc_info.allocationSize) &&
(SafeModulo(mem_ranges[i].size, atom_size) != 0)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem_ranges->memory), "VUID-VkMappedMemoryRange-size-01390",
"%s: Size in pMemRanges[%d] is 0x%" PRIxLEAST64
", which is not a multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize (0x%" PRIxLEAST64 ").",
func_name, i, mem_ranges[i].size, atom_size);
}
}
return skip;
}
bool CoreChecks::PreCallValidateFlushMappedMemoryRanges(VkDevice device, uint32_t memRangeCount,
const VkMappedMemoryRange *pMemRanges) {
bool skip = false;
skip |= ValidateMappedMemoryRangeDeviceLimits("vkFlushMappedMemoryRanges", memRangeCount, pMemRanges);
skip |= ValidateAndCopyNoncoherentMemoryToDriver(memRangeCount, pMemRanges);
skip |= ValidateMemoryIsMapped("vkFlushMappedMemoryRanges", memRangeCount, pMemRanges);
return skip;
}
bool CoreChecks::PreCallValidateInvalidateMappedMemoryRanges(VkDevice device, uint32_t memRangeCount,
const VkMappedMemoryRange *pMemRanges) {
bool skip = false;
skip |= ValidateMappedMemoryRangeDeviceLimits("vkInvalidateMappedMemoryRanges", memRangeCount, pMemRanges);
skip |= ValidateMemoryIsMapped("vkInvalidateMappedMemoryRanges", memRangeCount, pMemRanges);
return skip;
}
void CoreChecks::PostCallRecordInvalidateMappedMemoryRanges(VkDevice device, uint32_t memRangeCount,
const VkMappedMemoryRange *pMemRanges, VkResult result) {
if (VK_SUCCESS == result) {
// Update our shadow copy with modified driver data
CopyNoncoherentMemoryFromDriver(memRangeCount, pMemRanges);
}
}
bool CoreChecks::PreCallValidateGetDeviceMemoryCommitment(VkDevice device, VkDeviceMemory mem, VkDeviceSize *pCommittedMem) {
bool skip = false;
auto mem_info = GetDevMemState(mem);
if (mem_info) {
if ((phys_dev_mem_props.memoryTypes[mem_info->alloc_info.memoryTypeIndex].propertyFlags &
VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,
HandleToUint64(mem), "VUID-vkGetDeviceMemoryCommitment-memory-00690",
"Querying commitment for memory without VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT set: mem obj %s.",
report_data->FormatHandle(mem).c_str());
}
}
return skip;
}
bool CoreChecks::ValidateBindImageMemory(VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset, const char *api_name) {
bool skip = false;
IMAGE_STATE *image_state = GetImageState(image);
if (image_state) {
// Track objects tied to memory
uint64_t image_handle = HandleToUint64(image);
skip = ValidateSetMemBinding(mem, image_handle, kVulkanObjectTypeImage, api_name);
#ifdef VK_USE_PLATFORM_ANDROID_KHR
if (image_state->external_format_android) {
if (image_state->memory_requirements_checked) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
kVUID_Core_DrawState_InvalidImage,
"%s: Must not call vkGetImageMemoryRequirements on image %s that will be bound to an external "
"Android hardware buffer.",
api_name, report_data->FormatHandle(image_handle).c_str());
}
return skip;
}
#endif // VK_USE_PLATFORM_ANDROID_KHR
if (!image_state->memory_requirements_checked) {
// There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
// BindImageMemory but it's implied in that memory being bound must conform with VkMemoryRequirements from
// vkGetImageMemoryRequirements()
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
kVUID_Core_DrawState_InvalidImage,
"%s: Binding memory to image %s but vkGetImageMemoryRequirements() has not been called on that image.",
api_name, report_data->FormatHandle(image_handle).c_str());
// Make the call for them so we can verify the state
DispatchGetImageMemoryRequirements(device, image, &image_state->requirements);
}
// Validate bound memory range information
auto mem_info = GetDevMemState(mem);
if (mem_info) {
skip |= ValidateInsertImageMemoryRange(image, mem_info, memoryOffset, image_state->requirements,
image_state->createInfo.tiling == VK_IMAGE_TILING_LINEAR, api_name);
skip |= ValidateMemoryTypes(mem_info, image_state->requirements.memoryTypeBits, api_name,
"VUID-vkBindImageMemory-memory-01047");
}
// Validate memory requirements alignment
if (SafeModulo(memoryOffset, image_state->requirements.alignment) != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
"VUID-vkBindImageMemory-memoryOffset-01048",
"%s: memoryOffset is 0x%" PRIxLEAST64
" but must be an integer multiple of the VkMemoryRequirements::alignment value 0x%" PRIxLEAST64
", returned from a call to vkGetImageMemoryRequirements with image.",
api_name, memoryOffset, image_state->requirements.alignment);
}
if (mem_info) {
// Validate memory requirements size
if (image_state->requirements.size > mem_info->alloc_info.allocationSize - memoryOffset) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle,
"VUID-vkBindImageMemory-size-01049",
"%s: memory size minus memoryOffset is 0x%" PRIxLEAST64
" but must be at least as large as VkMemoryRequirements::size value 0x%" PRIxLEAST64
", returned from a call to vkGetImageMemoryRequirements with image.",
api_name, mem_info->alloc_info.allocationSize - memoryOffset, image_state->requirements.size);
}
// Validate dedicated allocation
if (mem_info->is_dedicated && ((mem_info->dedicated_image != image) || (memoryOffset != 0))) {
// TODO: Add vkBindImageMemory2KHR error message when added to spec.
auto validation_error = kVUIDUndefined;
if (strcmp(api_name, "vkBindImageMemory()") == 0) {
validation_error = "VUID-vkBindImageMemory-memory-01509";
}
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, image_handle,
validation_error,
"%s: for dedicated memory allocation %s, VkMemoryDedicatedAllocateInfoKHR::image %s must be equal "
"to image %s and memoryOffset 0x%" PRIxLEAST64 " must be zero.",
api_name, report_data->FormatHandle(mem).c_str(),
report_data->FormatHandle(mem_info->dedicated_image).c_str(),
report_data->FormatHandle(image_handle).c_str(), memoryOffset);
}
}
}
return skip;
}
bool CoreChecks::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset) {
return ValidateBindImageMemory(image, mem, memoryOffset, "vkBindImageMemory()");
}
void CoreChecks::UpdateBindImageMemoryState(VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset) {
IMAGE_STATE *image_state = GetImageState(image);
if (image_state) {
// Track bound memory range information
auto mem_info = GetDevMemState(mem);
if (mem_info) {
InsertImageMemoryRange(image, mem_info, memoryOffset, image_state->requirements,
image_state->createInfo.tiling == VK_IMAGE_TILING_LINEAR);
}
// Track objects tied to memory
uint64_t image_handle = HandleToUint64(image);
SetMemBinding(mem, image_state, memoryOffset, image_handle, kVulkanObjectTypeImage);
}
}
void CoreChecks::PostCallRecordBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset,
VkResult result) {
if (VK_SUCCESS != result) return;
UpdateBindImageMemoryState(image, mem, memoryOffset);
}
bool CoreChecks::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
const VkBindImageMemoryInfoKHR *pBindInfos) {
bool skip = false;
char api_name[128];
for (uint32_t i = 0; i < bindInfoCount; i++) {
sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name);
}
return skip;
}
bool CoreChecks::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
const VkBindImageMemoryInfoKHR *pBindInfos) {
bool skip = false;
char api_name[128];
for (uint32_t i = 0; i < bindInfoCount; i++) {
sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name);
}
return skip;
}
void CoreChecks::PostCallRecordBindImageMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR *pBindInfos,
VkResult result) {
if (VK_SUCCESS != result) return;
for (uint32_t i = 0; i < bindInfoCount; i++) {
UpdateBindImageMemoryState(pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset);
}
}
void CoreChecks::PostCallRecordBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
const VkBindImageMemoryInfoKHR *pBindInfos, VkResult result) {
if (VK_SUCCESS != result) return;
for (uint32_t i = 0; i < bindInfoCount; i++) {
UpdateBindImageMemoryState(pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset);
}
}
bool CoreChecks::PreCallValidateSetEvent(VkDevice device, VkEvent event) {
bool skip = false;
auto event_state = GetEventState(event);
if (event_state) {
if (event_state->write_in_use) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT,
HandleToUint64(event), kVUID_Core_DrawState_QueueForwardProgress,
"Cannot call vkSetEvent() on event %s that is already in use by a command buffer.",
report_data->FormatHandle(event).c_str());
}
}
return skip;
}
void CoreChecks::PreCallRecordSetEvent(VkDevice device, VkEvent event) {
auto event_state = GetEventState(event);
if (event_state) {
event_state->needsSignaled = false;
event_state->stageMask = VK_PIPELINE_STAGE_HOST_BIT;
}
// Host setting event is visible to all queues immediately so update stageMask for any queue that's seen this event
// TODO : For correctness this needs separate fix to verify that app doesn't make incorrect assumptions about the
// ordering of this command in relation to vkCmd[Set|Reset]Events (see GH297)
for (auto queue_data : queueMap) {
auto event_entry = queue_data.second.eventToStageMap.find(event);
if (event_entry != queue_data.second.eventToStageMap.end()) {
event_entry->second |= VK_PIPELINE_STAGE_HOST_BIT;
}
}
}
bool CoreChecks::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo *pBindInfo,
VkFence fence) {
auto pFence = GetFenceState(fence);
bool skip = ValidateFenceForSubmit(pFence);
if (skip) {
return true;
}
unordered_set<VkSemaphore> signaled_semaphores;
unordered_set<VkSemaphore> unsignaled_semaphores;
unordered_set<VkSemaphore> internal_semaphores;
for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; ++bindIdx) {
const VkBindSparseInfo &bindInfo = pBindInfo[bindIdx];
std::vector<SEMAPHORE_WAIT> semaphore_waits;
std::vector<VkSemaphore> semaphore_signals;
for (uint32_t i = 0; i < bindInfo.waitSemaphoreCount; ++i) {
VkSemaphore semaphore = bindInfo.pWaitSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) {
if (unsignaled_semaphores.count(semaphore) ||
(!(signaled_semaphores.count(semaphore)) && !(pSemaphore->signaled))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress,
"Queue %s is waiting on semaphore %s that has no way to be signaled.",
report_data->FormatHandle(queue).c_str(), report_data->FormatHandle(semaphore).c_str());
} else {
signaled_semaphores.erase(semaphore);
unsignaled_semaphores.insert(semaphore);
}
}
if (pSemaphore && pSemaphore->scope == kSyncScopeExternalTemporary) {
internal_semaphores.insert(semaphore);
}
}
for (uint32_t i = 0; i < bindInfo.signalSemaphoreCount; ++i) {
VkSemaphore semaphore = bindInfo.pSignalSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore && pSemaphore->scope == kSyncScopeInternal) {
if (signaled_semaphores.count(semaphore) || (!(unsignaled_semaphores.count(semaphore)) && pSemaphore->signaled)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress,
"Queue %s is signaling semaphore %s that was previously signaled by queue %s but has not since "
"been waited on by any queue.",
report_data->FormatHandle(queue).c_str(), report_data->FormatHandle(semaphore).c_str(),
report_data->FormatHandle(pSemaphore->signaler.first).c_str());
} else {
unsignaled_semaphores.erase(semaphore);
signaled_semaphores.insert(semaphore);
}
}
}
// Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
std::unordered_set<IMAGE_STATE *> sparse_images;
// If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
const auto &image_bind = bindInfo.pImageBinds[i];
auto image_state = GetImageState(image_bind.image);
if (!image_state)
continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
sparse_images.insert(image_state);
if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
// For now just warning if sparse image binding occurs without calling to get reqs first
return log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState,
"vkQueueBindSparse(): Binding sparse memory to image %s without first calling "
"vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
report_data->FormatHandle(image_state->image).c_str());
}
}
if (!image_state->memory_requirements_checked) {
// For now just warning if sparse image binding occurs without calling to get reqs first
return log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState,
"vkQueueBindSparse(): Binding sparse memory to image %s without first calling "
"vkGetImageMemoryRequirements() to retrieve requirements.",
report_data->FormatHandle(image_state->image).c_str());
}
}
for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
const auto &image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
if (!image_state)
continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
sparse_images.insert(image_state);
if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
// For now just warning if sparse image binding occurs without calling to get reqs first
return log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState,
"vkQueueBindSparse(): Binding opaque sparse memory to image %s without first calling "
"vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
report_data->FormatHandle(image_state->image).c_str());
}
}
if (!image_state->memory_requirements_checked) {
// For now just warning if sparse image binding occurs without calling to get reqs first
return log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState,
"vkQueueBindSparse(): Binding opaque sparse memory to image %s without first calling "
"vkGetImageMemoryRequirements() to retrieve requirements.",
report_data->FormatHandle(image_state->image).c_str());
}
for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
image_state->sparse_metadata_bound = true;
}
}
}
for (const auto &sparse_image_state : sparse_images) {
if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound) {
// Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
return log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
HandleToUint64(sparse_image_state->image), kVUID_Core_MemTrack_InvalidState,
"vkQueueBindSparse(): Binding sparse memory to image %s which requires a metadata aspect but no "
"binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
report_data->FormatHandle(sparse_image_state->image).c_str());
}
}
}
return skip;
}
void CoreChecks::PostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo *pBindInfo,
VkFence fence, VkResult result) {
if (result != VK_SUCCESS) return;
uint64_t early_retire_seq = 0;
auto pFence = GetFenceState(fence);
auto pQueue = GetQueueState(queue);
if (pFence) {
if (pFence->scope == kSyncScopeInternal) {
SubmitFence(pQueue, pFence, std::max(1u, bindInfoCount));
if (!bindInfoCount) {
// No work to do, just dropping a fence in the queue by itself.
pQueue->submissions.emplace_back(std::vector<VkCommandBuffer>(), std::vector<SEMAPHORE_WAIT>(),
std::vector<VkSemaphore>(), std::vector<VkSemaphore>(), fence);
}
} else {
// Retire work up until this fence early, we will not see the wait that corresponds to this signal
early_retire_seq = pQueue->seq + pQueue->submissions.size();
if (!external_sync_warning) {
external_sync_warning = true;
log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence),
kVUID_Core_DrawState_QueueForwardProgress,
"vkQueueBindSparse(): Signaling external fence %s on queue %s will disable validation of preceding command "
"buffer lifecycle states and the in-use status of associated objects.",
report_data->FormatHandle(fence).c_str(), report_data->FormatHandle(queue).c_str());
}
}
}
for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; ++bindIdx) {
const VkBindSparseInfo &bindInfo = pBindInfo[bindIdx];
// Track objects tied to memory
for (uint32_t j = 0; j < bindInfo.bufferBindCount; j++) {
for (uint32_t k = 0; k < bindInfo.pBufferBinds[j].bindCount; k++) {
auto sparse_binding = bindInfo.pBufferBinds[j].pBinds[k];
SetSparseMemBinding({sparse_binding.memory, sparse_binding.memoryOffset, sparse_binding.size},
HandleToUint64(bindInfo.pBufferBinds[j].buffer), kVulkanObjectTypeBuffer);
}
}
for (uint32_t j = 0; j < bindInfo.imageOpaqueBindCount; j++) {
for (uint32_t k = 0; k < bindInfo.pImageOpaqueBinds[j].bindCount; k++) {
auto sparse_binding = bindInfo.pImageOpaqueBinds[j].pBinds[k];
SetSparseMemBinding({sparse_binding.memory, sparse_binding.memoryOffset, sparse_binding.size},
HandleToUint64(bindInfo.pImageOpaqueBinds[j].image), kVulkanObjectTypeImage);
}
}
for (uint32_t j = 0; j < bindInfo.imageBindCount; j++) {
for (uint32_t k = 0; k < bindInfo.pImageBinds[j].bindCount; k++) {
auto sparse_binding = bindInfo.pImageBinds[j].pBinds[k];
// TODO: This size is broken for non-opaque bindings, need to update to comprehend full sparse binding data
VkDeviceSize size = sparse_binding.extent.depth * sparse_binding.extent.height * sparse_binding.extent.width * 4;
SetSparseMemBinding({sparse_binding.memory, sparse_binding.memoryOffset, size},
HandleToUint64(bindInfo.pImageBinds[j].image), kVulkanObjectTypeImage);
}
}
std::vector<SEMAPHORE_WAIT> semaphore_waits;
std::vector<VkSemaphore> semaphore_signals;
std::vector<VkSemaphore> semaphore_externals;
for (uint32_t i = 0; i < bindInfo.waitSemaphoreCount; ++i) {
VkSemaphore semaphore = bindInfo.pWaitSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore) {
if (pSemaphore->scope == kSyncScopeInternal) {
if (pSemaphore->signaler.first != VK_NULL_HANDLE) {
semaphore_waits.push_back({semaphore, pSemaphore->signaler.first, pSemaphore->signaler.second});
pSemaphore->in_use.fetch_add(1);
}
pSemaphore->signaler.first = VK_NULL_HANDLE;
pSemaphore->signaled = false;
} else {
semaphore_externals.push_back(semaphore);
pSemaphore->in_use.fetch_add(1);
if (pSemaphore->scope == kSyncScopeExternalTemporary) {
pSemaphore->scope = kSyncScopeInternal;
}
}
}
}
for (uint32_t i = 0; i < bindInfo.signalSemaphoreCount; ++i) {
VkSemaphore semaphore = bindInfo.pSignalSemaphores[i];
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore) {
if (pSemaphore->scope == kSyncScopeInternal) {
pSemaphore->signaler.first = queue;
pSemaphore->signaler.second = pQueue->seq + pQueue->submissions.size() + 1;
pSemaphore->signaled = true;
pSemaphore->in_use.fetch_add(1);
semaphore_signals.push_back(semaphore);
} else {
// Retire work up until this submit early, we will not see the wait that corresponds to this signal
early_retire_seq = std::max(early_retire_seq, pQueue->seq + pQueue->submissions.size() + 1);
if (!external_sync_warning) {
external_sync_warning = true;
log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress,
"vkQueueBindSparse(): Signaling external semaphore %s on queue %s will disable validation of "
"preceding command buffer lifecycle states and the in-use status of associated objects.",
report_data->FormatHandle(semaphore).c_str(), report_data->FormatHandle(queue).c_str());
}
}
}
}
pQueue->submissions.emplace_back(std::vector<VkCommandBuffer>(), semaphore_waits, semaphore_signals, semaphore_externals,
bindIdx == bindInfoCount - 1 ? fence : VK_NULL_HANDLE);
}
if (early_retire_seq) {
RetireWorkOnQueue(pQueue, early_retire_seq);
}
}
void CoreChecks::PostCallRecordCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSemaphore *pSemaphore, VkResult result) {
if (VK_SUCCESS != result) return;
std::unique_ptr<SEMAPHORE_STATE> semaphore_state(new SEMAPHORE_STATE{});
semaphore_state->signaler.first = VK_NULL_HANDLE;
semaphore_state->signaler.second = 0;
semaphore_state->signaled = false;
semaphore_state->scope = kSyncScopeInternal;
semaphoreMap[*pSemaphore] = std::move(semaphore_state);
}
bool CoreChecks::ValidateImportSemaphore(VkSemaphore semaphore, const char *caller_name) {
bool skip = false;
SEMAPHORE_STATE *sema_node = GetSemaphoreState(semaphore);
if (sema_node) {
VK_OBJECT obj_struct = {HandleToUint64(semaphore), kVulkanObjectTypeSemaphore};
skip |= ValidateObjectNotInUse(sema_node, obj_struct, caller_name, kVUIDUndefined);
}
return skip;
}
void CoreChecks::RecordImportSemaphoreState(VkSemaphore semaphore, VkExternalSemaphoreHandleTypeFlagBitsKHR handle_type,
VkSemaphoreImportFlagsKHR flags) {
SEMAPHORE_STATE *sema_node = GetSemaphoreState(semaphore);
if (sema_node && sema_node->scope != kSyncScopeExternalPermanent) {
if ((handle_type == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT_KHR || flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR) &&
sema_node->scope == kSyncScopeInternal) {
sema_node->scope = kSyncScopeExternalTemporary;
} else {
sema_node->scope = kSyncScopeExternalPermanent;
}
}
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool CoreChecks::PreCallValidateImportSemaphoreWin32HandleKHR(
VkDevice device, const VkImportSemaphoreWin32HandleInfoKHR *pImportSemaphoreWin32HandleInfo) {
return ValidateImportSemaphore(pImportSemaphoreWin32HandleInfo->semaphore, "vkImportSemaphoreWin32HandleKHR");
}
void CoreChecks::PostCallRecordImportSemaphoreWin32HandleKHR(
VkDevice device, const VkImportSemaphoreWin32HandleInfoKHR *pImportSemaphoreWin32HandleInfo, VkResult result) {
if (VK_SUCCESS != result) return;
RecordImportSemaphoreState(pImportSemaphoreWin32HandleInfo->semaphore, pImportSemaphoreWin32HandleInfo->handleType,
pImportSemaphoreWin32HandleInfo->flags);
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool CoreChecks::PreCallValidateImportSemaphoreFdKHR(VkDevice device, const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo) {
return ValidateImportSemaphore(pImportSemaphoreFdInfo->semaphore, "vkImportSemaphoreFdKHR");
}
void CoreChecks::PostCallRecordImportSemaphoreFdKHR(VkDevice device, const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordImportSemaphoreState(pImportSemaphoreFdInfo->semaphore, pImportSemaphoreFdInfo->handleType,
pImportSemaphoreFdInfo->flags);
}
void CoreChecks::RecordGetExternalSemaphoreState(VkSemaphore semaphore, VkExternalSemaphoreHandleTypeFlagBitsKHR handle_type) {
SEMAPHORE_STATE *semaphore_state = GetSemaphoreState(semaphore);
if (semaphore_state && handle_type != VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT_KHR) {
// Cannot track semaphore state once it is exported, except for Sync FD handle types which have copy transference
semaphore_state->scope = kSyncScopeExternalPermanent;
}
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
void CoreChecks::PostCallRecordGetSemaphoreWin32HandleKHR(VkDevice device,
const VkSemaphoreGetWin32HandleInfoKHR *pGetWin32HandleInfo,
HANDLE *pHandle, VkResult result) {
if (VK_SUCCESS != result) return;
RecordGetExternalSemaphoreState(pGetWin32HandleInfo->semaphore, pGetWin32HandleInfo->handleType);
}
#endif
void CoreChecks::PostCallRecordGetSemaphoreFdKHR(VkDevice device, const VkSemaphoreGetFdInfoKHR *pGetFdInfo, int *pFd,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordGetExternalSemaphoreState(pGetFdInfo->semaphore, pGetFdInfo->handleType);
}
bool CoreChecks::ValidateImportFence(VkFence fence, const char *caller_name) {
FENCE_STATE *fence_node = GetFenceState(fence);
bool skip = false;
if (fence_node && fence_node->scope == kSyncScopeInternal && fence_node->state == FENCE_INFLIGHT) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence),
kVUIDUndefined, "Cannot call %s on fence %s that is currently in use.", caller_name,
report_data->FormatHandle(fence).c_str());
}
return skip;
}
void CoreChecks::RecordImportFenceState(VkFence fence, VkExternalFenceHandleTypeFlagBitsKHR handle_type,
VkFenceImportFlagsKHR flags) {
FENCE_STATE *fence_node = GetFenceState(fence);
if (fence_node && fence_node->scope != kSyncScopeExternalPermanent) {
if ((handle_type == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT_KHR || flags & VK_FENCE_IMPORT_TEMPORARY_BIT_KHR) &&
fence_node->scope == kSyncScopeInternal) {
fence_node->scope = kSyncScopeExternalTemporary;
} else {
fence_node->scope = kSyncScopeExternalPermanent;
}
}
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool CoreChecks::PreCallValidateImportFenceWin32HandleKHR(VkDevice device,
const VkImportFenceWin32HandleInfoKHR *pImportFenceWin32HandleInfo) {
return ValidateImportFence(pImportFenceWin32HandleInfo->fence, "vkImportFenceWin32HandleKHR");
}
void CoreChecks::PostCallRecordImportFenceWin32HandleKHR(VkDevice device,
const VkImportFenceWin32HandleInfoKHR *pImportFenceWin32HandleInfo,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordImportFenceState(pImportFenceWin32HandleInfo->fence, pImportFenceWin32HandleInfo->handleType,
pImportFenceWin32HandleInfo->flags);
}
#endif // VK_USE_PLATFORM_WIN32_KHR
bool CoreChecks::PreCallValidateImportFenceFdKHR(VkDevice device, const VkImportFenceFdInfoKHR *pImportFenceFdInfo) {
return ValidateImportFence(pImportFenceFdInfo->fence, "vkImportFenceFdKHR");
}
void CoreChecks::PostCallRecordImportFenceFdKHR(VkDevice device, const VkImportFenceFdInfoKHR *pImportFenceFdInfo,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordImportFenceState(pImportFenceFdInfo->fence, pImportFenceFdInfo->handleType, pImportFenceFdInfo->flags);
}
void CoreChecks::RecordGetExternalFenceState(VkFence fence, VkExternalFenceHandleTypeFlagBitsKHR handle_type) {
FENCE_STATE *fence_state = GetFenceState(fence);
if (fence_state) {
if (handle_type != VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT_KHR) {
// Export with reference transference becomes external
fence_state->scope = kSyncScopeExternalPermanent;
} else if (fence_state->scope == kSyncScopeInternal) {
// Export with copy transference has a side effect of resetting the fence
fence_state->state = FENCE_UNSIGNALED;
}
}
}
#ifdef VK_USE_PLATFORM_WIN32_KHR
void CoreChecks::PostCallRecordGetFenceWin32HandleKHR(VkDevice device, const VkFenceGetWin32HandleInfoKHR *pGetWin32HandleInfo,
HANDLE *pHandle, VkResult result) {
if (VK_SUCCESS != result) return;
RecordGetExternalFenceState(pGetWin32HandleInfo->fence, pGetWin32HandleInfo->handleType);
}
#endif
void CoreChecks::PostCallRecordGetFenceFdKHR(VkDevice device, const VkFenceGetFdInfoKHR *pGetFdInfo, int *pFd, VkResult result) {
if (VK_SUCCESS != result) return;
RecordGetExternalFenceState(pGetFdInfo->fence, pGetFdInfo->handleType);
}
void CoreChecks::PostCallRecordCreateEvent(VkDevice device, const VkEventCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkEvent *pEvent, VkResult result) {
if (VK_SUCCESS != result) return;
eventMap[*pEvent].needsSignaled = false;
eventMap[*pEvent].write_in_use = 0;
eventMap[*pEvent].stageMask = VkPipelineStageFlags(0);
}
bool CoreChecks::ValidateCreateSwapchain(const char *func_name, VkSwapchainCreateInfoKHR const *pCreateInfo,
SURFACE_STATE *surface_state, SWAPCHAIN_NODE *old_swapchain_state) {
// All physical devices and queue families are required to be able to present to any native window on Android; require the
// application to have established support on any other platform.
if (!instance_extensions.vk_khr_android_surface) {
auto support_predicate = [this](decltype(surface_state->gpu_queue_support)::value_type qs) -> bool {
// TODO: should restrict search only to queue families of VkDeviceQueueCreateInfos, not whole phys. device
return (qs.first.gpu == physical_device) && qs.second;
};
const auto &support = surface_state->gpu_queue_support;
bool is_supported = std::any_of(support.begin(), support.end(), support_predicate);
if (!is_supported) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-surface-01270",
"%s: pCreateInfo->surface is not known at this time to be supported for presentation by this device. The "
"vkGetPhysicalDeviceSurfaceSupportKHR() must be called beforehand, and it must return VK_TRUE support with "
"this surface for at least one queue family of this device.",
func_name))
return true;
}
}
if (old_swapchain_state) {
if (old_swapchain_state->createInfo.surface != pCreateInfo->surface) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pCreateInfo->oldSwapchain), "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933",
"%s: pCreateInfo->oldSwapchain's surface is not pCreateInfo->surface", func_name))
return true;
}
if (old_swapchain_state->retired) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pCreateInfo->oldSwapchain), "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933",
"%s: pCreateInfo->oldSwapchain is retired", func_name))
return true;
}
}
if ((pCreateInfo->imageExtent.width == 0) || (pCreateInfo->imageExtent.height == 0)) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-imageExtent-01689", "%s: pCreateInfo->imageExtent = (%d, %d) which is illegal.",
func_name, pCreateInfo->imageExtent.width, pCreateInfo->imageExtent.height))
return true;
}
auto physical_device_state = GetPhysicalDeviceState();
if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physical_device), kVUID_Core_DrawState_SwapchainCreateBeforeQuery,
"%s: surface capabilities not retrieved for this physical device", func_name))
return true;
} else { // have valid capabilities
auto &capabilities = physical_device_state->surfaceCapabilities;
// Validate pCreateInfo->minImageCount against VkSurfaceCapabilitiesKHR::{min|max}ImageCount:
if (pCreateInfo->minImageCount < capabilities.minImageCount) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-minImageCount-01271",
"%s called with minImageCount = %d, which is outside the bounds returned by "
"vkGetPhysicalDeviceSurfaceCapabilitiesKHR() (i.e. minImageCount = %d, maxImageCount = %d).",
func_name, pCreateInfo->minImageCount, capabilities.minImageCount, capabilities.maxImageCount))
return true;
}
if ((capabilities.maxImageCount > 0) && (pCreateInfo->minImageCount > capabilities.maxImageCount)) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-minImageCount-01272",
"%s called with minImageCount = %d, which is outside the bounds returned by "
"vkGetPhysicalDeviceSurfaceCapabilitiesKHR() (i.e. minImageCount = %d, maxImageCount = %d).",
func_name, pCreateInfo->minImageCount, capabilities.minImageCount, capabilities.maxImageCount))
return true;
}
// Validate pCreateInfo->imageExtent against VkSurfaceCapabilitiesKHR::{current|min|max}ImageExtent:
if ((pCreateInfo->imageExtent.width < capabilities.minImageExtent.width) ||
(pCreateInfo->imageExtent.width > capabilities.maxImageExtent.width) ||
(pCreateInfo->imageExtent.height < capabilities.minImageExtent.height) ||
(pCreateInfo->imageExtent.height > capabilities.maxImageExtent.height)) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-imageExtent-01274",
"%s called with imageExtent = (%d,%d), which is outside the bounds returned by "
"vkGetPhysicalDeviceSurfaceCapabilitiesKHR(): currentExtent = (%d,%d), minImageExtent = (%d,%d), "
"maxImageExtent = (%d,%d).",
func_name, pCreateInfo->imageExtent.width, pCreateInfo->imageExtent.height,
capabilities.currentExtent.width, capabilities.currentExtent.height, capabilities.minImageExtent.width,
capabilities.minImageExtent.height, capabilities.maxImageExtent.width, capabilities.maxImageExtent.height))
return true;
}
// pCreateInfo->preTransform should have exactly one bit set, and that bit must also be set in
// VkSurfaceCapabilitiesKHR::supportedTransforms.
if (!pCreateInfo->preTransform || (pCreateInfo->preTransform & (pCreateInfo->preTransform - 1)) ||
!(pCreateInfo->preTransform & capabilities.supportedTransforms)) {
// This is an error situation; one for which we'd like to give the developer a helpful, multi-line error message. Build
// it up a little at a time, and then log it:
std::string errorString = "";
char str[1024];
// Here's the first part of the message:
sprintf(str, "%s called with a non-supported pCreateInfo->preTransform (i.e. %s). Supported values are:\n", func_name,
string_VkSurfaceTransformFlagBitsKHR(pCreateInfo->preTransform));
errorString += str;
for (int i = 0; i < 32; i++) {
// Build up the rest of the message:
if ((1 << i) & capabilities.supportedTransforms) {
const char *newStr = string_VkSurfaceTransformFlagBitsKHR((VkSurfaceTransformFlagBitsKHR)(1 << i));
sprintf(str, " %s\n", newStr);
errorString += str;
}
}
// Log the message that we've built up:
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-preTransform-01279", "%s.", errorString.c_str()))
return true;
}
// pCreateInfo->compositeAlpha should have exactly one bit set, and that bit must also be set in
// VkSurfaceCapabilitiesKHR::supportedCompositeAlpha
if (!pCreateInfo->compositeAlpha || (pCreateInfo->compositeAlpha & (pCreateInfo->compositeAlpha - 1)) ||
!((pCreateInfo->compositeAlpha) & capabilities.supportedCompositeAlpha)) {
// This is an error situation; one for which we'd like to give the developer a helpful, multi-line error message. Build
// it up a little at a time, and then log it:
std::string errorString = "";
char str[1024];
// Here's the first part of the message:
sprintf(str, "%s called with a non-supported pCreateInfo->compositeAlpha (i.e. %s). Supported values are:\n",
func_name, string_VkCompositeAlphaFlagBitsKHR(pCreateInfo->compositeAlpha));
errorString += str;
for (int i = 0; i < 32; i++) {
// Build up the rest of the message:
if ((1 << i) & capabilities.supportedCompositeAlpha) {
const char *newStr = string_VkCompositeAlphaFlagBitsKHR((VkCompositeAlphaFlagBitsKHR)(1 << i));
sprintf(str, " %s\n", newStr);
errorString += str;
}
}
// Log the message that we've built up:
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-compositeAlpha-01280", "%s.", errorString.c_str()))
return true;
}
// Validate pCreateInfo->imageArrayLayers against VkSurfaceCapabilitiesKHR::maxImageArrayLayers:
if (pCreateInfo->imageArrayLayers > capabilities.maxImageArrayLayers) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-imageArrayLayers-01275",
"%s called with a non-supported imageArrayLayers (i.e. %d). Maximum value is %d.", func_name,
pCreateInfo->imageArrayLayers, capabilities.maxImageArrayLayers))
return true;
}
// Validate pCreateInfo->imageUsage against VkSurfaceCapabilitiesKHR::supportedUsageFlags:
if (pCreateInfo->imageUsage != (pCreateInfo->imageUsage & capabilities.supportedUsageFlags)) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-imageUsage-01276",
"%s called with a non-supported pCreateInfo->imageUsage (i.e. 0x%08x). Supported flag bits are 0x%08x.",
func_name, pCreateInfo->imageUsage, capabilities.supportedUsageFlags))
return true;
}
if (device_extensions.vk_khr_surface_protected_capabilities &&
(pCreateInfo->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR)) {
VkPhysicalDeviceSurfaceInfo2KHR surfaceInfo = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR};
surfaceInfo.surface = pCreateInfo->surface;
VkSurfaceProtectedCapabilitiesKHR surfaceProtectedCapabilities = {VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR};
VkSurfaceCapabilities2KHR surfaceCapabilities = {VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR};
surfaceCapabilities.pNext = &surfaceProtectedCapabilities;
DispatchGetPhysicalDeviceSurfaceCapabilities2KHR(physical_device_state->phys_device, &surfaceInfo,
&surfaceCapabilities);
if (!surfaceProtectedCapabilities.supportsProtected) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-flags-03187",
"%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR but the surface "
"capabilities does not have VkSurfaceProtectedCapabilitiesKHR.supportsProtected set to VK_TRUE.",
func_name))
return true;
}
}
}
// Validate pCreateInfo values with the results of vkGetPhysicalDeviceSurfaceFormatsKHR():
if (physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
kVUID_Core_DrawState_SwapchainCreateBeforeQuery,
"%s called before calling vkGetPhysicalDeviceSurfaceFormatsKHR().", func_name))
return true;
} else {
// Validate pCreateInfo->imageFormat against VkSurfaceFormatKHR::format:
bool foundFormat = false;
bool foundColorSpace = false;
bool foundMatch = false;
for (auto const &format : physical_device_state->surface_formats) {
if (pCreateInfo->imageFormat == format.format) {
// Validate pCreateInfo->imageColorSpace against VkSurfaceFormatKHR::colorSpace:
foundFormat = true;
if (pCreateInfo->imageColorSpace == format.colorSpace) {
foundMatch = true;
break;
}
} else {
if (pCreateInfo->imageColorSpace == format.colorSpace) {
foundColorSpace = true;
}
}
}
if (!foundMatch) {
if (!foundFormat) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-imageFormat-01273",
"%s called with a non-supported pCreateInfo->imageFormat (i.e. %d).", func_name,
pCreateInfo->imageFormat))
return true;
}
if (!foundColorSpace) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-imageFormat-01273",
"%s called with a non-supported pCreateInfo->imageColorSpace (i.e. %d).", func_name,
pCreateInfo->imageColorSpace))
return true;
}
}
}
// Validate pCreateInfo values with the results of vkGetPhysicalDeviceSurfacePresentModesKHR():
if (physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
// FIFO is required to always be supported
if (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
kVUID_Core_DrawState_SwapchainCreateBeforeQuery,
"%s called before calling vkGetPhysicalDeviceSurfacePresentModesKHR().", func_name))
return true;
}
} else {
// Validate pCreateInfo->presentMode against vkGetPhysicalDeviceSurfacePresentModesKHR():
bool foundMatch = std::find(physical_device_state->present_modes.begin(), physical_device_state->present_modes.end(),
pCreateInfo->presentMode) != physical_device_state->present_modes.end();
if (!foundMatch) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-presentMode-01281", "%s called with a non-supported presentMode (i.e. %s).",
func_name, string_VkPresentModeKHR(pCreateInfo->presentMode)))
return true;
}
}
// Validate state for shared presentable case
if (VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR == pCreateInfo->presentMode ||
VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR == pCreateInfo->presentMode) {
if (!device_extensions.vk_khr_shared_presentable_image) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
kVUID_Core_DrawState_ExtensionNotEnabled,
"%s called with presentMode %s which requires the VK_KHR_shared_presentable_image extension, which has not "
"been enabled.",
func_name, string_VkPresentModeKHR(pCreateInfo->presentMode)))
return true;
} else if (pCreateInfo->minImageCount != 1) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-VkSwapchainCreateInfoKHR-minImageCount-01383",
"%s called with presentMode %s, but minImageCount value is %d. For shared presentable image, minImageCount "
"must be 1.",
func_name, string_VkPresentModeKHR(pCreateInfo->presentMode), pCreateInfo->minImageCount))
return true;
}
}
if (pCreateInfo->flags & VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR) {
if (!device_extensions.vk_khr_swapchain_mutable_format) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
kVUID_Core_DrawState_ExtensionNotEnabled,
"%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR which requires the "
"VK_KHR_swapchain_mutable_format extension, which has not been enabled.",
func_name))
return true;
} else {
const auto *image_format_list = lvl_find_in_chain<VkImageFormatListCreateInfoKHR>(pCreateInfo->pNext);
if (image_format_list == nullptr) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-flags-03168",
"%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR but the pNext chain of "
"pCreateInfo does not contain an instance of VkImageFormatListCreateInfoKHR.",
func_name))
return true;
} else if (image_format_list->viewFormatCount == 0) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-flags-03168",
"%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR but the viewFormatCount "
"member of VkImageFormatListCreateInfoKHR in the pNext chain is zero.",
func_name))
return true;
} else {
bool found_base_format = false;
for (uint32_t i = 0; i < image_format_list->viewFormatCount; ++i) {
if (image_format_list->pViewFormats[i] == pCreateInfo->imageFormat) {
found_base_format = true;
break;
}
}
if (!found_base_format) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-flags-03168",
"%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR but none of the "
"elements of the pViewFormats member of VkImageFormatListCreateInfoKHR match "
"pCreateInfo->imageFormat.",
func_name))
return true;
}
}
}
}
if ((pCreateInfo->imageSharingMode == VK_SHARING_MODE_CONCURRENT) && pCreateInfo->pQueueFamilyIndices) {
bool skip =
ValidateQueueFamilies(pCreateInfo->queueFamilyIndexCount, pCreateInfo->pQueueFamilyIndices, "vkCreateBuffer",
"pCreateInfo->pQueueFamilyIndices", "VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01428",
"VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01428", false);
if (skip) return true;
}
return false;
}
bool CoreChecks::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchain) {
auto surface_state = GetSurfaceState(pCreateInfo->surface);
auto old_swapchain_state = GetSwapchainState(pCreateInfo->oldSwapchain);
return ValidateCreateSwapchain("vkCreateSwapchainKHR()", pCreateInfo, surface_state, old_swapchain_state);
}
void CoreChecks::RecordCreateSwapchainState(VkResult result, const VkSwapchainCreateInfoKHR *pCreateInfo,
VkSwapchainKHR *pSwapchain, SURFACE_STATE *surface_state,
SWAPCHAIN_NODE *old_swapchain_state) {
if (VK_SUCCESS == result) {
auto swapchain_state = unique_ptr<SWAPCHAIN_NODE>(new SWAPCHAIN_NODE(pCreateInfo, *pSwapchain));
if (VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR == pCreateInfo->presentMode ||
VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR == pCreateInfo->presentMode) {
swapchain_state->shared_presentable = true;
}
surface_state->swapchain = swapchain_state.get();
swapchainMap[*pSwapchain] = std::move(swapchain_state);
} else {
surface_state->swapchain = nullptr;
}
// Spec requires that even if CreateSwapchainKHR fails, oldSwapchain is retired
if (old_swapchain_state) {
old_swapchain_state->retired = true;
}
return;
}
void CoreChecks::PostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchain,
VkResult result) {
auto surface_state = GetSurfaceState(pCreateInfo->surface);
auto old_swapchain_state = GetSwapchainState(pCreateInfo->oldSwapchain);
RecordCreateSwapchainState(result, pCreateInfo, pSwapchain, surface_state, old_swapchain_state);
}
void CoreChecks::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
const VkAllocationCallbacks *pAllocator) {
if (!swapchain) return;
auto swapchain_data = GetSwapchainState(swapchain);
if (swapchain_data) {
if (swapchain_data->images.size() > 0) {
for (auto swapchain_image : swapchain_data->images) {
auto image_sub = imageSubresourceMap.find(swapchain_image);
if (image_sub != imageSubresourceMap.end()) {
for (auto imgsubpair : image_sub->second) {
auto image_item = imageLayoutMap.find(imgsubpair);
if (image_item != imageLayoutMap.end()) {
imageLayoutMap.erase(image_item);
}
}
imageSubresourceMap.erase(image_sub);
}
ClearMemoryObjectBindings(HandleToUint64(swapchain_image), kVulkanObjectTypeSwapchainKHR);
EraseQFOImageRelaseBarriers(swapchain_image);
imageMap.erase(swapchain_image);
}
}
auto surface_state = GetSurfaceState(swapchain_data->createInfo.surface);
if (surface_state) {
if (surface_state->swapchain == swapchain_data) surface_state->swapchain = nullptr;
}
swapchainMap.erase(swapchain);
}
}
bool CoreChecks::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t *pSwapchainImageCount,
VkImage *pSwapchainImages) {
auto swapchain_state = GetSwapchainState(swapchain);
bool skip = false;
if (swapchain_state && pSwapchainImages) {
// Compare the preliminary value of *pSwapchainImageCount with the value this time:
if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
HandleToUint64(device), kVUID_Core_Swapchain_PriorCount,
"vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
"been seen for pSwapchainImages.");
} else if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
kVUID_Core_Swapchain_InvalidCount,
"vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount, and with pSwapchainImages set to a "
"value (%d) that is greater than the value (%d) that was returned when pSwapchainImageCount was NULL.",
*pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
}
}
return skip;
}
void CoreChecks::PostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t *pSwapchainImageCount,
VkImage *pSwapchainImages, VkResult result) {
if ((result != VK_SUCCESS) && (result != VK_INCOMPLETE)) return;
auto swapchain_state = GetSwapchainState(swapchain);
if (*pSwapchainImageCount > swapchain_state->images.size()) swapchain_state->images.resize(*pSwapchainImageCount);
if (pSwapchainImages) {
if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
}
for (uint32_t i = 0; i < *pSwapchainImageCount; ++i) {
if (swapchain_state->images[i] != VK_NULL_HANDLE) continue; // Already retrieved this.
IMAGE_LAYOUT_STATE image_layout_node;
image_layout_node.layout = VK_IMAGE_LAYOUT_UNDEFINED;
image_layout_node.format = swapchain_state->createInfo.imageFormat;
// Add imageMap entries for each swapchain image
VkImageCreateInfo image_ci = {};
image_ci.flags = 0;
image_ci.imageType = VK_IMAGE_TYPE_2D;
image_ci.format = swapchain_state->createInfo.imageFormat;
image_ci.extent.width = swapchain_state->createInfo.imageExtent.width;
image_ci.extent.height = swapchain_state->createInfo.imageExtent.height;
image_ci.extent.depth = 1;
image_ci.mipLevels = 1;
image_ci.arrayLayers = swapchain_state->createInfo.imageArrayLayers;
image_ci.samples = VK_SAMPLE_COUNT_1_BIT;
image_ci.tiling = VK_IMAGE_TILING_OPTIMAL;
image_ci.usage = swapchain_state->createInfo.imageUsage;
image_ci.sharingMode = swapchain_state->createInfo.imageSharingMode;
imageMap[pSwapchainImages[i]] = unique_ptr<IMAGE_STATE>(new IMAGE_STATE(pSwapchainImages[i], &image_ci));
auto &image_state = imageMap[pSwapchainImages[i]];
image_state->valid = false;
image_state->binding.mem = MEMTRACKER_SWAP_CHAIN_IMAGE_KEY;
swapchain_state->images[i] = pSwapchainImages[i];
ImageSubresourcePair subpair = {pSwapchainImages[i], false, VkImageSubresource()};
imageSubresourceMap[pSwapchainImages[i]].push_back(subpair);
imageLayoutMap[subpair] = image_layout_node;
}
}
if (*pSwapchainImageCount) {
if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_COUNT) {
swapchain_state->vkGetSwapchainImagesKHRState = QUERY_COUNT;
}
swapchain_state->get_swapchain_image_count = *pSwapchainImageCount;
}
}
bool CoreChecks::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) {
bool skip = false;
auto queue_state = GetQueueState(queue);
for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; ++i) {
auto pSemaphore = GetSemaphoreState(pPresentInfo->pWaitSemaphores[i]);
if (pSemaphore && !pSemaphore->signaled) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0,
kVUID_Core_DrawState_QueueForwardProgress, "Queue %s is waiting on semaphore %s that has no way to be signaled.",
report_data->FormatHandle(queue).c_str(), report_data->FormatHandle(pPresentInfo->pWaitSemaphores[i]).c_str());
}
}
for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
auto swapchain_data = GetSwapchainState(pPresentInfo->pSwapchains[i]);
if (swapchain_data) {
if (pPresentInfo->pImageIndices[i] >= swapchain_data->images.size()) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[i]), kVUID_Core_DrawState_SwapchainInvalidImage,
"vkQueuePresentKHR: Swapchain image index too large (%u). There are only %u images in this swapchain.",
pPresentInfo->pImageIndices[i], (uint32_t)swapchain_data->images.size());
} else {
auto image = swapchain_data->images[pPresentInfo->pImageIndices[i]];
auto image_state = GetImageState(image);
if (image_state->shared_presentable) {
image_state->layout_locked = true;
}
if (!image_state->acquired) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[i]), kVUID_Core_DrawState_SwapchainImageNotAcquired,
"vkQueuePresentKHR: Swapchain image index %u has not been acquired.",
pPresentInfo->pImageIndices[i]);
}
vector<VkImageLayout> layouts;
if (FindLayouts(image, layouts)) {
for (auto layout : layouts) {
if ((layout != VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) && (!device_extensions.vk_khr_shared_presentable_image ||
(layout != VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT,
HandleToUint64(queue), "VUID-VkPresentInfoKHR-pImageIndices-01296",
"Images passed to present must be in layout VK_IMAGE_LAYOUT_PRESENT_SRC_KHR or "
"VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR but is in %s.",
string_VkImageLayout(layout));
}
}
}
}
// All physical devices and queue families are required to be able to present to any native window on Android; require
// the application to have established support on any other platform.
if (!instance_extensions.vk_khr_android_surface) {
auto surface_state = GetSurfaceState(swapchain_data->createInfo.surface);
auto support_it = surface_state->gpu_queue_support.find({physical_device, queue_state->queueFamilyIndex});
if (support_it == surface_state->gpu_queue_support.end()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[i]), kVUID_Core_DrawState_SwapchainUnsupportedQueue,
"vkQueuePresentKHR: Presenting image without calling vkGetPhysicalDeviceSurfaceSupportKHR");
} else if (!support_it->second) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[i]), "VUID-vkQueuePresentKHR-pSwapchains-01292",
"vkQueuePresentKHR: Presenting image on queue that cannot present to this surface.");
}
}
}
}
if (pPresentInfo && pPresentInfo->pNext) {
// Verify ext struct
const auto *present_regions = lvl_find_in_chain<VkPresentRegionsKHR>(pPresentInfo->pNext);
if (present_regions) {
for (uint32_t i = 0; i < present_regions->swapchainCount; ++i) {
auto swapchain_data = GetSwapchainState(pPresentInfo->pSwapchains[i]);
assert(swapchain_data);
VkPresentRegionKHR region = present_regions->pRegions[i];
for (uint32_t j = 0; j < region.rectangleCount; ++j) {
VkRectLayerKHR rect = region.pRectangles[j];
if ((rect.offset.x + rect.extent.width) > swapchain_data->createInfo.imageExtent.width) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[i]), "VUID-VkRectLayerKHR-offset-01261",
"vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, "
"pRegion[%i].pRectangles[%i], the sum of offset.x (%i) and extent.width (%i) is greater "
"than the corresponding swapchain's imageExtent.width (%i).",
i, j, rect.offset.x, rect.extent.width, swapchain_data->createInfo.imageExtent.width);
}
if ((rect.offset.y + rect.extent.height) > swapchain_data->createInfo.imageExtent.height) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[i]), "VUID-VkRectLayerKHR-offset-01261",
"vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, "
"pRegion[%i].pRectangles[%i], the sum of offset.y (%i) and extent.height (%i) is greater "
"than the corresponding swapchain's imageExtent.height (%i).",
i, j, rect.offset.y, rect.extent.height, swapchain_data->createInfo.imageExtent.height);
}
if (rect.layer > swapchain_data->createInfo.imageArrayLayers) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[i]), "VUID-VkRectLayerKHR-layer-01262",
"vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, pRegion[%i].pRectangles[%i], the layer "
"(%i) is greater than the corresponding swapchain's imageArrayLayers (%i).",
i, j, rect.layer, swapchain_data->createInfo.imageArrayLayers);
}
}
}
}
const auto *present_times_info = lvl_find_in_chain<VkPresentTimesInfoGOOGLE>(pPresentInfo->pNext);
if (present_times_info) {
if (pPresentInfo->swapchainCount != present_times_info->swapchainCount) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pPresentInfo->pSwapchains[0]), "VUID-VkPresentTimesInfoGOOGLE-swapchainCount-01247",
"vkQueuePresentKHR(): VkPresentTimesInfoGOOGLE.swapchainCount is %i but pPresentInfo->swapchainCount "
"is %i. For VkPresentTimesInfoGOOGLE down pNext chain of VkPresentInfoKHR, "
"VkPresentTimesInfoGOOGLE.swapchainCount must equal VkPresentInfoKHR.swapchainCount.",
present_times_info->swapchainCount, pPresentInfo->swapchainCount);
}
}
}
return skip;
}
void CoreChecks::PostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo, VkResult result) {
// Semaphore waits occur before error generation, if the call reached the ICD. (Confirm?)
for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; ++i) {
auto pSemaphore = GetSemaphoreState(pPresentInfo->pWaitSemaphores[i]);
if (pSemaphore) {
pSemaphore->signaler.first = VK_NULL_HANDLE;
pSemaphore->signaled = false;
}
}
for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
// Note: this is imperfect, in that we can get confused about what did or didn't succeed-- but if the app does that, it's
// confused itself just as much.
auto local_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
if (local_result != VK_SUCCESS && local_result != VK_SUBOPTIMAL_KHR) continue; // this present didn't actually happen.
// Mark the image as having been released to the WSI
auto swapchain_data = GetSwapchainState(pPresentInfo->pSwapchains[i]);
if (swapchain_data && (swapchain_data->images.size() > pPresentInfo->pImageIndices[i])) {
auto image = swapchain_data->images[pPresentInfo->pImageIndices[i]];
auto image_state = GetImageState(image);
if (image_state) {
image_state->acquired = false;
}
}
}
// Note: even though presentation is directed to a queue, there is no direct ordering between QP and subsequent work, so QP (and
// its semaphore waits) /never/ participate in any completion proof.
}
bool CoreChecks::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
const VkSwapchainCreateInfoKHR *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchains) {
bool skip = false;
if (pCreateInfos) {
for (uint32_t i = 0; i < swapchainCount; i++) {
auto surface_state = GetSurfaceState(pCreateInfos[i].surface);
auto old_swapchain_state = GetSwapchainState(pCreateInfos[i].oldSwapchain);
std::stringstream func_name;
func_name << "vkCreateSharedSwapchainsKHR[" << swapchainCount << "]()";
skip |= ValidateCreateSwapchain(func_name.str().c_str(), &pCreateInfos[i], surface_state, old_swapchain_state);
}
}
return skip;
}
void CoreChecks::PostCallRecordCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
const VkSwapchainCreateInfoKHR *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchains,
VkResult result) {
if (pCreateInfos) {
for (uint32_t i = 0; i < swapchainCount; i++) {
auto surface_state = GetSurfaceState(pCreateInfos[i].surface);
auto old_swapchain_state = GetSwapchainState(pCreateInfos[i].oldSwapchain);
RecordCreateSwapchainState(result, &pCreateInfos[i], &pSwapchains[i], surface_state, old_swapchain_state);
}
}
}
bool CoreChecks::ValidateAcquireNextImage(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore,
VkFence fence, uint32_t *pImageIndex, const char *func_name) {
bool skip = false;
if (fence == VK_NULL_HANDLE && semaphore == VK_NULL_HANDLE) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"VUID-vkAcquireNextImageKHR-semaphore-01780",
"%s: Semaphore and fence cannot both be VK_NULL_HANDLE. There would be no way to "
"determine the completion of this operation.",
func_name);
}
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore && pSemaphore->scope == kSyncScopeInternal && pSemaphore->signaled) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,
HandleToUint64(semaphore), "VUID-vkAcquireNextImageKHR-semaphore-01286",
"%s: Semaphore must not be currently signaled or in a wait state.", func_name);
}
auto pFence = GetFenceState(fence);
if (pFence) {
skip |= ValidateFenceForSubmit(pFence);
}
auto swapchain_data = GetSwapchainState(swapchain);
if (swapchain_data && swapchain_data->retired) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(swapchain), "VUID-vkAcquireNextImageKHR-swapchain-01285",
"%s: This swapchain has been retired. The application can still present any images it "
"has acquired, but cannot acquire any more.",
func_name);
}
auto physical_device_state = GetPhysicalDeviceState();
if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState != UNCALLED) {
uint64_t acquired_images = std::count_if(swapchain_data->images.begin(), swapchain_data->images.end(),
[=](VkImage image) { return GetImageState(image)->acquired; });
if (acquired_images > swapchain_data->images.size() - physical_device_state->surfaceCapabilities.minImageCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(swapchain), kVUID_Core_DrawState_SwapchainTooManyImages,
"%s: Application has already acquired the maximum number of images (0x%" PRIxLEAST64 ")", func_name,
acquired_images);
}
}
if (swapchain_data && swapchain_data->images.size() == 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(swapchain), kVUID_Core_DrawState_SwapchainImagesNotFound,
"%s: No images found to acquire from. Application probably did not call "
"vkGetSwapchainImagesKHR after swapchain creation.",
func_name);
}
return skip;
}
bool CoreChecks::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
VkSemaphore semaphore, VkFence fence, uint32_t *pImageIndex) {
return ValidateAcquireNextImage(device, swapchain, timeout, semaphore, fence, pImageIndex, "vkAcquireNextImageKHR");
}
bool CoreChecks::PreCallValidateAcquireNextImage2KHR(VkDevice device, const VkAcquireNextImageInfoKHR *pAcquireInfo,
uint32_t *pImageIndex) {
bool skip = false;
skip |= ValidateDeviceMaskToPhysicalDeviceCount(pAcquireInfo->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pAcquireInfo->swapchain),
"VUID-VkAcquireNextImageInfoKHR-deviceMask-01290");
skip |= ValidateDeviceMaskToZero(pAcquireInfo->deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,
HandleToUint64(pAcquireInfo->swapchain), "VUID-VkAcquireNextImageInfoKHR-deviceMask-01291");
skip |= ValidateAcquireNextImage(device, pAcquireInfo->swapchain, pAcquireInfo->timeout, pAcquireInfo->semaphore,
pAcquireInfo->fence, pImageIndex, "vkAcquireNextImage2KHR");
return skip;
}
void CoreChecks::RecordAcquireNextImageState(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore,
VkFence fence, uint32_t *pImageIndex) {
auto pFence = GetFenceState(fence);
if (pFence && pFence->scope == kSyncScopeInternal) {
// Treat as inflight since it is valid to wait on this fence, even in cases where it is technically a temporary
// import
pFence->state = FENCE_INFLIGHT;
pFence->signaler.first = VK_NULL_HANDLE; // ANI isn't on a queue, so this can't participate in a completion proof.
}
auto pSemaphore = GetSemaphoreState(semaphore);
if (pSemaphore && pSemaphore->scope == kSyncScopeInternal) {
// Treat as signaled since it is valid to wait on this semaphore, even in cases where it is technically a
// temporary import
pSemaphore->signaled = true;
pSemaphore->signaler.first = VK_NULL_HANDLE;
}
// Mark the image as acquired.
auto swapchain_data = GetSwapchainState(swapchain);
if (swapchain_data && (swapchain_data->images.size() > *pImageIndex)) {
auto image = swapchain_data->images[*pImageIndex];
auto image_state = GetImageState(image);
if (image_state) {
image_state->acquired = true;
image_state->shared_presentable = swapchain_data->shared_presentable;
}
}
}
void CoreChecks::PostCallRecordAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
VkSemaphore semaphore, VkFence fence, uint32_t *pImageIndex, VkResult result) {
if ((VK_SUCCESS != result) && (VK_SUBOPTIMAL_KHR != result)) return;
RecordAcquireNextImageState(device, swapchain, timeout, semaphore, fence, pImageIndex);
}
void CoreChecks::PostCallRecordAcquireNextImage2KHR(VkDevice device, const VkAcquireNextImageInfoKHR *pAcquireInfo,
uint32_t *pImageIndex, VkResult result) {
if ((VK_SUCCESS != result) && (VK_SUBOPTIMAL_KHR != result)) return;
RecordAcquireNextImageState(device, pAcquireInfo->swapchain, pAcquireInfo->timeout, pAcquireInfo->semaphore,
pAcquireInfo->fence, pImageIndex);
}
void CoreChecks::PostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t *pPhysicalDeviceCount,
VkPhysicalDevice *pPhysicalDevices, VkResult result) {
if ((NULL != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
auto &phys_device_state = physical_device_map[pPhysicalDevices[i]];
phys_device_state.phys_device = pPhysicalDevices[i];
// Init actual features for each physical device
DispatchGetPhysicalDeviceFeatures(pPhysicalDevices[i], &phys_device_state.features2.features);
}
}
}
// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
static bool ValidateCommonGetPhysicalDeviceQueueFamilyProperties(debug_report_data *report_data, PHYSICAL_DEVICE_STATE *pd_state,
uint32_t requested_queue_family_property_count, bool qfp_null,
const char *caller_name) {
bool skip = false;
if (!qfp_null) {
// Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(pd_state->phys_device), kVUID_Core_DevLimit_MissingQueryCount,
"%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is recommended "
"to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
caller_name, caller_name);
// Then verify that pCount that is passed in on second call matches what was returned
} else if (pd_state->queue_family_count != requested_queue_family_property_count) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(pd_state->phys_device), kVUID_Core_DevLimit_CountMismatch,
"%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
". It is recommended to instead receive all the properties by calling %s with pQueueFamilyPropertyCount that was "
"previously obtained by calling %s with NULL pQueueFamilyProperties.",
caller_name, requested_queue_family_property_count, pd_state->queue_family_count, caller_name, caller_name);
}
pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
}
return skip;
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
uint32_t *pQueueFamilyPropertyCount,
VkQueueFamilyProperties *pQueueFamilyProperties) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
assert(physical_device_state);
return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(report_data, physical_device_state, *pQueueFamilyPropertyCount,
(nullptr == pQueueFamilyProperties),
"vkGetPhysicalDeviceQueueFamilyProperties()");
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
uint32_t *pQueueFamilyPropertyCount,
VkQueueFamilyProperties2KHR *pQueueFamilyProperties) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
assert(physical_device_state);
return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(report_data, physical_device_state, *pQueueFamilyPropertyCount,
(nullptr == pQueueFamilyProperties),
"vkGetPhysicalDeviceQueueFamilyProperties2()");
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
uint32_t *pQueueFamilyPropertyCount,
VkQueueFamilyProperties2KHR *pQueueFamilyProperties) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
assert(physical_device_state);
return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(report_data, physical_device_state, *pQueueFamilyPropertyCount,
(nullptr == pQueueFamilyProperties),
"vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
}
// Common function to update state for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
static void StateUpdateCommonGetPhysicalDeviceQueueFamilyProperties(PHYSICAL_DEVICE_STATE *pd_state, uint32_t count,
VkQueueFamilyProperties2KHR *pQueueFamilyProperties) {
if (!pQueueFamilyProperties) {
if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState)
pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT;
pd_state->queue_family_count = count;
} else { // Save queue family properties
pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS;
pd_state->queue_family_count = std::max(pd_state->queue_family_count, count);
pd_state->queue_family_properties.resize(std::max(static_cast<uint32_t>(pd_state->queue_family_properties.size()), count));
for (uint32_t i = 0; i < count; ++i) {
pd_state->queue_family_properties[i] = pQueueFamilyProperties[i].queueFamilyProperties;
}
}
}
void CoreChecks::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
uint32_t *pQueueFamilyPropertyCount,
VkQueueFamilyProperties *pQueueFamilyProperties) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
assert(physical_device_state);
VkQueueFamilyProperties2KHR *pqfp = nullptr;
std::vector<VkQueueFamilyProperties2KHR> qfp;
qfp.resize(*pQueueFamilyPropertyCount);
if (pQueueFamilyProperties) {
for (uint32_t i = 0; i < *pQueueFamilyPropertyCount; ++i) {
qfp[i].sType = VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2_KHR;
qfp[i].pNext = nullptr;
qfp[i].queueFamilyProperties = pQueueFamilyProperties[i];
}
pqfp = qfp.data();
}
StateUpdateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount, pqfp);
}
void CoreChecks::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
uint32_t *pQueueFamilyPropertyCount,
VkQueueFamilyProperties2KHR *pQueueFamilyProperties) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
assert(physical_device_state);
StateUpdateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
pQueueFamilyProperties);
}
void CoreChecks::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
uint32_t *pQueueFamilyPropertyCount,
VkQueueFamilyProperties2KHR *pQueueFamilyProperties) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
assert(physical_device_state);
StateUpdateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
pQueueFamilyProperties);
}
bool CoreChecks::PreCallValidateDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface,
const VkAllocationCallbacks *pAllocator) {
auto surface_state = GetSurfaceState(surface);
bool skip = false;
if ((surface_state) && (surface_state->swapchain)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT,
HandleToUint64(instance), "VUID-vkDestroySurfaceKHR-surface-01266",
"vkDestroySurfaceKHR() called before its associated VkSwapchainKHR was destroyed.");
}
return skip;
}
void CoreChecks::PreCallRecordValidateDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface,
const VkAllocationCallbacks *pAllocator) {
surface_map.erase(surface);
}
void CoreChecks::RecordVulkanSurface(VkSurfaceKHR *pSurface) {
surface_map[*pSurface] = std::unique_ptr<SURFACE_STATE>(new SURFACE_STATE{*pSurface});
}
void CoreChecks::PostCallRecordCreateDisplayPlaneSurfaceKHR(VkInstance instance, const VkDisplaySurfaceCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
#ifdef VK_USE_PLATFORM_ANDROID_KHR
void CoreChecks::PostCallRecordCreateAndroidSurfaceKHR(VkInstance instance, const VkAndroidSurfaceCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
#endif // VK_USE_PLATFORM_ANDROID_KHR
#ifdef VK_USE_PLATFORM_IOS_MVK
void CoreChecks::PostCallRecordCreateIOSSurfaceMVK(VkInstance instance, const VkIOSSurfaceCreateInfoMVK *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
#endif // VK_USE_PLATFORM_IOS_MVK
#ifdef VK_USE_PLATFORM_MACOS_MVK
void CoreChecks::PostCallRecordCreateMacOSSurfaceMVK(VkInstance instance, const VkMacOSSurfaceCreateInfoMVK *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
#endif // VK_USE_PLATFORM_MACOS_MVK
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
void CoreChecks::PostCallRecordCreateWaylandSurfaceKHR(VkInstance instance, const VkWaylandSurfaceCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceWaylandPresentationSupportKHR(VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
struct wl_display *display) {
const auto pd_state = GetPhysicalDeviceState(physicalDevice);
return ValidatePhysicalDeviceQueueFamily(pd_state, queueFamilyIndex,
"VUID-vkGetPhysicalDeviceWaylandPresentationSupportKHR-queueFamilyIndex-01306",
"vkGetPhysicalDeviceWaylandPresentationSupportKHR", "queueFamilyIndex");
}
#endif // VK_USE_PLATFORM_WAYLAND_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
void CoreChecks::PostCallRecordCreateWin32SurfaceKHR(VkInstance instance, const VkWin32SurfaceCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceWin32PresentationSupportKHR(VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex) {
const auto pd_state = GetPhysicalDeviceState(physicalDevice);
return ValidatePhysicalDeviceQueueFamily(pd_state, queueFamilyIndex,
"VUID-vkGetPhysicalDeviceWin32PresentationSupportKHR-queueFamilyIndex-01309",
"vkGetPhysicalDeviceWin32PresentationSupportKHR", "queueFamilyIndex");
}
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_XCB_KHR
void CoreChecks::PostCallRecordCreateXcbSurfaceKHR(VkInstance instance, const VkXcbSurfaceCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceXcbPresentationSupportKHR(VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex, xcb_connection_t *connection,
xcb_visualid_t visual_id) {
const auto pd_state = GetPhysicalDeviceState(physicalDevice);
return ValidatePhysicalDeviceQueueFamily(pd_state, queueFamilyIndex,
"VUID-vkGetPhysicalDeviceXcbPresentationSupportKHR-queueFamilyIndex-01312",
"vkGetPhysicalDeviceXcbPresentationSupportKHR", "queueFamilyIndex");
}
#endif // VK_USE_PLATFORM_XCB_KHR
#ifdef VK_USE_PLATFORM_XLIB_KHR
void CoreChecks::PostCallRecordCreateXlibSurfaceKHR(VkInstance instance, const VkXlibSurfaceCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordVulkanSurface(pSurface);
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceXlibPresentationSupportKHR(VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex, Display *dpy,
VisualID visualID) {
const auto pd_state = GetPhysicalDeviceState(physicalDevice);
return ValidatePhysicalDeviceQueueFamily(pd_state, queueFamilyIndex,
"VUID-vkGetPhysicalDeviceXlibPresentationSupportKHR-queueFamilyIndex-01315",
"vkGetPhysicalDeviceXlibPresentationSupportKHR", "queueFamilyIndex");
}
#endif // VK_USE_PLATFORM_XLIB_KHR
void CoreChecks::PostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
VkSurfaceCapabilitiesKHR *pSurfaceCapabilities,
VkResult result) {
if (VK_SUCCESS != result) return;
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
physical_device_state->surfaceCapabilities = *pSurfaceCapabilities;
}
void CoreChecks::PostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR *pSurfaceInfo,
VkSurfaceCapabilities2KHR *pSurfaceCapabilities,
VkResult result) {
if (VK_SUCCESS != result) return;
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
physical_device_state->surfaceCapabilities = pSurfaceCapabilities->surfaceCapabilities;
}
void CoreChecks::PostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
VkSurfaceCapabilities2EXT *pSurfaceCapabilities,
VkResult result) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
physical_device_state->surfaceCapabilities.minImageCount = pSurfaceCapabilities->minImageCount;
physical_device_state->surfaceCapabilities.maxImageCount = pSurfaceCapabilities->maxImageCount;
physical_device_state->surfaceCapabilities.currentExtent = pSurfaceCapabilities->currentExtent;
physical_device_state->surfaceCapabilities.minImageExtent = pSurfaceCapabilities->minImageExtent;
physical_device_state->surfaceCapabilities.maxImageExtent = pSurfaceCapabilities->maxImageExtent;
physical_device_state->surfaceCapabilities.maxImageArrayLayers = pSurfaceCapabilities->maxImageArrayLayers;
physical_device_state->surfaceCapabilities.supportedTransforms = pSurfaceCapabilities->supportedTransforms;
physical_device_state->surfaceCapabilities.currentTransform = pSurfaceCapabilities->currentTransform;
physical_device_state->surfaceCapabilities.supportedCompositeAlpha = pSurfaceCapabilities->supportedCompositeAlpha;
physical_device_state->surfaceCapabilities.supportedUsageFlags = pSurfaceCapabilities->supportedUsageFlags;
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex,
VkSurfaceKHR surface, VkBool32 *pSupported) {
const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
return ValidatePhysicalDeviceQueueFamily(physical_device_state, queueFamilyIndex,
"VUID-vkGetPhysicalDeviceSurfaceSupportKHR-queueFamilyIndex-01269",
"vkGetPhysicalDeviceSurfaceSupportKHR", "queueFamilyIndex");
}
void CoreChecks::PostCallRecordGetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex,
VkSurfaceKHR surface, VkBool32 *pSupported, VkResult result) {
if (VK_SUCCESS != result) return;
auto surface_state = GetSurfaceState(surface);
surface_state->gpu_queue_support[{physicalDevice, queueFamilyIndex}] = (*pSupported == VK_TRUE);
}
void CoreChecks::PostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
uint32_t *pPresentModeCount, VkPresentModeKHR *pPresentModes,
VkResult result) {
if ((VK_SUCCESS != result) && (VK_INCOMPLETE != result)) return;
// TODO: This isn't quite right -- available modes may differ by surface AND physical device.
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
auto &call_state = physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState;
if (*pPresentModeCount) {
if (call_state < QUERY_COUNT) call_state = QUERY_COUNT;
if (*pPresentModeCount > physical_device_state->present_modes.size())
physical_device_state->present_modes.resize(*pPresentModeCount);
}
if (pPresentModes) {
if (call_state < QUERY_DETAILS) call_state = QUERY_DETAILS;
for (uint32_t i = 0; i < *pPresentModeCount; i++) {
physical_device_state->present_modes[i] = pPresentModes[i];
}
}
}
bool CoreChecks::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
uint32_t *pSurfaceFormatCount,
VkSurfaceFormatKHR *pSurfaceFormats) {
if (!pSurfaceFormats) return false;
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
auto &call_state = physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
bool skip = false;
switch (call_state) {
case UNCALLED:
// Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
// previously call this function with a NULL value of pSurfaceFormats:
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), kVUID_Core_DevLimit_MustQueryCount,
"vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
"positive value has been seen for pSurfaceFormats.");
break;
default:
auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
if (prev_format_count != *pSurfaceFormatCount) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), kVUID_Core_DevLimit_CountMismatch,
"vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
"pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
"when pSurfaceFormatCount was NULL.",
*pSurfaceFormatCount, prev_format_count);
}
break;
}
return skip;
}
void CoreChecks::PostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
uint32_t *pSurfaceFormatCount,
VkSurfaceFormatKHR *pSurfaceFormats, VkResult result) {
if ((VK_SUCCESS != result) && (VK_INCOMPLETE != result)) return;
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
auto &call_state = physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
if (*pSurfaceFormatCount) {
if (call_state < QUERY_COUNT) call_state = QUERY_COUNT;
if (*pSurfaceFormatCount > physical_device_state->surface_formats.size())
physical_device_state->surface_formats.resize(*pSurfaceFormatCount);
}
if (pSurfaceFormats) {
if (call_state < QUERY_DETAILS) call_state = QUERY_DETAILS;
for (uint32_t i = 0; i < *pSurfaceFormatCount; i++) {
physical_device_state->surface_formats[i] = pSurfaceFormats[i];
}
}
}
void CoreChecks::PostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR *pSurfaceInfo,
uint32_t *pSurfaceFormatCount,
VkSurfaceFormat2KHR *pSurfaceFormats, VkResult result) {
if ((VK_SUCCESS != result) && (VK_INCOMPLETE != result)) return;
auto physicalDeviceState = GetPhysicalDeviceState(physicalDevice);
if (*pSurfaceFormatCount) {
if (physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
}
if (*pSurfaceFormatCount > physicalDeviceState->surface_formats.size())
physicalDeviceState->surface_formats.resize(*pSurfaceFormatCount);
}
if (pSurfaceFormats) {
if (physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
}
for (uint32_t i = 0; i < *pSurfaceFormatCount; i++) {
physicalDeviceState->surface_formats[i] = pSurfaceFormats[i].surfaceFormat;
}
}
}
void CoreChecks::PreCallRecordCmdBeginDebugUtilsLabelEXT(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT *pLabelInfo) {
BeginCmdDebugUtilsLabel(report_data, commandBuffer, pLabelInfo);
}
void CoreChecks::PostCallRecordCmdEndDebugUtilsLabelEXT(VkCommandBuffer commandBuffer) {
EndCmdDebugUtilsLabel(report_data, commandBuffer);
}
void CoreChecks::PreCallRecordCmdInsertDebugUtilsLabelEXT(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT *pLabelInfo) {
InsertCmdDebugUtilsLabel(report_data, commandBuffer, pLabelInfo);
// Squirrel away an easily accessible copy.
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
cb_state->debug_label = LoggingLabel(pLabelInfo);
}
void CoreChecks::PostRecordEnumeratePhysicalDeviceGroupsState(uint32_t *pPhysicalDeviceGroupCount,
VkPhysicalDeviceGroupPropertiesKHR *pPhysicalDeviceGroupProperties) {
if (NULL != pPhysicalDeviceGroupProperties) {
for (uint32_t i = 0; i < *pPhysicalDeviceGroupCount; i++) {
for (uint32_t j = 0; j < pPhysicalDeviceGroupProperties[i].physicalDeviceCount; j++) {
VkPhysicalDevice cur_phys_dev = pPhysicalDeviceGroupProperties[i].physicalDevices[j];
auto &phys_device_state = physical_device_map[cur_phys_dev];
phys_device_state.phys_device = cur_phys_dev;
// Init actual features for each physical device
DispatchGetPhysicalDeviceFeatures(cur_phys_dev, &phys_device_state.features2.features);
}
}
}
}
void CoreChecks::PostCallRecordEnumeratePhysicalDeviceGroups(VkInstance instance, uint32_t *pPhysicalDeviceGroupCount,
VkPhysicalDeviceGroupPropertiesKHR *pPhysicalDeviceGroupProperties,
VkResult result) {
if ((VK_SUCCESS != result) && (VK_INCOMPLETE != result)) return;
PostRecordEnumeratePhysicalDeviceGroupsState(pPhysicalDeviceGroupCount, pPhysicalDeviceGroupProperties);
}
void CoreChecks::PostCallRecordEnumeratePhysicalDeviceGroupsKHR(VkInstance instance, uint32_t *pPhysicalDeviceGroupCount,
VkPhysicalDeviceGroupPropertiesKHR *pPhysicalDeviceGroupProperties,
VkResult result) {
if ((VK_SUCCESS != result) && (VK_INCOMPLETE != result)) return;
PostRecordEnumeratePhysicalDeviceGroupsState(pPhysicalDeviceGroupCount, pPhysicalDeviceGroupProperties);
}
bool CoreChecks::ValidateDescriptorUpdateTemplate(const char *func_name,
const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo) {
bool skip = false;
const auto layout = GetDescriptorSetLayout(this, pCreateInfo->descriptorSetLayout);
if (VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET == pCreateInfo->templateType && !layout) {
auto ds_uint = HandleToUint64(pCreateInfo->descriptorSetLayout);
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, ds_uint,
"VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00350",
"%s: Invalid pCreateInfo->descriptorSetLayout (%s)", func_name, report_data->FormatHandle(ds_uint).c_str());
} else if (VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR == pCreateInfo->templateType) {
auto bind_point = pCreateInfo->pipelineBindPoint;
bool valid_bp = (bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS) || (bind_point == VK_PIPELINE_BIND_POINT_COMPUTE);
if (!valid_bp) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00351",
"%s: Invalid pCreateInfo->pipelineBindPoint (%" PRIu32 ").", func_name, static_cast<uint32_t>(bind_point));
}
const auto pipeline_layout = GetPipelineLayout(pCreateInfo->pipelineLayout);
if (!pipeline_layout) {
uint64_t pl_uint = HandleToUint64(pCreateInfo->pipelineLayout);
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, pl_uint,
"VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00352",
"%s: Invalid pCreateInfo->pipelineLayout (%s)", func_name, report_data->FormatHandle(pl_uint).c_str());
} else {
const uint32_t pd_set = pCreateInfo->set;
if ((pd_set >= pipeline_layout->set_layouts.size()) || !pipeline_layout->set_layouts[pd_set] ||
!pipeline_layout->set_layouts[pd_set]->IsPushDescriptor()) {
uint64_t pl_uint = HandleToUint64(pCreateInfo->pipelineLayout);
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT,
pl_uint, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00353",
"%s: pCreateInfo->set (%" PRIu32
") does not refer to the push descriptor set layout for pCreateInfo->pipelineLayout (%s).",
func_name, pd_set, report_data->FormatHandle(pl_uint).c_str());
}
}
}
return skip;
}
bool CoreChecks::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate) {
bool skip = ValidateDescriptorUpdateTemplate("vkCreateDescriptorUpdateTemplate()", pCreateInfo);
return skip;
}
bool CoreChecks::PreCallValidateCreateDescriptorUpdateTemplateKHR(VkDevice device,
const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate) {
bool skip = ValidateDescriptorUpdateTemplate("vkCreateDescriptorUpdateTemplateKHR()", pCreateInfo);
return skip;
}
void CoreChecks::PreCallRecordDestroyDescriptorUpdateTemplate(VkDevice device,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
const VkAllocationCallbacks *pAllocator) {
if (!descriptorUpdateTemplate) return;
desc_template_map.erase(descriptorUpdateTemplate);
}
void CoreChecks::PreCallRecordDestroyDescriptorUpdateTemplateKHR(VkDevice device,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
const VkAllocationCallbacks *pAllocator) {
if (!descriptorUpdateTemplate) return;
desc_template_map.erase(descriptorUpdateTemplate);
}
void CoreChecks::RecordCreateDescriptorUpdateTemplateState(const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo,
VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate) {
safe_VkDescriptorUpdateTemplateCreateInfo *local_create_info = new safe_VkDescriptorUpdateTemplateCreateInfo(pCreateInfo);
std::unique_ptr<TEMPLATE_STATE> template_state(new TEMPLATE_STATE(*pDescriptorUpdateTemplate, local_create_info));
desc_template_map[*pDescriptorUpdateTemplate] = std::move(template_state);
}
void CoreChecks::PostCallRecordCreateDescriptorUpdateTemplate(VkDevice device,
const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordCreateDescriptorUpdateTemplateState(pCreateInfo, pDescriptorUpdateTemplate);
}
void CoreChecks::PostCallRecordCreateDescriptorUpdateTemplateKHR(VkDevice device,
const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate,
VkResult result) {
if (VK_SUCCESS != result) return;
RecordCreateDescriptorUpdateTemplateState(pCreateInfo, pDescriptorUpdateTemplate);
}
bool CoreChecks::ValidateUpdateDescriptorSetWithTemplate(VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
const void *pData) {
bool skip = false;
auto const template_map_entry = desc_template_map.find(descriptorUpdateTemplate);
if ((template_map_entry == desc_template_map.end()) || (template_map_entry->second.get() == nullptr)) {
// Object tracker will report errors for invalid descriptorUpdateTemplate values, avoiding a crash in release builds
// but retaining the assert as template support is new enough to want to investigate these in debug builds.
assert(0);
} else {
const TEMPLATE_STATE *template_state = template_map_entry->second.get();
// TODO: Validate template push descriptor updates
if (template_state->create_info.templateType == VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET) {
skip = ValidateUpdateDescriptorSetsWithTemplateKHR(descriptorSet, template_state, pData);
}
}
return skip;
}
bool CoreChecks::PreCallValidateUpdateDescriptorSetWithTemplate(VkDevice device, VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const void *pData) {
return ValidateUpdateDescriptorSetWithTemplate(descriptorSet, descriptorUpdateTemplate, pData);
}
bool CoreChecks::PreCallValidateUpdateDescriptorSetWithTemplateKHR(VkDevice device, VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
const void *pData) {
return ValidateUpdateDescriptorSetWithTemplate(descriptorSet, descriptorUpdateTemplate, pData);
}
void CoreChecks::RecordUpdateDescriptorSetWithTemplateState(VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
const void *pData) {
auto const template_map_entry = desc_template_map.find(descriptorUpdateTemplate);
if ((template_map_entry == desc_template_map.end()) || (template_map_entry->second.get() == nullptr)) {
assert(0);
} else {
const TEMPLATE_STATE *template_state = template_map_entry->second.get();
// TODO: Record template push descriptor updates
if (template_state->create_info.templateType == VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET) {
PerformUpdateDescriptorSetsWithTemplateKHR(descriptorSet, template_state, pData);
}
}
}
void CoreChecks::PreCallRecordUpdateDescriptorSetWithTemplate(VkDevice device, VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const void *pData) {
RecordUpdateDescriptorSetWithTemplateState(descriptorSet, descriptorUpdateTemplate, pData);
}
void CoreChecks::PreCallRecordUpdateDescriptorSetWithTemplateKHR(VkDevice device, VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
const void *pData) {
RecordUpdateDescriptorSetWithTemplateState(descriptorSet, descriptorUpdateTemplate, pData);
}
static std::shared_ptr<cvdescriptorset::DescriptorSetLayout const> GetDslFromPipelineLayout(
PIPELINE_LAYOUT_STATE const *layout_data, uint32_t set) {
std::shared_ptr<cvdescriptorset::DescriptorSetLayout const> dsl = nullptr;
if (layout_data && (set < layout_data->set_layouts.size())) {
dsl = layout_data->set_layouts[set];
}
return dsl;
}
bool CoreChecks::PreCallValidateCmdPushDescriptorSetWithTemplateKHR(VkCommandBuffer commandBuffer,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
VkPipelineLayout layout, uint32_t set, const void *pData) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
const char *const func_name = "vkPushDescriptorSetWithTemplateKHR()";
bool skip = false;
skip |= ValidateCmd(cb_state, CMD_PUSHDESCRIPTORSETWITHTEMPLATEKHR, func_name);
auto layout_data = GetPipelineLayout(layout);
auto dsl = GetDslFromPipelineLayout(layout_data, set);
const auto layout_u64 = HandleToUint64(layout);
// Validate the set index points to a push descriptor set and is in range
if (dsl) {
if (!dsl->IsPushDescriptor()) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, layout_u64,
"VUID-vkCmdPushDescriptorSetKHR-set-00365",
"%s: Set index %" PRIu32 " does not match push descriptor set layout index for VkPipelineLayout %s.",
func_name, set, report_data->FormatHandle(layout_u64).c_str());
}
} else if (layout_data && (set >= layout_data->set_layouts.size())) {
skip = log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, layout_u64,
"VUID-vkCmdPushDescriptorSetKHR-set-00364",
"%s: Set index %" PRIu32 " is outside of range for VkPipelineLayout %s (set < %" PRIu32 ").", func_name, set,
report_data->FormatHandle(layout_u64).c_str(), static_cast<uint32_t>(layout_data->set_layouts.size()));
}
const auto template_state = GetDescriptorTemplateState(descriptorUpdateTemplate);
if (template_state) {
const auto &template_ci = template_state->create_info;
static const std::map<VkPipelineBindPoint, std::string> bind_errors = {
std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-00366"),
std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-00366"),
std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_NV,
"VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-00366")};
skip |= ValidatePipelineBindPoint(cb_state, template_ci.pipelineBindPoint, func_name, bind_errors);
if (template_ci.templateType != VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), kVUID_Core_PushDescriptorUpdate_TemplateType,
"%s: descriptorUpdateTemplate %s was not created with flag "
"VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR.",
func_name, report_data->FormatHandle(descriptorUpdateTemplate).c_str());
}
if (template_ci.set != set) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), kVUID_Core_PushDescriptorUpdate_Template_SetMismatched,
"%s: descriptorUpdateTemplate %s created with set %" PRIu32
" does not match command parameter set %" PRIu32 ".",
func_name, report_data->FormatHandle(descriptorUpdateTemplate).c_str(), template_ci.set, set);
}
if (!CompatForSet(set, layout_data, GetPipelineLayout(template_ci.pipelineLayout))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), kVUID_Core_PushDescriptorUpdate_Template_LayoutMismatched,
"%s: descriptorUpdateTemplate %s created with pipelineLayout %s is incompatible with command parameter "
"layout %s for set %" PRIu32,
func_name, report_data->FormatHandle(descriptorUpdateTemplate).c_str(),
report_data->FormatHandle(template_ci.pipelineLayout).c_str(),
report_data->FormatHandle(layout).c_str(), set);
}
}
if (dsl && template_state) {
// Create an empty proxy in order to use the existing descriptor set update validation
cvdescriptorset::DescriptorSet proxy_ds(VK_NULL_HANDLE, VK_NULL_HANDLE, dsl, 0, this);
// Decode the template into a set of write updates
cvdescriptorset::DecodedTemplateUpdate decoded_template(this, VK_NULL_HANDLE, template_state, pData,
dsl->GetDescriptorSetLayout());
// Validate the decoded update against the proxy_ds
skip |= proxy_ds.ValidatePushDescriptorsUpdate(report_data, static_cast<uint32_t>(decoded_template.desc_writes.size()),
decoded_template.desc_writes.data(), func_name);
}
return skip;
}
void CoreChecks::PreCallRecordCmdPushDescriptorSetWithTemplateKHR(VkCommandBuffer commandBuffer,
VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate,
VkPipelineLayout layout, uint32_t set, const void *pData) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
const auto template_state = GetDescriptorTemplateState(descriptorUpdateTemplate);
if (template_state) {
auto layout_data = GetPipelineLayout(layout);
auto dsl = GetDslFromPipelineLayout(layout_data, set);
const auto &template_ci = template_state->create_info;
if (dsl && !dsl->IsDestroyed()) {
// Decode the template into a set of write updates
cvdescriptorset::DecodedTemplateUpdate decoded_template(this, VK_NULL_HANDLE, template_state, pData,
dsl->GetDescriptorSetLayout());
RecordCmdPushDescriptorSetState(cb_state, template_ci.pipelineBindPoint, layout, set,
static_cast<uint32_t>(decoded_template.desc_writes.size()),
decoded_template.desc_writes.data());
}
}
}
void CoreChecks::RecordGetPhysicalDeviceDisplayPlanePropertiesState(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount,
void *pProperties) {
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
if (*pPropertyCount) {
if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
}
physical_device_state->display_plane_property_count = *pPropertyCount;
}
if (pProperties) {
if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
}
}
}
void CoreChecks::PostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount,
VkDisplayPlanePropertiesKHR *pProperties,
VkResult result) {
if ((VK_SUCCESS != result) && (VK_INCOMPLETE != result)) return;
RecordGetPhysicalDeviceDisplayPlanePropertiesState(physicalDevice, pPropertyCount, pProperties);
}
void CoreChecks::PostCallRecordGetPhysicalDeviceDisplayPlaneProperties2KHR(VkPhysicalDevice physicalDevice,
uint32_t *pPropertyCount,
VkDisplayPlaneProperties2KHR *pProperties,
VkResult result) {
if ((VK_SUCCESS != result) && (VK_INCOMPLETE != result)) return;
RecordGetPhysicalDeviceDisplayPlanePropertiesState(physicalDevice, pPropertyCount, pProperties);
}
bool CoreChecks::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
const char *api_name) {
bool skip = false;
auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), kVUID_Core_Swapchain_GetSupportedDisplaysWithoutQuery,
"Potential problem with calling %s() without first querying vkGetPhysicalDeviceDisplayPlanePropertiesKHR "
"or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
api_name);
} else {
if (planeIndex >= physical_device_state->display_plane_property_count) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), "VUID-vkGetDisplayPlaneSupportedDisplaysKHR-planeIndex-01249",
"%s(): planeIndex must be in the range [0, %d] that was returned by vkGetPhysicalDeviceDisplayPlanePropertiesKHR "
"or vkGetPhysicalDeviceDisplayPlaneProperties2KHR. Do you have the plane index hardcoded?",
api_name, physical_device_state->display_plane_property_count - 1);
}
}
return skip;
}
bool CoreChecks::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
uint32_t *pDisplayCount, VkDisplayKHR *pDisplays) {
bool skip = false;
skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, planeIndex,
"vkGetDisplayPlaneSupportedDisplaysKHR");
return skip;
}
bool CoreChecks::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
uint32_t planeIndex, VkDisplayPlaneCapabilitiesKHR *pCapabilities) {
bool skip = false;
skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, planeIndex, "vkGetDisplayPlaneCapabilitiesKHR");
return skip;
}
bool CoreChecks::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
const VkDisplayPlaneInfo2KHR *pDisplayPlaneInfo,
VkDisplayPlaneCapabilities2KHR *pCapabilities) {
bool skip = false;
skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, pDisplayPlaneInfo->planeIndex,
"vkGetDisplayPlaneCapabilities2KHR");
return skip;
}
bool CoreChecks::PreCallValidateCmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer,
const VkDebugMarkerMarkerInfoEXT *pMarkerInfo) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
return ValidateCmd(cb_state, CMD_DEBUGMARKERBEGINEXT, "vkCmdDebugMarkerBeginEXT()");
}
bool CoreChecks::PreCallValidateCmdDebugMarkerEndEXT(VkCommandBuffer commandBuffer) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
return ValidateCmd(cb_state, CMD_DEBUGMARKERENDEXT, "vkCmdDebugMarkerEndEXT()");
}
bool CoreChecks::PreCallValidateCmdBeginQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query,
VkQueryControlFlags flags, uint32_t index) {
if (disabled.query_validation) return false;
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
QueryObject query_obj(queryPool, query, index);
const char *cmd_name = "vkCmdBeginQueryIndexedEXT()";
bool skip = ValidateBeginQuery(
cb_state, query_obj, flags, CMD_BEGINQUERYINDEXEDEXT, cmd_name, "VUID-vkCmdBeginQueryIndexedEXT-commandBuffer-cmdpool",
"VUID-vkCmdBeginQueryIndexedEXT-queryType-02338", "VUID-vkCmdBeginQueryIndexedEXT-queryType-02333",
"VUID-vkCmdBeginQueryIndexedEXT-queryType-02331", "VUID-vkCmdBeginQueryIndexedEXT-query-02332");
// Extension specific VU's
const auto &query_pool_ci = GetQueryPoolState(query_obj.pool)->createInfo;
if (query_pool_ci.queryType == VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT) {
if (device_extensions.vk_ext_transform_feedback &&
(index >= phys_dev_ext_props.transform_feedback_props.maxTransformFeedbackStreams)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdBeginQueryIndexedEXT-queryType-02339",
"%s: index %" PRIu32
" must be less than VkPhysicalDeviceTransformFeedbackPropertiesEXT::maxTransformFeedbackStreams %" PRIu32 ".",
cmd_name, index, phys_dev_ext_props.transform_feedback_props.maxTransformFeedbackStreams);
}
} else if (index != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdBeginQueryIndexedEXT-queryType-02340",
"%s: index %" PRIu32
" must be zero if the query pool %s was not created with type VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT.",
cmd_name, index, report_data->FormatHandle(queryPool).c_str());
}
return skip;
}
void CoreChecks::PostCallRecordCmdBeginQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query,
VkQueryControlFlags flags, uint32_t index) {
QueryObject query_obj = {queryPool, query, index};
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
RecordBeginQuery(cb_state, query_obj);
}
bool CoreChecks::PreCallValidateCmdEndQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query,
uint32_t index) {
if (disabled.query_validation) return false;
QueryObject query_obj = {queryPool, query, index};
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
assert(cb_state);
return ValidateCmdEndQuery(cb_state, query_obj, CMD_ENDQUERYINDEXEDEXT, "vkCmdEndQueryIndexedEXT()",
"VUID-vkCmdEndQueryIndexedEXT-commandBuffer-cmdpool", "VUID-vkCmdEndQueryIndexedEXT-None-02342");
}
void CoreChecks::PostCallRecordCmdEndQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query,
uint32_t index) {
QueryObject query_obj = {queryPool, query, index};
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
RecordCmdEndQuery(cb_state, query_obj);
}
bool CoreChecks::PreCallValidateCmdSetDiscardRectangleEXT(VkCommandBuffer commandBuffer, uint32_t firstDiscardRectangle,
uint32_t discardRectangleCount, const VkRect2D *pDiscardRectangles) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
// Minimal validation for command buffer state
return ValidateCmd(cb_state, CMD_SETDISCARDRECTANGLEEXT, "vkCmdSetDiscardRectangleEXT()");
}
bool CoreChecks::PreCallValidateCmdSetSampleLocationsEXT(VkCommandBuffer commandBuffer,
const VkSampleLocationsInfoEXT *pSampleLocationsInfo) {
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
// Minimal validation for command buffer state
return ValidateCmd(cb_state, CMD_SETSAMPLELOCATIONSEXT, "vkCmdSetSampleLocationsEXT()");
}
bool CoreChecks::ValidateCreateSamplerYcbcrConversion(const char *func_name,
const VkSamplerYcbcrConversionCreateInfo *create_info) {
bool skip = false;
if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
skip |= ValidateCreateSamplerYcbcrConversionANDROID(create_info);
} else { // Not android hardware buffer
if (VK_FORMAT_UNDEFINED == create_info->format) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, 0,
"VUID-VkSamplerYcbcrConversionCreateInfo-format-01649",
"%s: CreateInfo format type is VK_FORMAT_UNDEFINED.", func_name);
}
}
return skip;
}
bool CoreChecks::PreCallValidateCreateSamplerYcbcrConversion(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkSamplerYcbcrConversion *pYcbcrConversion) {
return ValidateCreateSamplerYcbcrConversion("vkCreateSamplerYcbcrConversion()", pCreateInfo);
}
bool CoreChecks::PreCallValidateCreateSamplerYcbcrConversionKHR(VkDevice device,
const VkSamplerYcbcrConversionCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkSamplerYcbcrConversion *pYcbcrConversion) {
return ValidateCreateSamplerYcbcrConversion("vkCreateSamplerYcbcrConversionKHR()", pCreateInfo);
}
void CoreChecks::RecordCreateSamplerYcbcrConversionState(const VkSamplerYcbcrConversionCreateInfo *create_info,
VkSamplerYcbcrConversion ycbcr_conversion) {
if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
RecordCreateSamplerYcbcrConversionANDROID(create_info, ycbcr_conversion);
}
}
void CoreChecks::PostCallRecordCreateSamplerYcbcrConversion(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkSamplerYcbcrConversion *pYcbcrConversion, VkResult result) {
if (VK_SUCCESS != result) return;
RecordCreateSamplerYcbcrConversionState(pCreateInfo, *pYcbcrConversion);
}
void CoreChecks::PostCallRecordCreateSamplerYcbcrConversionKHR(VkDevice device,
const VkSamplerYcbcrConversionCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkSamplerYcbcrConversion *pYcbcrConversion, VkResult result) {
if (VK_SUCCESS != result) return;
RecordCreateSamplerYcbcrConversionState(pCreateInfo, *pYcbcrConversion);
}
void CoreChecks::PostCallRecordDestroySamplerYcbcrConversion(VkDevice device, VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks *pAllocator) {
if (!ycbcrConversion) return;
if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
RecordDestroySamplerYcbcrConversionANDROID(ycbcrConversion);
}
}
void CoreChecks::PostCallRecordDestroySamplerYcbcrConversionKHR(VkDevice device, VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks *pAllocator) {
if (!ycbcrConversion) return;
if (device_extensions.vk_android_external_memory_android_hardware_buffer) {
RecordDestroySamplerYcbcrConversionANDROID(ycbcrConversion);
}
}
bool CoreChecks::PreCallValidateGetBufferDeviceAddressEXT(VkDevice device, const VkBufferDeviceAddressInfoEXT *pInfo) {
bool skip = false;
if (!enabled_features.buffer_address.bufferDeviceAddress) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
HandleToUint64(pInfo->buffer), "VUID-vkGetBufferDeviceAddressEXT-None-02598",
"The bufferDeviceAddress feature must: be enabled.");
}
if (physical_device_count > 1 && !enabled_features.buffer_address.bufferDeviceAddressMultiDevice) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,
HandleToUint64(pInfo->buffer), "VUID-vkGetBufferDeviceAddressEXT-device-02599",
"If device was created with multiple physical devices, then the "
"bufferDeviceAddressMultiDevice feature must: be enabled.");
}
auto buffer_state = GetBufferState(pInfo->buffer);
if (buffer_state) {
if (!(buffer_state->createInfo.flags & VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT)) {
skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkGetBufferDeviceAddressEXT()",
"VUID-VkBufferDeviceAddressInfoEXT-buffer-02600");
}
skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT, true,
"VUID-VkBufferDeviceAddressInfoEXT-buffer-02601", "vkGetBufferDeviceAddressEXT()",
"VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT");
}
return skip;
}
void CoreChecks::PreCallRecordGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties *pPhysicalDeviceProperties) {
if (enabled.gpu_validation && enabled.gpu_validation_reserve_binding_slot) {
if (pPhysicalDeviceProperties->limits.maxBoundDescriptorSets > 1) {
pPhysicalDeviceProperties->limits.maxBoundDescriptorSets -= 1;
} else {
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,
HandleToUint64(physicalDevice), "UNASSIGNED-GPU-Assisted Validation Setup Error.",
"Unable to reserve descriptor binding slot on a device with only one slot.");
}
}
}
VkResult CoreChecks::CoreLayerCreateValidationCacheEXT(VkDevice device, const VkValidationCacheCreateInfoEXT *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkValidationCacheEXT *pValidationCache) {
*pValidationCache = ValidationCache::Create(pCreateInfo);
return *pValidationCache ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED;
}
void CoreChecks::CoreLayerDestroyValidationCacheEXT(VkDevice device, VkValidationCacheEXT validationCache,
const VkAllocationCallbacks *pAllocator) {
delete CastFromHandle<ValidationCache *>(validationCache);
}
VkResult CoreChecks::CoreLayerGetValidationCacheDataEXT(VkDevice device, VkValidationCacheEXT validationCache, size_t *pDataSize,
void *pData) {
size_t inSize = *pDataSize;
CastFromHandle<ValidationCache *>(validationCache)->Write(pDataSize, pData);
return (pData && *pDataSize != inSize) ? VK_INCOMPLETE : VK_SUCCESS;
}
VkResult CoreChecks::CoreLayerMergeValidationCachesEXT(VkDevice device, VkValidationCacheEXT dstCache, uint32_t srcCacheCount,
const VkValidationCacheEXT *pSrcCaches) {
bool skip = false;
auto dst = CastFromHandle<ValidationCache *>(dstCache);
VkResult result = VK_SUCCESS;
for (uint32_t i = 0; i < srcCacheCount; i++) {
auto src = CastFromHandle<const ValidationCache *>(pSrcCaches[i]);
if (src == dst) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT, 0,
"VUID-vkMergeValidationCachesEXT-dstCache-01536",
"vkMergeValidationCachesEXT: dstCache (0x%" PRIx64 ") must not appear in pSrcCaches array.",
HandleToUint64(dstCache));
result = VK_ERROR_VALIDATION_FAILED_EXT;
}
if (!skip) {
dst->Merge(src);
}
}
return result;
}
bool CoreChecks::PreCallValidateCmdSetDeviceMask(VkCommandBuffer commandBuffer, uint32_t deviceMask) {
bool skip = false;
CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer);
skip |= ValidateDeviceMaskToPhysicalDeviceCount(deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetDeviceMask-deviceMask-00108");
skip |= ValidateDeviceMaskToZero(deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer),
"VUID-vkCmdSetDeviceMask-deviceMask-00109");
skip |= ValidateDeviceMaskToCommandBuffer(cb_state, deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetDeviceMask-deviceMask-00110");
if (cb_state->activeRenderPass) {
skip |= ValidateDeviceMaskToRenderPass(cb_state, deviceMask, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,
HandleToUint64(commandBuffer), "VUID-vkCmdSetDeviceMask-deviceMask-00111");
}
return skip;
}
| 1 | 10,839 | You're killing this "else" case here which currently flags an error when maxBoundDescriptorSets == 0. | KhronosGroup-Vulkan-ValidationLayers | cpp |
@@ -509,6 +509,16 @@ fill_refs_and_checksums_from_summary (GVariant *summary,
return TRUE;
}
+static gboolean
+remove_null_checksum_refs (gpointer key,
+ gpointer value,
+ gpointer user_data)
+{
+ const char *checksum = value;
+
+ return (checksum == NULL);
+}
+
/* Given a summary file (@summary_bytes), extract the refs it lists, and use that
* to fill in the checksums in the @supported_ref_to_checksum map. This includes
* the main refs list in the summary, and the map of collection IDs to further | 1 | /*
* Copyright © 2016 Kinvolk GmbH
* Copyright © 2017 Endless Mobile, Inc.
*
* SPDX-License-Identifier: LGPL-2.0+
*
* 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 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Authors:
* - Krzesimir Nowak <krzesimir@kinvolk.io>
* - Philip Withnall <withnall@endlessm.com>
*/
#include "config.h"
#ifdef HAVE_AVAHI
#include <avahi-client/client.h>
#include <avahi-client/lookup.h>
#include <avahi-common/address.h>
#include <avahi-common/defs.h>
#include <avahi-common/error.h>
#include <avahi-common/malloc.h>
#include <avahi-common/strlst.h>
#include <avahi-glib/glib-malloc.h>
#include <avahi-glib/glib-watch.h>
#include <netinet/in.h>
#include <string.h>
#endif /* HAVE_AVAHI */
#include <gio/gio.h>
#include <glib.h>
#include <glib-object.h>
#include <libglnx.h>
#include "ostree-autocleanups.h"
#include "ostree-repo-finder.h"
#include "ostree-repo-finder-avahi.h"
#ifdef HAVE_AVAHI
#include "ostree-bloom-private.h"
#include "ostree-remote-private.h"
#include "ostree-repo-private.h"
#include "ostree-repo.h"
#include "ostree-repo-finder-avahi-private.h"
#include "ostree-soup-uri.h"
#include "otutil.h"
#endif /* HAVE_AVAHI */
/**
* SECTION:ostree-repo-finder-avahi
* @title: OstreeRepoFinderAvahi
* @short_description: Finds remote repositories from ref names by looking at
* adverts of refs from peers on the local network
* @stability: Unstable
* @include: libostree/ostree-repo-finder-avahi.h
*
* #OstreeRepoFinderAvahi is an implementation of #OstreeRepoFinder which looks
* for refs being hosted by peers on the local network.
*
* Any ref which matches by collection ID and ref name is returned as a result,
* with no limitations on the peers which host them, as long as they are
* accessible over the local network, and their adverts reach this machine via
* DNS-SD/mDNS.
*
* For each repository which is found, a result will be returned for the
* intersection of the refs being searched for, and the refs in `refs/mirrors`
* in the remote repository.
*
* DNS-SD resolution is performed using Avahi, which will continue to scan for
* matching peers throughout the lifetime of the process. It’s recommended that
* ostree_repo_finder_avahi_start() be called early on in the process’ lifetime,
* and the #GMainContext which is passed to ostree_repo_finder_avahi_new()
* continues to be iterated until ostree_repo_finder_avahi_stop() is called.
*
* The values stored in DNS-SD TXT records are stored as big-endian whenever
* endianness is relevant.
*
* Internally, #OstreeRepoFinderAvahi has an Avahi client, browser and resolver
* which work in the background to track all available peers on the local
* network. Whenever a resolve request is made using
* ostree_repo_finder_resolve_async(), the request is blocked until the
* background tracking is in a consistent state (typically this only happens at
* startup), and is then answered using the current cache of background data.
* The Avahi client tracks the #OstreeRepoFinderAvahi’s connection with the
* Avahi D-Bus service. The browser looks for DNS-SD peers on the local network;
* and the resolver is used to retrieve information about services advertised by
* each peer, including the services’ TXT records.
*
* Since: 2018.6
*/
#ifdef HAVE_AVAHI
/* FIXME: Submit these upstream */
G_DEFINE_AUTOPTR_CLEANUP_FUNC (AvahiClient, avahi_client_free)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (AvahiServiceBrowser, avahi_service_browser_free)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (AvahiServiceResolver, avahi_service_resolver_free)
/* FIXME: Register this with IANA? https://tools.ietf.org/html/rfc6335#section-5.2 */
const gchar * const OSTREE_AVAHI_SERVICE_TYPE = "_ostree_repo._tcp";
static const gchar *
ostree_avahi_client_state_to_string (AvahiClientState state)
{
switch (state)
{
case AVAHI_CLIENT_S_REGISTERING:
return "registering";
case AVAHI_CLIENT_S_RUNNING:
return "running";
case AVAHI_CLIENT_S_COLLISION:
return "collision";
case AVAHI_CLIENT_CONNECTING:
return "connecting";
case AVAHI_CLIENT_FAILURE:
return "failure";
default:
return "unknown";
}
}
static const gchar *
ostree_avahi_resolver_event_to_string (AvahiResolverEvent event)
{
switch (event)
{
case AVAHI_RESOLVER_FOUND:
return "found";
case AVAHI_RESOLVER_FAILURE:
return "failure";
default:
return "unknown";
}
}
static const gchar *
ostree_avahi_browser_event_to_string (AvahiBrowserEvent event)
{
switch (event)
{
case AVAHI_BROWSER_NEW:
return "new";
case AVAHI_BROWSER_REMOVE:
return "remove";
case AVAHI_BROWSER_CACHE_EXHAUSTED:
return "cache-exhausted";
case AVAHI_BROWSER_ALL_FOR_NOW:
return "all-for-now";
case AVAHI_BROWSER_FAILURE:
return "failure";
default:
return "unknown";
}
}
typedef struct
{
gchar *uri;
OstreeRemote *keyring_remote; /* (owned) */
} UriAndKeyring;
static void
uri_and_keyring_free (UriAndKeyring *data)
{
g_free (data->uri);
ostree_remote_unref (data->keyring_remote);
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (UriAndKeyring, uri_and_keyring_free)
static UriAndKeyring *
uri_and_keyring_new (const gchar *uri,
OstreeRemote *keyring_remote)
{
g_autoptr(UriAndKeyring) data = NULL;
data = g_new0 (UriAndKeyring, 1);
data->uri = g_strdup (uri);
data->keyring_remote = ostree_remote_ref (keyring_remote);
return g_steal_pointer (&data);
}
static guint
uri_and_keyring_hash (gconstpointer key)
{
const UriAndKeyring *_key = key;
return g_str_hash (_key->uri) ^ g_str_hash (_key->keyring_remote->keyring);
}
static gboolean
uri_and_keyring_equal (gconstpointer a,
gconstpointer b)
{
const UriAndKeyring *_a = a, *_b = b;
return (g_str_equal (_a->uri, _b->uri) &&
g_str_equal (_a->keyring_remote->keyring, _b->keyring_remote->keyring));
}
/* This must return a valid remote name (suitable for use in a refspec). */
static gchar *
uri_and_keyring_to_name (UriAndKeyring *data)
{
g_autofree gchar *escaped_uri = g_uri_escape_string (data->uri, NULL, FALSE);
g_autofree gchar *escaped_keyring = g_uri_escape_string (data->keyring_remote->keyring, NULL, FALSE);
/* FIXME: Need a better separator than `_`, since it’s not escaped in the input. */
g_autofree gchar *out = g_strdup_printf ("%s_%s", escaped_uri, escaped_keyring);
for (gsize i = 0; out[i] != '\0'; i++)
{
if (out[i] == '%')
out[i] = '_';
}
g_return_val_if_fail (ostree_validate_remote_name (out, NULL), NULL);
return g_steal_pointer (&out);
}
/* Internal structure representing a service found advertised by a peer on the
* local network. This includes details for connecting to the service, and the
* metadata associated with the advert (@txt). */
typedef struct
{
gchar *name;
gchar *domain;
gchar *address;
guint16 port;
AvahiStringList *txt;
} OstreeAvahiService;
static void
ostree_avahi_service_free (OstreeAvahiService *service)
{
g_free (service->name);
g_free (service->domain);
g_free (service->address);
avahi_string_list_free (service->txt);
g_free (service);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (OstreeAvahiService, ostree_avahi_service_free)
/* Convert an AvahiAddress to a string which is suitable for use in URIs (for
* example). Take into account the scope ID, if the address is IPv6 and a
* link-local address.
* (See https://en.wikipedia.org/wiki/IPv6_address#Link-local_addresses_and_zone_indices and
* https://github.com/lathiat/avahi/issues/110.) */
static gchar *
address_to_string (const AvahiAddress *address,
AvahiIfIndex interface)
{
char address_string[AVAHI_ADDRESS_STR_MAX];
avahi_address_snprint (address_string, sizeof (address_string), address);
switch (address->proto)
{
case AVAHI_PROTO_INET6:
if (IN6_IS_ADDR_LINKLOCAL (address->data.data) ||
IN6_IS_ADDR_LOOPBACK (address->data.data))
return g_strdup_printf ("%s%%%d", address_string, interface);
/* else fall through */
case AVAHI_PROTO_INET:
case AVAHI_PROTO_UNSPEC:
default:
return g_strdup (address_string);
}
}
static OstreeAvahiService *
ostree_avahi_service_new (const gchar *name,
const gchar *domain,
const AvahiAddress *address,
AvahiIfIndex interface,
guint16 port,
AvahiStringList *txt)
{
g_autoptr(OstreeAvahiService) service = NULL;
g_return_val_if_fail (name != NULL, NULL);
g_return_val_if_fail (domain != NULL, NULL);
g_return_val_if_fail (address != NULL, NULL);
g_return_val_if_fail (port > 0, NULL);
service = g_new0 (OstreeAvahiService, 1);
service->name = g_strdup (name);
service->domain = g_strdup (domain);
service->address = address_to_string (address, interface);
service->port = port;
service->txt = avahi_string_list_copy (txt);
return g_steal_pointer (&service);
}
/* Check whether @str is entirely lower case. */
static gboolean
str_is_lowercase (const gchar *str)
{
gsize i;
for (i = 0; str[i] != '\0'; i++)
{
if (!g_ascii_islower (str[i]))
return FALSE;
}
return TRUE;
}
/* Look up @key in the @attributes table derived from a TXT record, and validate
* that its value is of type @value_type. If the key is not found, or its value
* is of the wrong type or is not in normal form, %NULL is returned. @key must
* be lowercase in order to match reliably. */
static GVariant *
_ostree_txt_records_lookup_variant (GHashTable *attributes,
const gchar *key,
const GVariantType *value_type)
{
GBytes *value;
g_autoptr(GVariant) variant = NULL;
g_return_val_if_fail (attributes != NULL, NULL);
g_return_val_if_fail (str_is_lowercase (key), NULL);
g_return_val_if_fail (value_type != NULL, NULL);
value = g_hash_table_lookup (attributes, key);
if (value == NULL)
{
g_debug ("TXT attribute ‘%s’ not found.", key);
return NULL;
}
variant = g_variant_new_from_bytes (value_type, value, FALSE);
if (!g_variant_is_normal_form (variant))
{
g_debug ("TXT attribute ‘%s’ value is not in normal form. Ignoring.", key);
return NULL;
}
return g_steal_pointer (&variant);
}
/* Bloom hash function family for #OstreeCollectionRef, parameterised by @k. */
static guint64
ostree_collection_ref_bloom_hash (gconstpointer element,
guint8 k)
{
const OstreeCollectionRef *ref = element;
return ostree_str_bloom_hash (ref->collection_id, k) ^ ostree_str_bloom_hash (ref->ref_name, k);
}
/* Return the (possibly empty) subset of @refs which are possibly in the given
* encoded bloom filter, @bloom_encoded. The returned array is not
* %NULL-terminated. If there is an error decoding the bloom filter (invalid
* type, zero length, unknown hash function), %NULL will be returned. */
static GPtrArray *
bloom_refs_intersection (GVariant *bloom_encoded,
const OstreeCollectionRef * const *refs)
{
g_autoptr(OstreeBloom) bloom = NULL;
g_autoptr(GVariant) bloom_variant = NULL;
guint8 k, hash_id;
OstreeBloomHashFunc hash_func;
const guint8 *bloom_bytes;
gsize n_bloom_bytes;
g_autoptr(GBytes) bytes = NULL;
gsize i;
g_autoptr(GPtrArray) possible_refs = NULL; /* (element-type OstreeCollectionRef) */
g_variant_get (bloom_encoded, "(yy@ay)", &k, &hash_id, &bloom_variant);
if (k == 0)
return NULL;
switch (hash_id)
{
case 1:
hash_func = ostree_collection_ref_bloom_hash;
break;
default:
return NULL;
}
bloom_bytes = g_variant_get_fixed_array (bloom_variant, &n_bloom_bytes, sizeof (guint8));
bytes = g_bytes_new_static (bloom_bytes, n_bloom_bytes);
bloom = ostree_bloom_new_from_bytes (bytes, k, hash_func);
possible_refs = g_ptr_array_new_with_free_func (NULL);
for (i = 0; refs[i] != NULL; i++)
{
if (ostree_bloom_maybe_contains (bloom, refs[i]))
g_ptr_array_add (possible_refs, (gpointer) refs[i]);
}
return g_steal_pointer (&possible_refs);
}
/* Given a @summary_map of ref name to commit details, and the @collection_id
* for all the refs in the @summary_map (which may be %NULL if the summary does
* not specify one), add the refs to @refs_and_checksums.
*
* The @summary_map is validated as it’s iterated over; on error, @error will be
* set and @refs_and_checksums will be left in an undefined state. */
static gboolean
fill_refs_and_checksums_from_summary_map (GVariantIter *summary_map,
const gchar *collection_id,
GHashTable *refs_and_checksums /* (element-type OstreeCollectionRef utf8) */,
GError **error)
{
g_autofree gchar *ref_name = NULL;
g_autoptr(GVariant) checksum_variant = NULL;
while (g_variant_iter_loop (summary_map, "(s(t@aya{sv}))",
(gpointer *) &ref_name, NULL,
(gpointer *) &checksum_variant, NULL))
{
const OstreeCollectionRef ref = { (gchar *) collection_id, ref_name };
if (!ostree_validate_rev (ref_name, error))
return FALSE;
if (!ostree_validate_structureof_csum_v (checksum_variant, error))
return FALSE;
if (g_hash_table_contains (refs_and_checksums, &ref))
{
g_autofree gchar *checksum_string = ostree_checksum_from_bytes_v (checksum_variant);
g_hash_table_replace (refs_and_checksums,
ostree_collection_ref_dup (&ref),
g_steal_pointer (&checksum_string));
}
}
return TRUE;
}
/* Given a @summary file, add the refs it lists to @refs_and_checksums. This
* includes the main refs list in the summary, and the map of collection IDs
* to further refs lists.
*
* The @summary is validated as it’s explored; on error, @error will be
* set and @refs_and_checksums will be left in an undefined state. */
static gboolean
fill_refs_and_checksums_from_summary (GVariant *summary,
GHashTable *refs_and_checksums /* (element-type OstreeCollectionRef utf8) */,
GError **error)
{
g_autoptr(GVariant) ref_map_v = NULL;
g_autoptr(GVariant) additional_metadata_v = NULL;
g_autoptr(GVariantIter) ref_map = NULL;
g_auto(GVariantDict) additional_metadata = OT_VARIANT_BUILDER_INITIALIZER;
const gchar *collection_id;
g_autoptr(GVariantIter) collection_map = NULL;
ref_map_v = g_variant_get_child_value (summary, 0);
additional_metadata_v = g_variant_get_child_value (summary, 1);
ref_map = g_variant_iter_new (ref_map_v);
g_variant_dict_init (&additional_metadata, additional_metadata_v);
/* If the summary file specifies a collection ID (to apply to all the refs in its
* ref map), use that to start matching against the queried refs. Otherwise,
* it might specify all its refs in a collection-map; or the summary format is
* old and unsuitable for P2P redistribution and we should bail. */
if (g_variant_dict_lookup (&additional_metadata, OSTREE_SUMMARY_COLLECTION_ID, "&s", &collection_id))
{
if (!ostree_validate_collection_id (collection_id, error))
return FALSE;
if (!fill_refs_and_checksums_from_summary_map (ref_map, collection_id, refs_and_checksums, error))
return FALSE;
}
g_clear_pointer (&ref_map, (GDestroyNotify) g_variant_iter_free);
/* Repeat for the other collections listed in the summary. */
if (g_variant_dict_lookup (&additional_metadata, OSTREE_SUMMARY_COLLECTION_MAP, "a{sa(s(taya{sv}))}", &collection_map))
{
while (g_variant_iter_loop (collection_map, "{sa(s(taya{sv}))}", &collection_id, &ref_map))
{
if (!ostree_validate_collection_id (collection_id, error))
return FALSE;
if (!fill_refs_and_checksums_from_summary_map (ref_map, collection_id, refs_and_checksums, error))
return FALSE;
}
}
return TRUE;
}
/* Given a summary file (@summary_bytes), extract the refs it lists, and use that
* to fill in the checksums in the @supported_ref_to_checksum map. This includes
* the main refs list in the summary, and the map of collection IDs to further
* refs lists.
*
* The @summary is validated as it’s explored; on error, @error will be
* set and %FALSE will be returned. If the intersection of the summary file refs
* and the keys in @supported_ref_to_checksum is empty, an error is set. */
static gboolean
get_refs_and_checksums_from_summary (GBytes *summary_bytes,
GHashTable *supported_ref_to_checksum /* (element-type OstreeCollectionRef utf8) */,
GError **error)
{
g_autoptr(GVariant) summary = g_variant_ref_sink (g_variant_new_from_bytes (OSTREE_SUMMARY_GVARIANT_FORMAT, summary_bytes, FALSE));
GHashTableIter iter;
const OstreeCollectionRef *ref;
const gchar *checksum;
if (!g_variant_is_normal_form (summary))
{
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
"Not normal form");
return FALSE;
}
if (!g_variant_is_of_type (summary, OSTREE_SUMMARY_GVARIANT_FORMAT))
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
"Doesn't match variant type '%s'",
(char *)OSTREE_SUMMARY_GVARIANT_FORMAT);
return FALSE;
}
if (!fill_refs_and_checksums_from_summary (summary, supported_ref_to_checksum, error))
return FALSE;
/* Check that at least one of the refs has a non-%NULL checksum set, otherwise
* we can discard this peer. */
g_hash_table_iter_init (&iter, supported_ref_to_checksum);
while (g_hash_table_iter_next (&iter,
(gpointer *) &ref,
(gpointer *) &checksum))
{
if (checksum != NULL)
return TRUE;
}
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
"No matching refs were found in the summary file");
return FALSE;
}
/* Download the summary file from @remote, and return the bytes of the file in
* @out_summary_bytes. This will return %TRUE and set @out_summary_bytes to %NULL
* if the summary file does not exist. */
static gboolean
fetch_summary_from_remote (OstreeRepo *repo,
OstreeRemote *remote,
GBytes **out_summary_bytes,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GBytes) summary_bytes = NULL;
gboolean remote_already_existed = _ostree_repo_add_remote (repo, remote);
gboolean success = ostree_repo_remote_fetch_summary_with_options (repo,
remote->name,
NULL /* options */,
&summary_bytes,
NULL /* signature */,
cancellable,
error);
if (!remote_already_existed)
_ostree_repo_remove_remote (repo, remote);
if (!success)
return FALSE;
g_assert (out_summary_bytes != NULL);
*out_summary_bytes = g_steal_pointer (&summary_bytes);
return TRUE;
}
#endif /* HAVE_AVAHI */
struct _OstreeRepoFinderAvahi
{
GObject parent_instance;
#ifdef HAVE_AVAHI
/* All elements of this structure must only be accessed from @avahi_context
* after construction. */
/* Note: There is a ref-count loop here: each #GTask has a reference to the
* #OstreeRepoFinderAvahi, and we have to keep a reference to the #GTask. */
GPtrArray *resolve_tasks; /* (element-type (owned) GTask) */
AvahiGLibPoll *poll;
AvahiClient *client;
AvahiServiceBrowser *browser;
AvahiClientState client_state;
gboolean browser_failed;
gboolean browser_all_for_now;
GCancellable *avahi_cancellable;
GMainContext *avahi_context;
/* Map of service name (typically human readable) to a #GPtrArray of the
* #AvahiServiceResolver instances we have running against that name. We
* could end up with more than one resolver if the same name is advertised to
* us over multiple interfaces or protocols (for example, IPv4 and IPv6).
* Resolve all of them just in case one doesn’t work. */
GHashTable *resolvers; /* (element-type (owned) utf8 (owned) GPtrArray (element-type (owned) AvahiServiceResolver)) */
/* Array of #OstreeAvahiService instances representing all the services which
* we currently think are valid. */
GPtrArray *found_services; /* (element-type (owned OstreeAvahiService) */
#endif /* HAVE_AVAHI */
};
static void ostree_repo_finder_avahi_iface_init (OstreeRepoFinderInterface *iface);
G_DEFINE_TYPE_WITH_CODE (OstreeRepoFinderAvahi, ostree_repo_finder_avahi, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE (OSTREE_TYPE_REPO_FINDER, ostree_repo_finder_avahi_iface_init))
#ifdef HAVE_AVAHI
/* Download the summary file from @remote and fill in the checksums in the given
* @supported_ref_to_checksum hash table, given the existing refs in it as keys.
* See get_refs_and_checksums_from_summary() for more details. */
static gboolean
get_checksums (OstreeRepoFinderAvahi *finder,
OstreeRepo *repo,
OstreeRemote *remote,
GHashTable *supported_ref_to_checksum /* (element-type OstreeCollectionRef utf8) */,
GError **error)
{
g_autoptr(GBytes) summary_bytes = NULL;
if (!fetch_summary_from_remote (repo,
remote,
&summary_bytes,
finder->avahi_cancellable,
error))
return FALSE;
if (summary_bytes == NULL)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
"No summary file found on server");
return FALSE;
}
return get_refs_and_checksums_from_summary (summary_bytes, supported_ref_to_checksum, error);
}
/* Build some #OstreeRepoFinderResults out of the given #OstreeAvahiService by
* parsing its DNS-SD TXT records and finding the intersection between the refs
* it advertises and @refs. One or more results will be added to @results, with
* multiple results being added if the intersection of refs covers refs which
* need different GPG keyrings. One result is added per (uri, keyring) pair.
*
* If any of the TXT records are malformed or missing, or if the intersection of
* refs is empty, return early without modifying @results.
*
* This recognises the following TXT records:
* - `v` (`y`): Version of the TXT record format. Only version `1` is currently
* supported.
* - `rb` (`(yyay)`): Bloom filter indicating which refs are served by the peer.
* - `st` (`t`): Timestamp (seconds since the Unix epoch, big endian) the
* summary file was last modified.
* - `ri` (`q`): Repository index, indicating which of several repositories
* hosted on the peer this is. Big endian.
*/
static void
ostree_avahi_service_build_repo_finder_result (OstreeAvahiService *service,
OstreeRepoFinderAvahi *finder,
OstreeRepo *parent_repo,
gint priority,
const OstreeCollectionRef * const *refs,
GPtrArray *results,
GCancellable *cancellable)
{
g_autoptr(GHashTable) attributes = NULL;
g_autoptr(GVariant) version = NULL;
g_autoptr(GVariant) bloom = NULL;
g_autoptr(GVariant) summary_timestamp = NULL;
g_autoptr(GVariant) repo_index = NULL;
g_autofree gchar *repo_path = NULL;
g_autoptr(GPtrArray) possible_refs = NULL; /* (element-type OstreeCollectionRef) */
SoupURI *_uri = NULL;
g_autofree gchar *uri = NULL;
g_autoptr(GError) error = NULL;
gsize i;
g_autoptr(GHashTable) repo_to_refs = NULL; /* (element-type UriAndKeyring GHashTable) */
GHashTable *supported_ref_to_checksum; /* (element-type OstreeCollectionRef utf8) */
GHashTableIter iter;
UriAndKeyring *repo;
g_return_if_fail (service != NULL);
g_return_if_fail (refs != NULL);
attributes = _ostree_txt_records_parse (service->txt);
/* Check the record version. */
version = _ostree_txt_records_lookup_variant (attributes, "v", G_VARIANT_TYPE_BYTE);
if (g_variant_get_byte (version) != 1)
{
g_debug ("Unknown v=%02x attribute provided in TXT record. Ignoring.",
g_variant_get_byte (version));
return;
}
/* Refs bloom filter? */
bloom = _ostree_txt_records_lookup_variant (attributes, "rb", G_VARIANT_TYPE ("(yyay)"));
if (bloom == NULL)
{
g_debug ("Missing rb (refs bloom) attribute in TXT record. Ignoring.");
return;
}
possible_refs = bloom_refs_intersection (bloom, refs);
if (possible_refs == NULL)
{
g_debug ("Wrong k parameter or hash id in rb (refs bloom) attribute in TXT record. Ignoring.");
return;
}
if (possible_refs->len == 0)
{
g_debug ("TXT record definitely has no matching refs. Ignoring.");
return;
}
/* Summary timestamp. */
summary_timestamp = _ostree_txt_records_lookup_variant (attributes, "st", G_VARIANT_TYPE_UINT64);
if (summary_timestamp == NULL)
{
g_debug ("Missing st (summary timestamp) attribute in TXT record. Ignoring.");
return;
}
/* Repository index. */
repo_index = _ostree_txt_records_lookup_variant (attributes, "ri", G_VARIANT_TYPE_UINT16);
if (repo_index == NULL)
{
g_debug ("Missing ri (repository index) attribute in TXT record. Ignoring.");
return;
}
repo_path = g_strdup_printf ("/%u", GUINT16_FROM_BE (g_variant_get_uint16 (repo_index)));
/* Create a new result for each keyring needed by @possible_refs. Typically,
* there will be a separate keyring per collection, but some might be shared. */
repo_to_refs = g_hash_table_new_full (uri_and_keyring_hash, uri_and_keyring_equal,
(GDestroyNotify) uri_and_keyring_free, (GDestroyNotify) g_hash_table_unref);
_uri = soup_uri_new (NULL);
soup_uri_set_scheme (_uri, "http");
soup_uri_set_host (_uri, service->address);
soup_uri_set_port (_uri, service->port);
soup_uri_set_path (_uri, repo_path);
uri = soup_uri_to_string (_uri, FALSE);
soup_uri_free (_uri);
for (i = 0; i < possible_refs->len; i++)
{
const OstreeCollectionRef *ref = g_ptr_array_index (possible_refs, i);
g_autoptr(UriAndKeyring) resolved_repo = NULL;
g_autoptr(OstreeRemote) keyring_remote = NULL;
/* Look up the GPG keyring for this ref. */
keyring_remote = ostree_repo_resolve_keyring_for_collection (parent_repo,
ref->collection_id,
cancellable, &error);
if (keyring_remote == NULL)
{
g_debug ("Ignoring ref (%s, %s) on host ‘%s’ due to missing keyring: %s",
ref->collection_id, refs[i]->ref_name, service->address,
error->message);
g_clear_error (&error);
continue;
}
/* Add this repo to the results, keyed by the canonicalised repository URI
* to deduplicate the results. */
g_debug ("Resolved ref (%s, %s) to repo URI ‘%s’ with keyring ‘%s’ from remote ‘%s’.",
ref->collection_id, ref->ref_name, uri, keyring_remote->keyring,
keyring_remote->name);
resolved_repo = uri_and_keyring_new (uri, keyring_remote);
supported_ref_to_checksum = g_hash_table_lookup (repo_to_refs, resolved_repo);
if (supported_ref_to_checksum == NULL)
{
supported_ref_to_checksum = g_hash_table_new_full (ostree_collection_ref_hash,
ostree_collection_ref_equal,
NULL, g_free);
g_hash_table_insert (repo_to_refs, g_steal_pointer (&resolved_repo), supported_ref_to_checksum /* transfer */);
}
/* Add a placeholder to @supported_ref_to_checksum for this ref. It will
* be filled out by the get_checksums() call below. */
g_hash_table_insert (supported_ref_to_checksum, (gpointer) ref, NULL);
}
/* Aggregate the results. */
g_hash_table_iter_init (&iter, repo_to_refs);
while (g_hash_table_iter_next (&iter, (gpointer *) &repo, (gpointer *) &supported_ref_to_checksum))
{
g_autoptr(OstreeRemote) remote = NULL;
/* Build an #OstreeRemote. Use the escaped URI, since remote->name
* is used in file paths, so needs to not contain special characters. */
g_autofree gchar *name = uri_and_keyring_to_name (repo);
remote = ostree_remote_new_dynamic (name, repo->keyring_remote->name);
g_clear_pointer (&remote->keyring, g_free);
remote->keyring = g_strdup (repo->keyring_remote->keyring);
/* gpg-verify-summary is false since we use the unsigned summary file support. */
g_key_file_set_string (remote->options, remote->group, "url", repo->uri);
g_key_file_set_boolean (remote->options, remote->group, "gpg-verify", TRUE);
g_key_file_set_boolean (remote->options, remote->group, "gpg-verify-summary", FALSE);
get_checksums (finder, parent_repo, remote, supported_ref_to_checksum, &error);
if (error != NULL)
{
g_debug ("Failed to get checksums for possible refs; ignoring: %s", error->message);
g_clear_error (&error);
continue;
}
g_ptr_array_add (results, ostree_repo_finder_result_new (remote, OSTREE_REPO_FINDER (finder),
priority, supported_ref_to_checksum, NULL,
GUINT64_FROM_BE (g_variant_get_uint64 (summary_timestamp))));
}
}
typedef struct
{
OstreeCollectionRef **refs; /* (owned) (array zero-terminated=1) */
OstreeRepo *parent_repo; /* (owned) */
} ResolveData;
static void
resolve_data_free (ResolveData *data)
{
g_object_unref (data->parent_repo);
ostree_collection_ref_freev (data->refs);
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (ResolveData, resolve_data_free)
static ResolveData *
resolve_data_new (const OstreeCollectionRef * const *refs,
OstreeRepo *parent_repo)
{
g_autoptr(ResolveData) data = NULL;
data = g_new0 (ResolveData, 1);
data->refs = ostree_collection_ref_dupv (refs);
data->parent_repo = g_object_ref (parent_repo);
return g_steal_pointer (&data);
}
static void
fail_all_pending_tasks (OstreeRepoFinderAvahi *self,
GQuark domain,
gint code,
const gchar *format,
...) G_GNUC_PRINTF(4, 5);
/* Executed in @self->avahi_context.
*
* Return the given error from all the pending resolve tasks in
* self->resolve_tasks. */
static void
fail_all_pending_tasks (OstreeRepoFinderAvahi *self,
GQuark domain,
gint code,
const gchar *format,
...)
{
gsize i;
va_list args;
g_autoptr(GError) error = NULL;
g_assert (g_main_context_is_owner (self->avahi_context));
va_start (args, format);
error = g_error_new_valist (domain, code, format, args);
va_end (args);
for (i = 0; i < self->resolve_tasks->len; i++)
{
GTask *task = G_TASK (g_ptr_array_index (self->resolve_tasks, i));
g_task_return_error (task, g_error_copy (error));
}
g_ptr_array_set_size (self->resolve_tasks, 0);
}
static gint
results_compare_cb (gconstpointer a,
gconstpointer b)
{
const OstreeRepoFinderResult *result_a = *((const OstreeRepoFinderResult **) a);
const OstreeRepoFinderResult *result_b = *((const OstreeRepoFinderResult **) b);
return ostree_repo_finder_result_compare (result_a, result_b);
}
/* Executed in @self->avahi_context.
*
* For each of the pending resolve tasks in self->resolve_tasks, calculate and
* return the result set for its query given the currently known services from
* Avahi which are stored in self->found_services. */
static void
complete_all_pending_tasks (OstreeRepoFinderAvahi *self)
{
gsize i;
const gint priority = 60; /* arbitrarily chosen */
g_autoptr(GPtrArray) results_for_tasks = g_ptr_array_new_full (self->resolve_tasks->len, (GDestroyNotify)g_ptr_array_unref);
gboolean cancelled = FALSE;
g_assert (g_main_context_is_owner (self->avahi_context));
g_debug ("%s: Completing %u tasks", G_STRFUNC, self->resolve_tasks->len);
for (i = 0; i < self->resolve_tasks->len; i++)
{
g_autoptr(GPtrArray) results = NULL;
GTask *task;
ResolveData *data;
const OstreeCollectionRef * const *refs;
gsize j;
task = G_TASK (g_ptr_array_index (self->resolve_tasks, i));
data = g_task_get_task_data (task);
refs = (const OstreeCollectionRef * const *) data->refs;
results = g_ptr_array_new_with_free_func ((GDestroyNotify) ostree_repo_finder_result_free);
for (j = 0; j < self->found_services->len; j++)
{
OstreeAvahiService *service = g_ptr_array_index (self->found_services, j);
ostree_avahi_service_build_repo_finder_result (service, self, data->parent_repo,
priority, refs, results,
self->avahi_cancellable);
if (g_cancellable_is_cancelled (self->avahi_cancellable))
{
cancelled = TRUE;
break;
}
}
if (cancelled)
break;
g_ptr_array_add (results_for_tasks, g_steal_pointer (&results));
}
if (!cancelled)
{
for (i = 0; i < self->resolve_tasks->len; i++)
{
GTask *task = G_TASK (g_ptr_array_index (self->resolve_tasks, i));
GPtrArray *results = g_ptr_array_index (results_for_tasks, i);
g_ptr_array_sort (results, results_compare_cb);
g_task_return_pointer (task,
g_ptr_array_ref (results),
(GDestroyNotify) g_ptr_array_unref);
}
g_ptr_array_set_size (self->resolve_tasks, 0);
}
else
{
fail_all_pending_tasks (self, G_IO_ERROR, G_IO_ERROR_CANCELLED,
"Avahi service resolution cancelled.");
}
}
/* Executed in @self->avahi_context. */
static void
maybe_complete_all_pending_tasks (OstreeRepoFinderAvahi *self)
{
g_assert (g_main_context_is_owner (self->avahi_context));
g_debug ("%s: client_state: %s, browser_failed: %u, cancelled: %u, "
"browser_all_for_now: %u, n_resolvers: %u",
G_STRFUNC, ostree_avahi_client_state_to_string (self->client_state),
self->browser_failed,
g_cancellable_is_cancelled (self->avahi_cancellable),
self->browser_all_for_now, g_hash_table_size (self->resolvers));
if (self->client_state == AVAHI_CLIENT_FAILURE)
fail_all_pending_tasks (self, G_IO_ERROR, G_IO_ERROR_FAILED,
"Avahi client error: %s",
avahi_strerror (avahi_client_errno (self->client)));
else if (self->browser_failed)
fail_all_pending_tasks (self, G_IO_ERROR, G_IO_ERROR_FAILED,
"Avahi browser error: %s",
avahi_strerror (avahi_client_errno (self->client)));
else if (g_cancellable_is_cancelled (self->avahi_cancellable))
fail_all_pending_tasks (self, G_IO_ERROR, G_IO_ERROR_CANCELLED,
"Avahi service resolution cancelled.");
else if (self->browser_all_for_now &&
g_hash_table_size (self->resolvers) == 0)
complete_all_pending_tasks (self);
}
/* Executed in @self->avahi_context. */
static void
client_cb (AvahiClient *client,
AvahiClientState state,
void *finder_ptr)
{
/* Completing the pending tasks might drop the final reference to @self. */
g_autoptr(OstreeRepoFinderAvahi) self = g_object_ref (finder_ptr);
/* self->client will be NULL if client_cb() is called from
* ostree_repo_finder_avahi_start(). */
g_assert (self->client == NULL || g_main_context_is_owner (self->avahi_context));
g_debug ("%s: Entered state ‘%s’.",
G_STRFUNC, ostree_avahi_client_state_to_string (state));
/* We only care about entering and leaving %AVAHI_CLIENT_FAILURE. */
self->client_state = state;
if (self->client != NULL)
maybe_complete_all_pending_tasks (self);
}
/* Executed in @self->avahi_context. */
static void
resolve_cb (AvahiServiceResolver *resolver,
AvahiIfIndex interface,
AvahiProtocol protocol,
AvahiResolverEvent event,
const char *name,
const char *type,
const char *domain,
const char *host_name,
const AvahiAddress *address,
uint16_t port,
AvahiStringList *txt,
AvahiLookupResultFlags flags,
void *finder_ptr)
{
/* Completing the pending tasks might drop the final reference to @self. */
g_autoptr(OstreeRepoFinderAvahi) self = g_object_ref (finder_ptr);
g_autoptr(OstreeAvahiService) service = NULL;
GPtrArray *resolvers;
g_assert (g_main_context_is_owner (self->avahi_context));
g_debug ("%s: Resolve event ‘%s’ for name ‘%s’.",
G_STRFUNC, ostree_avahi_resolver_event_to_string (event), name);
/* Track the resolvers active for this @name. There may be several,
* as @name might appear to us over several interfaces or protocols. Most
* commonly this happens when both hosts are connected via IPv4 and IPv6. */
resolvers = g_hash_table_lookup (self->resolvers, name);
if (resolvers == NULL || resolvers->len == 0)
{
/* maybe it was removed in the meantime */
g_hash_table_remove (self->resolvers, name);
return;
}
else if (resolvers->len == 1)
{
g_hash_table_remove (self->resolvers, name);
}
else
{
g_ptr_array_remove_fast (resolvers, resolver);
}
/* Was resolution successful? */
switch (event)
{
case AVAHI_RESOLVER_FOUND:
service = ostree_avahi_service_new (name, domain, address, interface,
port, txt);
g_ptr_array_add (self->found_services, g_steal_pointer (&service));
break;
case AVAHI_RESOLVER_FAILURE:
default:
g_warning ("Failed to resolve service ‘%s’: %s", name,
avahi_strerror (avahi_client_errno (self->client)));
break;
}
maybe_complete_all_pending_tasks (self);
}
/* Executed in @self->avahi_context. */
static void
browse_new (OstreeRepoFinderAvahi *self,
AvahiIfIndex interface,
AvahiProtocol protocol,
const gchar *name,
const gchar *type,
const gchar *domain)
{
g_autoptr(AvahiServiceResolver) resolver = NULL;
GPtrArray *resolvers; /* (element-type AvahiServiceResolver) */
g_assert (g_main_context_is_owner (self->avahi_context));
resolver = avahi_service_resolver_new (self->client,
interface,
protocol,
name,
type,
domain,
AVAHI_PROTO_UNSPEC,
0,
resolve_cb,
self);
if (resolver == NULL)
{
g_warning ("Failed to resolve service ‘%s’: %s", name,
avahi_strerror (avahi_client_errno (self->client)));
return;
}
g_debug ("Found name service %s on the network; type: %s, domain: %s, "
"protocol: %u, interface: %u", name, type, domain, protocol,
interface);
/* Start a resolver for this (interface, protocol, name, type, domain)
* combination. */
resolvers = g_hash_table_lookup (self->resolvers, name);
if (resolvers == NULL)
{
resolvers = g_ptr_array_new_with_free_func ((GDestroyNotify) avahi_service_resolver_free);
g_hash_table_insert (self->resolvers, g_strdup (name), resolvers);
}
g_ptr_array_add (resolvers, g_steal_pointer (&resolver));
}
/* Executed in @self->avahi_context. Caller must call maybe_complete_all_pending_tasks(). */
static void
browse_remove (OstreeRepoFinderAvahi *self,
const char *name)
{
gsize i;
gboolean removed = FALSE;
g_assert (g_main_context_is_owner (self->avahi_context));
g_hash_table_remove (self->resolvers, name);
for (i = 0; i < self->found_services->len; i += (removed ? 0 : 1))
{
OstreeAvahiService *service = g_ptr_array_index (self->found_services, i);
removed = FALSE;
if (g_strcmp0 (service->name, name) == 0)
{
g_ptr_array_remove_index_fast (self->found_services, i);
removed = TRUE;
continue;
}
}
}
/* Executed in @self->avahi_context. */
static void
browse_cb (AvahiServiceBrowser *browser,
AvahiIfIndex interface,
AvahiProtocol protocol,
AvahiBrowserEvent event,
const char *name,
const char *type,
const char *domain,
AvahiLookupResultFlags flags,
void *finder_ptr)
{
/* Completing the pending tasks might drop the final reference to @self. */
g_autoptr(OstreeRepoFinderAvahi) self = g_object_ref (finder_ptr);
g_assert (g_main_context_is_owner (self->avahi_context));
g_debug ("%s: Browse event ‘%s’ for name ‘%s’.",
G_STRFUNC, ostree_avahi_browser_event_to_string (event), name);
self->browser_failed = FALSE;
switch (event)
{
case AVAHI_BROWSER_NEW:
browse_new (self, interface, protocol, name, type, domain);
break;
case AVAHI_BROWSER_REMOVE:
browse_remove (self, name);
break;
case AVAHI_BROWSER_CACHE_EXHAUSTED:
/* don’t care about this. */
break;
case AVAHI_BROWSER_ALL_FOR_NOW:
self->browser_all_for_now = TRUE;
break;
case AVAHI_BROWSER_FAILURE:
self->browser_failed = TRUE;
break;
default:
g_assert_not_reached ();
}
/* Check all the tasks for any event, since the @browser_failed state
* may have changed. */
maybe_complete_all_pending_tasks (self);
}
static gboolean add_resolve_task_cb (gpointer user_data);
#endif /* HAVE_AVAHI */
static void
ostree_repo_finder_avahi_resolve_async (OstreeRepoFinder *finder,
const OstreeCollectionRef * const *refs,
OstreeRepo *parent_repo,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
OstreeRepoFinderAvahi *self = OSTREE_REPO_FINDER_AVAHI (finder);
g_autoptr(GTask) task = NULL;
g_debug ("%s: Starting resolving", G_STRFUNC);
task = g_task_new (self, cancellable, callback, user_data);
g_task_set_source_tag (task, ostree_repo_finder_avahi_resolve_async);
#ifdef HAVE_AVAHI
g_task_set_task_data (task, resolve_data_new (refs, parent_repo), (GDestroyNotify) resolve_data_free);
/* Move @task to the @avahi_context where it can be processed. */
g_main_context_invoke (self->avahi_context, add_resolve_task_cb, g_steal_pointer (&task));
#else /* if !HAVE_AVAHI */
g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
"Avahi support was not compiled in to libostree");
#endif /* !HAVE_AVAHI */
}
#ifdef HAVE_AVAHI
/* Executed in @self->avahi_context. */
static gboolean
add_resolve_task_cb (gpointer user_data)
{
g_autoptr(GTask) task = G_TASK (user_data);
OstreeRepoFinderAvahi *self = g_task_get_source_object (task);
g_assert (g_main_context_is_owner (self->avahi_context));
g_debug ("%s", G_STRFUNC);
/* Track the task and check to see if the browser and resolvers are in a
* quiescent state suitable for returning a result immediately. */
g_ptr_array_add (self->resolve_tasks, g_object_ref (task));
maybe_complete_all_pending_tasks (self);
return G_SOURCE_REMOVE;
}
#endif /* HAVE_AVAHI */
static GPtrArray *
ostree_repo_finder_avahi_resolve_finish (OstreeRepoFinder *finder,
GAsyncResult *result,
GError **error)
{
g_return_val_if_fail (g_task_is_valid (result, finder), NULL);
return g_task_propagate_pointer (G_TASK (result), error);
}
static void
ostree_repo_finder_avahi_dispose (GObject *obj)
{
#ifdef HAVE_AVAHI
OstreeRepoFinderAvahi *self = OSTREE_REPO_FINDER_AVAHI (obj);
ostree_repo_finder_avahi_stop (self);
g_assert (self->resolve_tasks == NULL || self->resolve_tasks->len == 0);
g_clear_pointer (&self->resolve_tasks, g_ptr_array_unref);
g_clear_pointer (&self->browser, avahi_service_browser_free);
g_clear_pointer (&self->client, avahi_client_free);
g_clear_pointer (&self->poll, avahi_glib_poll_free);
g_clear_pointer (&self->avahi_context, g_main_context_unref);
g_clear_pointer (&self->found_services, g_ptr_array_unref);
g_clear_pointer (&self->resolvers, g_hash_table_unref);
g_clear_object (&self->avahi_cancellable);
#endif /* HAVE_AVAHI */
/* Chain up. */
G_OBJECT_CLASS (ostree_repo_finder_avahi_parent_class)->dispose (obj);
}
static void
ostree_repo_finder_avahi_class_init (OstreeRepoFinderAvahiClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->dispose = ostree_repo_finder_avahi_dispose;
}
static void
ostree_repo_finder_avahi_iface_init (OstreeRepoFinderInterface *iface)
{
iface->resolve_async = ostree_repo_finder_avahi_resolve_async;
iface->resolve_finish = ostree_repo_finder_avahi_resolve_finish;
}
static void
ostree_repo_finder_avahi_init (OstreeRepoFinderAvahi *self)
{
#ifdef HAVE_AVAHI
self->resolve_tasks = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
self->avahi_cancellable = g_cancellable_new ();
self->client_state = AVAHI_CLIENT_S_REGISTERING;
self->resolvers = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_ptr_array_unref);
self->found_services = g_ptr_array_new_with_free_func ((GDestroyNotify) ostree_avahi_service_free);
#endif /* HAVE_AVAHI */
}
/**
* ostree_repo-finder_avahi_new:
* @context: (transfer none) (nullable): a #GMainContext for processing Avahi
* events in, or %NULL to use the current thread-default
*
* Create a new #OstreeRepoFinderAvahi instance. It is intended that one such
* instance be created per process, and it be used to answer all resolution
* requests from #OstreeRepos.
*
* The calling code is responsible for ensuring that @context is iterated while
* the #OstreeRepoFinderAvahi is running (after ostree_repo_finder_avahi_start()
* is called). This may be done from any thread.
*
* If @context is %NULL, the current thread-default #GMainContext is used.
*
* Returns: (transfer full): a new #OstreeRepoFinderAvahi
* Since: 2018.6
*/
OstreeRepoFinderAvahi *
ostree_repo_finder_avahi_new (GMainContext *context)
{
g_autoptr(OstreeRepoFinderAvahi) finder = NULL;
finder = g_object_new (OSTREE_TYPE_REPO_FINDER_AVAHI, NULL);
#ifdef HAVE_AVAHI
/* FIXME: Make this a property */
if (context != NULL)
finder->avahi_context = g_main_context_ref (context);
else
finder->avahi_context = g_main_context_ref_thread_default ();
/* Avahi setup. Note: Technically the allocator is per-process state which we
* shouldn’t set here, but it’s probably fine. It’s unlikely that code which
* is using libostree is going to use an allocator which is not GLib, and
* *also* use Avahi API itself. */
avahi_set_allocator (avahi_glib_allocator ());
finder->poll = avahi_glib_poll_new (finder->avahi_context, G_PRIORITY_DEFAULT);
#endif /* HAVE_AVAHI */
return g_steal_pointer (&finder);
}
/**
* ostree_repo_finder_avahi_start:
* @self: an #OstreeRepoFinderAvahi
* @error: return location for a #GError
*
* Start monitoring the local network for peers who are advertising OSTree
* repositories, using Avahi. In order for this to work, the #GMainContext
* passed to @self at construction time must be iterated (so it will typically
* be the global #GMainContext, or be a separate #GMainContext in a worker
* thread).
*
* This will return an error (%G_IO_ERROR_FAILED) if initialisation fails, or if
* Avahi support is not available (%G_IO_ERROR_NOT_SUPPORTED). In either case,
* the #OstreeRepoFinderAvahi instance is useless afterwards and should be
* destroyed.
*
* Call ostree_repo_finder_avahi_stop() to stop the repo finder.
*
* It is an error to call this function multiple times on the same
* #OstreeRepoFinderAvahi instance, or to call it after
* ostree_repo_finder_avahi_stop().
*
* Since: 2018.6
*/
void
ostree_repo_finder_avahi_start (OstreeRepoFinderAvahi *self,
GError **error)
{
g_return_if_fail (OSTREE_IS_REPO_FINDER_AVAHI (self));
g_return_if_fail (error == NULL || *error == NULL);
#ifdef HAVE_AVAHI
g_autoptr(AvahiClient) client = NULL;
g_autoptr(AvahiServiceBrowser) browser = NULL;
int failure = 0;
if (g_cancellable_set_error_if_cancelled (self->avahi_cancellable, error))
return;
g_assert (self->client == NULL);
client = avahi_client_new (avahi_glib_poll_get (self->poll), 0,
client_cb, self, &failure);
if (client == NULL)
{
if (failure == AVAHI_ERR_NO_DAEMON)
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
"Avahi daemon is not running: %s",
avahi_strerror (failure));
else
g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
"Failed to create finder client: %s",
avahi_strerror (failure));
return;
}
/* Query for the OSTree DNS-SD service on the local network. */
browser = avahi_service_browser_new (client,
AVAHI_IF_UNSPEC,
AVAHI_PROTO_UNSPEC,
OSTREE_AVAHI_SERVICE_TYPE,
NULL,
0,
browse_cb,
self);
if (browser == NULL)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
"Failed to create service browser: %s",
avahi_strerror (avahi_client_errno (client)));
return;
}
/* Success. */
self->client = g_steal_pointer (&client);
self->browser = g_steal_pointer (&browser);
#else /* if !HAVE_AVAHI */
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
"Avahi support was not compiled in to libostree");
#endif /* !HAVE_AVAHI */
}
#ifdef HAVE_AVAHI
static gboolean stop_cb (gpointer user_data);
#endif /* HAVE_AVAHI */
/**
* ostree_repo_finder_avahi_stop:
* @self: an #OstreeRepoFinderAvahi
*
* Stop monitoring the local network for peers who are advertising OSTree
* repositories. If any resolve tasks (from ostree_repo_finder_resolve_async())
* are in progress, they will be cancelled and will return %G_IO_ERROR_CANCELLED.
*
* Call ostree_repo_finder_avahi_start() to start the repo finder.
*
* It is an error to call this function multiple times on the same
* #OstreeRepoFinderAvahi instance, or to call it before
* ostree_repo_finder_avahi_start().
*
* Since: 2018.6
*/
void
ostree_repo_finder_avahi_stop (OstreeRepoFinderAvahi *self)
{
g_return_if_fail (OSTREE_IS_REPO_FINDER_AVAHI (self));
#ifdef HAVE_AVAHI
if (self->browser == NULL)
return;
g_main_context_invoke (self->avahi_context, stop_cb, g_object_ref (self));
#endif /* HAVE_AVAHI */
}
#ifdef HAVE_AVAHI
static gboolean
stop_cb (gpointer user_data)
{
g_autoptr(OstreeRepoFinderAvahi) self = OSTREE_REPO_FINDER_AVAHI (user_data);
g_cancellable_cancel (self->avahi_cancellable);
maybe_complete_all_pending_tasks (self);
g_clear_pointer (&self->browser, avahi_service_browser_free);
g_clear_pointer (&self->client, avahi_client_free);
g_hash_table_remove_all (self->resolvers);
return G_SOURCE_REMOVE;
}
#endif /* HAVE_AVAHI */
| 1 | 15,850 | Nitpick: I'd append `_cb` to the function name here to mark it as a callback. Otherwise it looks a bit like this will do the entire job of removing null checksum refs from a hash table. | ostreedev-ostree | c |
@@ -86,8 +86,7 @@ public class Catalog implements AutoCloseable {
tableMap = loadTables(db);
}
Collection<TiTableInfo> tables = tableMap.values();
- tables.removeIf(TiTableInfo::isView);
- return ImmutableList.copyOf(tables);
+ return tables.stream().filter(TiTableInfo::isNotView).collect(Collectors.toList());
}
public TiTableInfo getTable(TiDBInfo db, String tableName) { | 1 | /*
* Copyright 2017 PingCAP, 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,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pingcap.tikv.catalog;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.pingcap.tikv.Snapshot;
import com.pingcap.tikv.meta.TiDBInfo;
import com.pingcap.tikv.meta.TiTableInfo;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
public class Catalog implements AutoCloseable {
private Supplier<Snapshot> snapshotProvider;
private ScheduledExecutorService service;
private CatalogCache metaCache;
private final boolean showRowId;
private final String dbPrefix;
private final Logger logger = Logger.getLogger(this.getClass());
@Override
public void close() throws Exception {
if (service != null) {
service.shutdownNow();
service.awaitTermination(1, TimeUnit.SECONDS);
}
}
private static class CatalogCache {
private CatalogCache(CatalogTransaction transaction, String dbPrefix, boolean loadTables) {
this.transaction = transaction;
this.dbPrefix = dbPrefix;
this.tableCache = new ConcurrentHashMap<>();
this.dbCache = loadDatabases(loadTables);
this.currentVersion = transaction.getLatestSchemaVersion();
}
private final Map<String, TiDBInfo> dbCache;
private final ConcurrentHashMap<TiDBInfo, Map<String, TiTableInfo>> tableCache;
private CatalogTransaction transaction;
private long currentVersion;
private final String dbPrefix;
public CatalogTransaction getTransaction() {
return transaction;
}
public long getVersion() {
return currentVersion;
}
public TiDBInfo getDatabase(String name) {
Objects.requireNonNull(name, "name is null");
return dbCache.get(name.toLowerCase());
}
public List<TiDBInfo> listDatabases() {
return ImmutableList.copyOf(dbCache.values());
}
public List<TiTableInfo> listTables(TiDBInfo db) {
Map<String, TiTableInfo> tableMap = tableCache.get(db);
if (tableMap == null) {
tableMap = loadTables(db);
}
Collection<TiTableInfo> tables = tableMap.values();
tables.removeIf(TiTableInfo::isView);
return ImmutableList.copyOf(tables);
}
public TiTableInfo getTable(TiDBInfo db, String tableName) {
Map<String, TiTableInfo> tableMap = tableCache.get(db);
if (tableMap == null) {
tableMap = loadTables(db);
}
TiTableInfo tbl = tableMap.get(tableName.toLowerCase());
// https://github.com/pingcap/tispark/issues/961
// TODO: support reading from view table in the future.
if (tbl != null && tbl.isView()) return null;
return tbl;
}
private Map<String, TiTableInfo> loadTables(TiDBInfo db) {
List<TiTableInfo> tables = transaction.getTables(db.getId());
ImmutableMap.Builder<String, TiTableInfo> builder = ImmutableMap.builder();
for (TiTableInfo table : tables) {
builder.put(table.getName().toLowerCase(), table);
}
Map<String, TiTableInfo> tableMap = builder.build();
tableCache.put(db, tableMap);
return tableMap;
}
private Map<String, TiDBInfo> loadDatabases(boolean loadTables) {
HashMap<String, TiDBInfo> newDBCache = new HashMap<>();
List<TiDBInfo> databases = transaction.getDatabases();
databases.forEach(
db -> {
TiDBInfo newDBInfo = db.rename(dbPrefix + db.getName());
newDBCache.put(newDBInfo.getName().toLowerCase(), newDBInfo);
if (loadTables) {
loadTables(newDBInfo);
}
});
return newDBCache;
}
}
public Catalog(
Supplier<Snapshot> snapshotProvider,
int refreshPeriod,
TimeUnit periodUnit,
boolean showRowId,
String dbPrefix) {
this.snapshotProvider = Objects.requireNonNull(snapshotProvider, "Snapshot Provider is null");
this.showRowId = showRowId;
this.dbPrefix = dbPrefix;
metaCache = new CatalogCache(new CatalogTransaction(snapshotProvider.get()), dbPrefix, false);
service =
Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder().setDaemon(true).build());
service.scheduleAtFixedRate(
() -> {
// Wrap this with a try catch block in case schedule update fails
try {
reloadCache(true);
} catch (Exception e) {
logger.warn("Reload Cache failed", e);
}
},
refreshPeriod,
refreshPeriod,
periodUnit);
}
public synchronized void reloadCache(boolean loadTables) {
Snapshot snapshot = snapshotProvider.get();
CatalogTransaction newTrx = new CatalogTransaction(snapshot);
long latestVersion = newTrx.getLatestSchemaVersion();
if (latestVersion > metaCache.getVersion()) {
metaCache = new CatalogCache(newTrx, dbPrefix, loadTables);
}
}
public void reloadCache() {
reloadCache(false);
}
public List<TiDBInfo> listDatabases() {
return metaCache.listDatabases();
}
public List<TiTableInfo> listTables(TiDBInfo database) {
Objects.requireNonNull(database, "database is null");
if (showRowId) {
return metaCache
.listTables(database)
.stream()
.map(TiTableInfo::copyTableWithRowId)
.collect(Collectors.toList());
} else {
return metaCache.listTables(database);
}
}
public TiDBInfo getDatabase(String dbName) {
Objects.requireNonNull(dbName, "dbName is null");
TiDBInfo dbInfo = metaCache.getDatabase(dbName);
if (dbInfo == null) {
// reload cache if database does not exist
reloadCache(true);
dbInfo = metaCache.getDatabase(dbName);
}
return dbInfo;
}
public TiTableInfo getTable(String dbName, String tableName) {
TiDBInfo database = getDatabase(dbName);
if (database == null) {
return null;
}
return getTable(database, tableName);
}
public TiTableInfo getTable(TiDBInfo database, String tableName) {
Objects.requireNonNull(database, "database is null");
Objects.requireNonNull(tableName, "tableName is null");
TiTableInfo table = metaCache.getTable(database, tableName);
if (table == null) {
// reload cache if table does not exist
reloadCache(true);
table = metaCache.getTable(database, tableName);
}
if (showRowId && table != null) {
return table.copyTableWithRowId();
} else {
return table;
}
}
@VisibleForTesting
public TiTableInfo getTable(TiDBInfo database, long tableId) {
Objects.requireNonNull(database, "database is null");
Collection<TiTableInfo> tables = listTables(database);
for (TiTableInfo table : tables) {
if (table.getId() == tableId) {
if (showRowId) {
return table.copyTableWithRowId();
} else {
return table;
}
}
}
return null;
}
}
| 1 | 11,043 | or you can use `filter(x => !x.isView)` | pingcap-tispark | java |
@@ -133,7 +133,6 @@ func (c *Cluster) storageBootstrap(ctx context.Context) error {
}
return c.ReconcileBootstrapData(ctx, bytes.NewBuffer(data), &c.config.Runtime.ControlRuntimeBootstrap)
- //return bootstrap.WriteToDiskFromStorage(bytes.NewBuffer(data), &c.runtime.ControlRuntimeBootstrap)
}
// getBootstrapKeyFromStorage will list all keys that has prefix /bootstrap and will check for key that is | 1 | package cluster
import (
"bytes"
"context"
"errors"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/k3s-io/kine/pkg/client"
"github.com/rancher/k3s/pkg/bootstrap"
"github.com/rancher/k3s/pkg/clientaccess"
"github.com/sirupsen/logrus"
)
// save writes the current ControlRuntimeBootstrap data to the datastore. This contains a complete
// snapshot of the cluster's CA certs and keys, encryption passphrases, etc - encrypted with the join token.
// This is used when bootstrapping a cluster from a managed database or external etcd cluster.
// This is NOT used with embedded etcd, which bootstraps over HTTP.
func (c *Cluster) save(ctx context.Context, override bool) error {
buf := &bytes.Buffer{}
if err := bootstrap.ReadFromDisk(buf, &c.runtime.ControlRuntimeBootstrap); err != nil {
return err
}
token := c.config.Token
if token == "" {
tokenFromFile, err := readTokenFromFile(c.runtime.ServerToken, c.runtime.ServerCA, c.config.DataDir)
if err != nil {
return err
}
token = tokenFromFile
}
normalizedToken, err := normalizeToken(token)
if err != nil {
return err
}
data, err := encrypt(normalizedToken, buf.Bytes())
if err != nil {
return err
}
storageClient, err := client.New(c.etcdConfig)
if err != nil {
return err
}
if _, err := c.getBootstrapKeyFromStorage(ctx, storageClient, normalizedToken, token); err != nil {
return err
}
if err := storageClient.Create(ctx, storageKey(normalizedToken), data); err != nil {
if err.Error() == "key exists" {
logrus.Warn("bootstrap key already exists")
if override {
bsd, err := c.bootstrapKeyData(ctx, storageClient)
if err != nil {
return err
}
return storageClient.Update(ctx, storageKey(normalizedToken), bsd.Modified, data)
}
return nil
} else if strings.Contains(err.Error(), "not supported for learner") {
logrus.Debug("skipping bootstrap data save on learner")
return nil
}
return err
}
return nil
}
// bootstrapKeyData lists keys stored in the datastore with the prefix "/bootstrap", and
// will return the first such key. It will return an error if not exactly one key is found.
func (c *Cluster) bootstrapKeyData(ctx context.Context, storageClient client.Client) (*client.Value, error) {
bootstrapList, err := storageClient.List(ctx, "/bootstrap", 0)
if err != nil {
return nil, err
}
if len(bootstrapList) == 0 {
return nil, errors.New("no bootstrap data found")
}
if len(bootstrapList) > 1 {
return nil, errors.New("found multiple bootstrap keys in storage")
}
return &bootstrapList[0], nil
}
// storageBootstrap loads data from the datastore into the ControlRuntimeBootstrap struct.
// The storage key and encryption passphrase are both derived from the join token.
// token is either passed.
func (c *Cluster) storageBootstrap(ctx context.Context) error {
if err := c.startStorage(ctx); err != nil {
return err
}
storageClient, err := client.New(c.etcdConfig)
if err != nil {
return err
}
token := c.config.Token
if token == "" {
tokenFromFile, err := readTokenFromFile(c.runtime.ServerToken, c.runtime.ServerCA, c.config.DataDir)
if err != nil {
return err
}
if tokenFromFile == "" {
// at this point this is a fresh start in a non managed environment
c.saveBootstrap = true
return nil
}
token = tokenFromFile
}
normalizedToken, err := normalizeToken(token)
if err != nil {
return err
}
value, err := c.getBootstrapKeyFromStorage(ctx, storageClient, normalizedToken, token)
if err != nil {
return err
}
if value == nil {
return nil
}
data, err := decrypt(normalizedToken, value.Data)
if err != nil {
return err
}
return c.ReconcileBootstrapData(ctx, bytes.NewBuffer(data), &c.config.Runtime.ControlRuntimeBootstrap)
//return bootstrap.WriteToDiskFromStorage(bytes.NewBuffer(data), &c.runtime.ControlRuntimeBootstrap)
}
// getBootstrapKeyFromStorage will list all keys that has prefix /bootstrap and will check for key that is
// hashed with empty string and will check for any key that is hashed by different token than the one
// passed to it, it will return error if it finds a key that is hashed with different token and will return
// value if it finds the key hashed by passed token or empty string
func (c *Cluster) getBootstrapKeyFromStorage(ctx context.Context, storageClient client.Client, normalizedToken, oldToken string) (*client.Value, error) {
emptyStringKey := storageKey("")
tokenKey := storageKey(normalizedToken)
bootstrapList, err := storageClient.List(ctx, "/bootstrap", 0)
if err != nil {
return nil, err
}
if len(bootstrapList) == 0 {
c.saveBootstrap = true
return nil, nil
}
if len(bootstrapList) > 1 {
logrus.Warn("found multiple bootstrap keys in storage")
}
// check for empty string key and for old token format with k10 prefix
if err := c.migrateOldTokens(ctx, bootstrapList, storageClient, emptyStringKey, tokenKey, normalizedToken, oldToken); err != nil {
return nil, err
}
// getting the list of bootstrap again after migrating the empty key
bootstrapList, err = storageClient.List(ctx, "/bootstrap", 0)
if err != nil {
return nil, err
}
for _, bootstrapKV := range bootstrapList {
// ensure bootstrap is stored in the current token's key
if string(bootstrapKV.Key) == tokenKey {
return &bootstrapKV, nil
}
}
return nil, errors.New("bootstrap data already found and encrypted with different token")
}
// readTokenFromFile will attempt to get the token from <data-dir>/token if it the file not found
// in case of fresh installation it will try to use the runtime serverToken saved in memory
// after stripping it from any additional information like the username or cahash, if the file
// found then it will still strip the token from any additional info
func readTokenFromFile(serverToken, certs, dataDir string) (string, error) {
tokenFile := filepath.Join(dataDir, "token")
b, err := ioutil.ReadFile(tokenFile)
if err != nil {
if os.IsNotExist(err) {
token, err := clientaccess.FormatToken(serverToken, certs)
if err != nil {
return token, err
}
return token, nil
}
return "", err
}
// strip the token from any new line if its read from file
return string(bytes.TrimRight(b, "\n")), nil
}
// normalizeToken will normalize the token read from file or passed as a cli flag
func normalizeToken(token string) (string, error) {
_, password, ok := clientaccess.ParseUsernamePassword(token)
if !ok {
return password, errors.New("failed to normalize token; must be in format K10<CA-HASH>::<USERNAME>:<PASSWORD> or <PASSWORD>")
}
return password, nil
}
// migrateOldTokens will list all keys that has prefix /bootstrap and will check for key that is
// hashed with empty string and keys that is hashed with old token format before normalizing
// then migrate those and resave only with the normalized token
func (c *Cluster) migrateOldTokens(ctx context.Context, bootstrapList []client.Value, storageClient client.Client, emptyStringKey, tokenKey, token, oldToken string) error {
oldTokenKey := storageKey(oldToken)
for _, bootstrapKV := range bootstrapList {
// checking for empty string bootstrap key
if string(bootstrapKV.Key) == emptyStringKey {
logrus.Warn("bootstrap data encrypted with empty string, deleting and resaving with token")
if err := doMigrateToken(ctx, storageClient, bootstrapKV, "", emptyStringKey, token, tokenKey); err != nil {
return err
}
} else if string(bootstrapKV.Key) == oldTokenKey && oldTokenKey != tokenKey {
logrus.Warn("bootstrap data encrypted with old token format string, deleting and resaving with token")
if err := doMigrateToken(ctx, storageClient, bootstrapKV, oldToken, oldTokenKey, token, tokenKey); err != nil {
return err
}
}
}
return nil
}
func doMigrateToken(ctx context.Context, storageClient client.Client, keyValue client.Value, oldToken, oldTokenKey, newToken, newTokenKey string) error {
// make sure that the process is non-destructive by decrypting/re-encrypting/storing the data before deleting the old key
data, err := decrypt(oldToken, keyValue.Data)
if err != nil {
return err
}
encryptedData, err := encrypt(newToken, data)
if err != nil {
return err
}
// saving the new encrypted data with the right token key
if err := storageClient.Create(ctx, newTokenKey, encryptedData); err != nil {
if err.Error() == "key exists" {
logrus.Warn("bootstrap key exists")
} else if strings.Contains(err.Error(), "not supported for learner") {
logrus.Debug("skipping bootstrap data save on learner")
return nil
} else {
return err
}
}
logrus.Infof("created bootstrap key %s", newTokenKey)
// deleting the old key
if err := storageClient.Delete(ctx, oldTokenKey, keyValue.Modified); err != nil {
logrus.Warnf("failed to delete old bootstrap key %s", oldTokenKey)
}
return nil
}
| 1 | 10,294 | Instead of NewBuffer on the line above, do NewReader to avoid having to wrap later. | k3s-io-k3s | go |
@@ -182,6 +182,7 @@ class AsciiDoc:
asciidoc_args = ['--theme=qute', '-a toc', '-a toc-placement=manual']
self.call(modified_src, dst, *asciidoc_args)
+ # pylint: enable=too-many-locals,too-many-statements
def _build_website(self):
"""Prepare and build the website.""" | 1 | #!/usr/bin/env python3
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Generate the html documentation based on the asciidoc files."""
import re
import os
import os.path
import sys
import subprocess
import glob
import shutil
import tempfile
import argparse
import io
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
from scripts import utils
class AsciiDoc:
"""Abstraction of an asciidoc subprocess."""
FILES = ['faq', 'changelog', 'contributing', 'quickstart', 'userscripts']
def __init__(self, args):
self._cmd = None
self._args = args
self._homedir = None
self._themedir = None
self._tempdir = None
self._failed = False
def prepare(self):
"""Get the asciidoc command and create the homedir to use."""
self._cmd = self._get_asciidoc_cmd()
self._homedir = tempfile.mkdtemp()
self._themedir = os.path.join(
self._homedir, '.asciidoc', 'themes', 'qute')
self._tempdir = os.path.join(self._homedir, 'tmp')
os.makedirs(self._tempdir)
os.makedirs(self._themedir)
def cleanup(self):
"""Clean up the temporary home directory for asciidoc."""
if self._homedir is not None and not self._failed:
shutil.rmtree(self._homedir)
def build(self):
if self._args.website:
self._build_website()
else:
self._build_docs()
self._copy_images()
def _build_docs(self):
"""Render .asciidoc files to .html sites."""
files = [('doc/{}.asciidoc'.format(f),
'qutebrowser/html/doc/{}.html'.format(f))
for f in self.FILES]
for src in glob.glob('doc/help/*.asciidoc'):
name, _ext = os.path.splitext(os.path.basename(src))
dst = 'qutebrowser/html/doc/{}.html'.format(name)
files.append((src, dst))
# patch image links to use local copy
replacements = [
("http://qutebrowser.org/img/cheatsheet-big.png",
"qute://help/img/cheatsheet-big.png"),
("http://qutebrowser.org/img/cheatsheet-small.png",
"qute://help/img/cheatsheet-small.png")
]
for src, dst in files:
src_basename = os.path.basename(src)
modified_src = os.path.join(self._tempdir, src_basename)
with open(modified_src, 'w', encoding='utf-8') as modified_f, \
open(src, 'r', encoding='utf-8') as f:
for line in f:
for orig, repl in replacements:
line = line.replace(orig, repl)
modified_f.write(line)
self.call(modified_src, dst)
def _copy_images(self):
"""Copy image files to qutebrowser/html/doc."""
print("Copying files...")
dst_path = os.path.join('qutebrowser', 'html', 'doc', 'img')
try:
os.mkdir(dst_path)
except FileExistsError:
pass
for filename in ['cheatsheet-big.png', 'cheatsheet-small.png']:
src = os.path.join('doc', 'img', filename)
dst = os.path.join(dst_path, filename)
shutil.copy(src, dst)
def _build_website_file(self, root, filename):
"""Build a single website file."""
# pylint: disable=too-many-locals,too-many-statements
src = os.path.join(root, filename)
src_basename = os.path.basename(src)
parts = [self._args.website[0]]
dirname = os.path.dirname(src)
if dirname:
parts.append(os.path.relpath(os.path.dirname(src)))
parts.append(
os.extsep.join((os.path.splitext(src_basename)[0],
'html')))
dst = os.path.join(*parts)
os.makedirs(os.path.dirname(dst), exist_ok=True)
modified_src = os.path.join(self._tempdir, src_basename)
shutil.copy('www/header.asciidoc', modified_src)
outfp = io.StringIO()
with open(modified_src, 'r', encoding='utf-8') as header_file:
header = header_file.read()
header += "\n\n"
with open(src, 'r', encoding='utf-8') as infp:
outfp.write("\n\n")
hidden = False
found_title = False
title = ""
last_line = ""
for line in infp:
if line.strip() == '// QUTE_WEB_HIDE':
assert not hidden
hidden = True
elif line.strip() == '// QUTE_WEB_HIDE_END':
assert hidden
hidden = False
elif line == "The Compiler <mail@qutebrowser.org>\n":
continue
elif re.match(r'^:\w+:.*', line):
# asciidoc field
continue
if not found_title:
if re.match(r'^=+$', line):
line = line.replace('=', '-')
found_title = True
title = last_line.rstrip('\n') + " | qutebrowser\n"
title += "=" * (len(title) - 1)
elif re.match(r'^= .+', line):
line = '==' + line[1:]
found_title = True
title = last_line.rstrip('\n') + " | qutebrowser\n"
title += "=" * (len(title) - 1)
if not hidden:
outfp.write(line.replace(".asciidoc[", ".html["))
last_line = line
current_lines = outfp.getvalue()
outfp.close()
with open(modified_src, 'w+', encoding='utf-8') as final_version:
final_version.write(title + "\n\n" + header + current_lines)
asciidoc_args = ['--theme=qute', '-a toc', '-a toc-placement=manual']
self.call(modified_src, dst, *asciidoc_args)
def _build_website(self):
"""Prepare and build the website."""
theme_file = os.path.abspath(os.path.join('www', 'qute.css'))
shutil.copy(theme_file, self._themedir)
outdir = self._args.website[0]
for root, _dirs, files in os.walk(os.getcwd()):
for filename in files:
basename, ext = os.path.splitext(filename)
if (ext != '.asciidoc' or
basename in ['header', 'OpenSans-License']):
continue
self._build_website_file(root, filename)
copy = {'icons': 'icons', 'doc/img': 'doc/img', 'www/media': 'media/'}
for src, dest in copy.items():
full_dest = os.path.join(outdir, dest)
try:
shutil.rmtree(full_dest)
except FileNotFoundError:
pass
shutil.copytree(src, full_dest)
for dst, link_name in [
('README.html', 'index.html'),
(os.path.join('doc', 'quickstart.html'), 'quickstart.html'),
]:
try:
os.symlink(dst, os.path.join(outdir, link_name))
except FileExistsError:
pass
def _get_asciidoc_cmd(self):
"""Try to find out what commandline to use to invoke asciidoc."""
if self._args.asciidoc is not None:
return self._args.asciidoc
try:
subprocess.call(['asciidoc'], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except OSError:
pass
else:
return ['asciidoc']
try:
subprocess.call(['asciidoc.py'], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except OSError:
pass
else:
return ['asciidoc.py']
raise FileNotFoundError
def call(self, src, dst, *args):
"""Call asciidoc for the given files.
Args:
src: The source .asciidoc file.
dst: The destination .html file, or None to auto-guess.
*args: Additional arguments passed to asciidoc.
"""
print("Calling asciidoc for {}...".format(os.path.basename(src)))
cmdline = self._cmd[:]
if dst is not None:
cmdline += ['--out-file', dst]
cmdline += args
cmdline.append(src)
try:
env = os.environ.copy()
env['HOME'] = self._homedir
subprocess.check_call(cmdline, env=env)
except (subprocess.CalledProcessError, OSError) as e:
self._failed = True
utils.print_col(str(e), 'red')
print("Keeping modified sources in {}.".format(self._homedir))
sys.exit(1)
def main(colors=False):
"""Generate html files for the online documentation."""
utils.change_cwd()
utils.use_color = colors
parser = argparse.ArgumentParser()
parser.add_argument('--website', help="Build website into a given "
"directory.", nargs=1)
parser.add_argument('--asciidoc', help="Full path to python and "
"asciidoc.py. If not given, it's searched in PATH.",
nargs=2, required=False,
metavar=('PYTHON', 'ASCIIDOC'))
args = parser.parse_args()
try:
os.mkdir('qutebrowser/html/doc')
except FileExistsError:
pass
asciidoc = AsciiDoc(args)
try:
asciidoc.prepare()
except FileNotFoundError:
utils.print_col("Could not find asciidoc! Please install it, or use "
"the --asciidoc argument to point this script to the "
"correct python/asciidoc.py location!", 'red')
sys.exit(1)
try:
asciidoc.build()
finally:
asciidoc.cleanup()
if __name__ == '__main__':
main(colors=True)
| 1 | 19,418 | No need for this, as pylint already only turns things off for this function and it's needed for the entire function. | qutebrowser-qutebrowser | py |
@@ -733,7 +733,7 @@ func (eval *BlockEvaluator) transactionGroup(txgroup []transactions.SignedTxnWit
txibs = append(txibs, txib)
if eval.validate {
- groupTxBytes += len(protocol.Encode(&txib))
+ groupTxBytes += txib.GetEncodedLength()
if eval.blockTxBytes+groupTxBytes > eval.proto.MaxTxnBytesPerBlock {
return ErrNoSpace
} | 1 | // Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand 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.
//
// go-algorand 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 go-algorand. If not, see <https://www.gnu.org/licenses/>.
package ledger
import (
"context"
"errors"
"fmt"
"sync"
"github.com/algorand/go-deadlock"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/crypto/compactcert"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/committee"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/data/transactions/logic"
"github.com/algorand/go-algorand/data/transactions/verify"
"github.com/algorand/go-algorand/ledger/apply"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/util/execpool"
)
// ErrNoSpace indicates insufficient space for transaction in block
var ErrNoSpace = errors.New("block does not have space for transaction")
// maxPaysetHint makes sure that we don't allocate too much memory up front
// in the block evaluator, since there cannot reasonably be more than this
// many transactions in a block.
const maxPaysetHint = 20000
type roundCowBase struct {
l ledgerForCowBase
// The round number of the previous block, for looking up prior state.
rnd basics.Round
// TxnCounter from previous block header.
txnCount uint64
// Round of the next expected compact cert. In the common case this
// is CompactCertNextRound from previous block header, except when
// compact certs are first enabled, in which case this gets set
// appropriately at the first block where compact certs are enabled.
compactCertNextRnd basics.Round
// The current protocol consensus params.
proto config.ConsensusParams
// The accounts that we're already accessed during this round evaluation. This is a caching
// buffer used to avoid looking up the same account data more than once during a single evaluator
// execution. The AccountData is always an historical one, then therefore won't be changing.
// The underlying (accountupdates) infrastucture may provide additional cross-round caching which
// are beyond the scope of this cache.
// The account data store here is always the account data without the rewards.
accounts map[basics.Address]basics.AccountData
// accountsMu is the accounts read-write mutex, used to syncronize the access ot the accounts map.
accountsMu deadlock.RWMutex
}
func (x *roundCowBase) getCreator(cidx basics.CreatableIndex, ctype basics.CreatableType) (basics.Address, bool, error) {
return x.l.GetCreatorForRound(x.rnd, cidx, ctype)
}
// lookup returns the non-rewarded account data for the provided account address. It uses the internal per-round cache
// first, and if it cannot find it there, it would defer to the underlaying implementation.
// note that errors in accounts data retrivals are not cached as these typically cause the transaction evaluation to fail.
func (x *roundCowBase) lookup(addr basics.Address) (basics.AccountData, error) {
x.accountsMu.RLock()
if accountData, found := x.accounts[addr]; found {
x.accountsMu.RUnlock()
return accountData, nil
}
x.accountsMu.RUnlock()
accountData, _, err := x.l.LookupWithoutRewards(x.rnd, addr)
if err == nil {
x.accountsMu.Lock()
x.accounts[addr] = accountData
x.accountsMu.Unlock()
}
return accountData, err
}
func (x *roundCowBase) checkDup(firstValid, lastValid basics.Round, txid transactions.Txid, txl ledgercore.Txlease) error {
return x.l.CheckDup(x.proto, x.rnd+1, firstValid, lastValid, txid, TxLease{txl})
}
func (x *roundCowBase) txnCounter() uint64 {
return x.txnCount
}
func (x *roundCowBase) compactCertNext() basics.Round {
return x.compactCertNextRnd
}
func (x *roundCowBase) blockHdr(r basics.Round) (bookkeeping.BlockHeader, error) {
return x.l.BlockHdr(r)
}
func (x *roundCowBase) allocated(addr basics.Address, aidx basics.AppIndex, global bool) (bool, error) {
acct, _, err := x.l.LookupWithoutRewards(x.rnd, addr)
if err != nil {
return false, err
}
// For global, check if app params exist
if global {
_, ok := acct.AppParams[aidx]
return ok, nil
}
// Otherwise, check app local states
_, ok := acct.AppLocalStates[aidx]
return ok, nil
}
// getKey gets the value for a particular key in some storage
// associated with an application globally or locally
func (x *roundCowBase) getKey(addr basics.Address, aidx basics.AppIndex, global bool, key string) (basics.TealValue, bool, error) {
ad, _, err := x.l.LookupWithoutRewards(x.rnd, addr)
if err != nil {
return basics.TealValue{}, false, err
}
exist := false
kv := basics.TealKeyValue{}
if global {
var app basics.AppParams
if app, exist = ad.AppParams[aidx]; exist {
kv = app.GlobalState
}
} else {
var ls basics.AppLocalState
if ls, exist = ad.AppLocalStates[aidx]; exist {
kv = ls.KeyValue
}
}
if !exist {
err = fmt.Errorf("cannot fetch key, %v", errNoStorage(addr, aidx, global))
return basics.TealValue{}, false, err
}
val, exist := kv[key]
return val, exist, nil
}
// getStorageCounts counts the storage types used by some account
// associated with an application globally or locally
func (x *roundCowBase) getStorageCounts(addr basics.Address, aidx basics.AppIndex, global bool) (basics.StateSchema, error) {
ad, _, err := x.l.LookupWithoutRewards(x.rnd, addr)
if err != nil {
return basics.StateSchema{}, err
}
count := basics.StateSchema{}
exist := false
kv := basics.TealKeyValue{}
if global {
var app basics.AppParams
if app, exist = ad.AppParams[aidx]; exist {
kv = app.GlobalState
}
} else {
var ls basics.AppLocalState
if ls, exist = ad.AppLocalStates[aidx]; exist {
kv = ls.KeyValue
}
}
if !exist {
return count, nil
}
for _, v := range kv {
if v.Type == basics.TealUintType {
count.NumUint++
} else {
count.NumByteSlice++
}
}
return count, nil
}
func (x *roundCowBase) getStorageLimits(addr basics.Address, aidx basics.AppIndex, global bool) (basics.StateSchema, error) {
creator, exists, err := x.getCreator(basics.CreatableIndex(aidx), basics.AppCreatable)
if err != nil {
return basics.StateSchema{}, err
}
// App doesn't exist, so no storage may be allocated.
if !exists {
return basics.StateSchema{}, nil
}
record, err := x.lookup(creator)
if err != nil {
return basics.StateSchema{}, err
}
params, ok := record.AppParams[aidx]
if !ok {
// This should never happen. If app exists then we should have
// found the creator successfully.
err = fmt.Errorf("app %d not found in account %s", aidx, creator.String())
return basics.StateSchema{}, err
}
if global {
return params.GlobalStateSchema, nil
}
return params.LocalStateSchema, nil
}
// wrappers for roundCowState to satisfy the (current) apply.Balances interface
func (cs *roundCowState) Get(addr basics.Address, withPendingRewards bool) (basics.AccountData, error) {
acct, err := cs.lookup(addr)
if err != nil {
return basics.AccountData{}, err
}
if withPendingRewards {
acct = acct.WithUpdatedRewards(cs.proto, cs.rewardsLevel())
}
return acct, nil
}
func (cs *roundCowState) GetCreator(cidx basics.CreatableIndex, ctype basics.CreatableType) (basics.Address, bool, error) {
return cs.getCreator(cidx, ctype)
}
func (cs *roundCowState) Put(addr basics.Address, acct basics.AccountData) error {
return cs.PutWithCreatable(addr, acct, nil, nil)
}
func (cs *roundCowState) PutWithCreatable(addr basics.Address, acct basics.AccountData, newCreatable *basics.CreatableLocator, deletedCreatable *basics.CreatableLocator) error {
cs.put(addr, acct, newCreatable, deletedCreatable)
return nil
}
func (cs *roundCowState) Move(from basics.Address, to basics.Address, amt basics.MicroAlgos, fromRewards *basics.MicroAlgos, toRewards *basics.MicroAlgos) error {
rewardlvl := cs.rewardsLevel()
fromBal, err := cs.lookup(from)
if err != nil {
return err
}
fromBalNew := fromBal.WithUpdatedRewards(cs.proto, rewardlvl)
if fromRewards != nil {
var ot basics.OverflowTracker
newFromRewards := ot.AddA(*fromRewards, ot.SubA(fromBalNew.MicroAlgos, fromBal.MicroAlgos))
if ot.Overflowed {
return fmt.Errorf("overflowed tracking of fromRewards for account %v: %d + (%d - %d)", from, *fromRewards, fromBalNew.MicroAlgos, fromBal.MicroAlgos)
}
*fromRewards = newFromRewards
}
var overflowed bool
fromBalNew.MicroAlgos, overflowed = basics.OSubA(fromBalNew.MicroAlgos, amt)
if overflowed {
return fmt.Errorf("overspend (account %v, data %+v, tried to spend %v)", from, fromBal, amt)
}
cs.put(from, fromBalNew, nil, nil)
toBal, err := cs.lookup(to)
if err != nil {
return err
}
toBalNew := toBal.WithUpdatedRewards(cs.proto, rewardlvl)
if toRewards != nil {
var ot basics.OverflowTracker
newToRewards := ot.AddA(*toRewards, ot.SubA(toBalNew.MicroAlgos, toBal.MicroAlgos))
if ot.Overflowed {
return fmt.Errorf("overflowed tracking of toRewards for account %v: %d + (%d - %d)", to, *toRewards, toBalNew.MicroAlgos, toBal.MicroAlgos)
}
*toRewards = newToRewards
}
toBalNew.MicroAlgos, overflowed = basics.OAddA(toBalNew.MicroAlgos, amt)
if overflowed {
return fmt.Errorf("balance overflow (account %v, data %+v, was going to receive %v)", to, toBal, amt)
}
cs.put(to, toBalNew, nil, nil)
return nil
}
func (cs *roundCowState) ConsensusParams() config.ConsensusParams {
return cs.proto
}
func (cs *roundCowState) compactCert(certRnd basics.Round, certType protocol.CompactCertType, cert compactcert.Cert, atRound basics.Round) error {
if certType != protocol.CompactCertBasic {
return fmt.Errorf("compact cert type %d not supported", certType)
}
nextCertRnd := cs.compactCertNext()
certHdr, err := cs.blockHdr(certRnd)
if err != nil {
return err
}
proto := config.Consensus[certHdr.CurrentProtocol]
votersRnd := certRnd.SubSaturate(basics.Round(proto.CompactCertRounds))
votersHdr, err := cs.blockHdr(votersRnd)
if err != nil {
return err
}
err = validateCompactCert(certHdr, cert, votersHdr, nextCertRnd, atRound)
if err != nil {
return err
}
cs.setCompactCertNext(certRnd + basics.Round(proto.CompactCertRounds))
return nil
}
// BlockEvaluator represents an in-progress evaluation of a block
// against the ledger.
type BlockEvaluator struct {
state *roundCowState
validate bool
generate bool
prevHeader bookkeeping.BlockHeader // cached
proto config.ConsensusParams
genesisHash crypto.Digest
block bookkeeping.Block
blockTxBytes int
blockGenerated bool // prevent repeated GenerateBlock calls
l ledgerForEvaluator
}
type ledgerForEvaluator interface {
ledgerForCowBase
GenesisHash() crypto.Digest
Totals(basics.Round) (ledgercore.AccountTotals, error)
CompactCertVoters(basics.Round) (*VotersForRound, error)
}
// ledgerForCowBase represents subset of Ledger functionality needed for cow business
type ledgerForCowBase interface {
BlockHdr(basics.Round) (bookkeeping.BlockHeader, error)
CheckDup(config.ConsensusParams, basics.Round, basics.Round, basics.Round, transactions.Txid, TxLease) error
LookupWithoutRewards(basics.Round, basics.Address) (basics.AccountData, basics.Round, error)
GetCreatorForRound(basics.Round, basics.CreatableIndex, basics.CreatableType) (basics.Address, bool, error)
}
// StartEvaluator creates a BlockEvaluator, given a ledger and a block header
// of the block that the caller is planning to evaluate. If the length of the
// payset being evaluated is known in advance, a paysetHint >= 0 can be
// passed, avoiding unnecessary payset slice growth.
func (l *Ledger) StartEvaluator(hdr bookkeeping.BlockHeader, paysetHint int) (*BlockEvaluator, error) {
return startEvaluator(l, hdr, paysetHint, true, true)
}
func startEvaluator(l ledgerForEvaluator, hdr bookkeeping.BlockHeader, paysetHint int, validate bool, generate bool) (*BlockEvaluator, error) {
proto, ok := config.Consensus[hdr.CurrentProtocol]
if !ok {
return nil, protocol.Error(hdr.CurrentProtocol)
}
base := &roundCowBase{
l: l,
// round that lookups come from is previous block. We validate
// the block at this round below, so underflow will be caught.
// If we are not validating, we must have previously checked
// an agreement.Certificate attesting that hdr is valid.
rnd: hdr.Round - 1,
proto: proto,
accounts: make(map[basics.Address]basics.AccountData),
}
eval := &BlockEvaluator{
validate: validate,
generate: generate,
block: bookkeeping.Block{BlockHeader: hdr},
proto: proto,
genesisHash: l.GenesisHash(),
l: l,
}
// Preallocate space for the payset so that we don't have to
// dynamically grow a slice (if evaluating a whole block).
if paysetHint > 0 {
if paysetHint > maxPaysetHint {
paysetHint = maxPaysetHint
}
eval.block.Payset = make([]transactions.SignedTxnInBlock, 0, paysetHint)
}
prevProto := proto
if hdr.Round > 0 {
var err error
eval.prevHeader, err = l.BlockHdr(base.rnd)
if err != nil {
return nil, fmt.Errorf("can't evaluate block %v without previous header: %v", hdr.Round, err)
}
base.txnCount = eval.prevHeader.TxnCounter
base.compactCertNextRnd = eval.prevHeader.CompactCert[protocol.CompactCertBasic].CompactCertNextRound
prevProto, ok = config.Consensus[eval.prevHeader.CurrentProtocol]
if !ok {
return nil, protocol.Error(eval.prevHeader.CurrentProtocol)
}
// Check if compact certs are being enabled as of this block.
if base.compactCertNextRnd == 0 && proto.CompactCertRounds != 0 {
// Determine the first block that will contain a Merkle
// commitment to the voters. We need to account for the
// fact that the voters come from CompactCertVotersLookback
// rounds ago.
votersRound := (hdr.Round + basics.Round(proto.CompactCertVotersLookback)).RoundUpToMultipleOf(basics.Round(proto.CompactCertRounds))
// The first compact cert will appear CompactCertRounds after that.
base.compactCertNextRnd = votersRound + basics.Round(proto.CompactCertRounds)
}
}
prevTotals, err := l.Totals(eval.prevHeader.Round)
if err != nil {
return nil, err
}
poolAddr := eval.prevHeader.RewardsPool
// get the reward pool account data without any rewards
incentivePoolData, _, err := l.LookupWithoutRewards(eval.prevHeader.Round, poolAddr)
if err != nil {
return nil, err
}
// this is expected to be a no-op, but update the rewards on the rewards pool if it was configured to receive rewards ( unlike mainnet ).
incentivePoolData = incentivePoolData.WithUpdatedRewards(prevProto, eval.prevHeader.RewardsLevel)
if generate {
if eval.proto.SupportGenesisHash {
eval.block.BlockHeader.GenesisHash = eval.genesisHash
}
eval.block.BlockHeader.RewardsState = eval.prevHeader.NextRewardsState(hdr.Round, proto, incentivePoolData.MicroAlgos, prevTotals.RewardUnits())
}
// set the eval state with the current header
eval.state = makeRoundCowState(base, eval.block.BlockHeader, eval.prevHeader.TimeStamp, paysetHint)
if validate {
err := eval.block.BlockHeader.PreCheck(eval.prevHeader)
if err != nil {
return nil, err
}
// Check that the rewards rate, level and residue match expected values
expectedRewardsState := eval.prevHeader.NextRewardsState(hdr.Round, proto, incentivePoolData.MicroAlgos, prevTotals.RewardUnits())
if eval.block.RewardsState != expectedRewardsState {
return nil, fmt.Errorf("bad rewards state: %+v != %+v", eval.block.RewardsState, expectedRewardsState)
}
// For backwards compatibility: introduce Genesis Hash value
if eval.proto.SupportGenesisHash && eval.block.BlockHeader.GenesisHash != eval.genesisHash {
return nil, fmt.Errorf("wrong genesis hash: %s != %s", eval.block.BlockHeader.GenesisHash, eval.genesisHash)
}
}
// Withdraw rewards from the incentive pool
var ot basics.OverflowTracker
rewardsPerUnit := ot.Sub(eval.block.BlockHeader.RewardsLevel, eval.prevHeader.RewardsLevel)
if ot.Overflowed {
return nil, fmt.Errorf("overflowed subtracting rewards(%d, %d) levels for block %v", eval.block.BlockHeader.RewardsLevel, eval.prevHeader.RewardsLevel, hdr.Round)
}
poolOld, err := eval.state.Get(poolAddr, true)
if err != nil {
return nil, err
}
// hotfix for testnet stall 08/26/2019; move some algos from testnet bank to rewards pool to give it enough time until protocol upgrade occur.
// hotfix for testnet stall 11/07/2019; the same bug again, account ran out before the protocol upgrade occurred.
poolOld, err = eval.workaroundOverspentRewards(poolOld, hdr.Round)
if err != nil {
return nil, err
}
poolNew := poolOld
poolNew.MicroAlgos = ot.SubA(poolOld.MicroAlgos, basics.MicroAlgos{Raw: ot.Mul(prevTotals.RewardUnits(), rewardsPerUnit)})
if ot.Overflowed {
return nil, fmt.Errorf("overflowed subtracting reward unit for block %v", hdr.Round)
}
err = eval.state.Put(poolAddr, poolNew)
if err != nil {
return nil, err
}
// ensure that we have at least MinBalance after withdrawing rewards
ot.SubA(poolNew.MicroAlgos, basics.MicroAlgos{Raw: proto.MinBalance})
if ot.Overflowed {
// TODO this should never happen; should we panic here?
return nil, fmt.Errorf("overflowed subtracting rewards for block %v", hdr.Round)
}
return eval, nil
}
// hotfix for testnet stall 08/26/2019; move some algos from testnet bank to rewards pool to give it enough time until protocol upgrade occur.
// hotfix for testnet stall 11/07/2019; do the same thing
func (eval *BlockEvaluator) workaroundOverspentRewards(rewardPoolBalance basics.AccountData, headerRound basics.Round) (poolOld basics.AccountData, err error) {
// verify that we patch the correct round.
if headerRound != 1499995 && headerRound != 2926564 {
return rewardPoolBalance, nil
}
// verify that we're patching the correct genesis ( i.e. testnet )
testnetGenesisHash, _ := crypto.DigestFromString("JBR3KGFEWPEE5SAQ6IWU6EEBZMHXD4CZU6WCBXWGF57XBZIJHIRA")
if eval.genesisHash != testnetGenesisHash {
return rewardPoolBalance, nil
}
// get the testnet bank ( dispenser ) account address.
bankAddr, _ := basics.UnmarshalChecksumAddress("GD64YIY3TWGDMCNPP553DZPPR6LDUSFQOIJVFDPPXWEG3FVOJCCDBBHU5A")
amount := basics.MicroAlgos{Raw: 20000000000}
err = eval.state.Move(bankAddr, eval.prevHeader.RewardsPool, amount, nil, nil)
if err != nil {
err = fmt.Errorf("unable to move funds from testnet bank to incentive pool: %v", err)
return
}
poolOld, err = eval.state.Get(eval.prevHeader.RewardsPool, true)
return
}
// TxnCounter returns the number of transactions that have been added to the block evaluator so far.
func (eval *BlockEvaluator) TxnCounter() int {
return len(eval.block.Payset)
}
// Round returns the round number of the block being evaluated by the BlockEvaluator.
func (eval *BlockEvaluator) Round() basics.Round {
return eval.block.Round()
}
// ResetTxnBytes resets the number of bytes tracked by the BlockEvaluator to
// zero. This is a specialized operation used by the transaction pool to
// simulate the effect of putting pending transactions in multiple blocks.
func (eval *BlockEvaluator) ResetTxnBytes() {
eval.blockTxBytes = 0
}
// TestTransactionGroup performs basic duplicate detection and well-formedness checks
// on a transaction group, but does not actually add the transactions to the block
// evaluator, or modify the block evaluator state in any other visible way.
func (eval *BlockEvaluator) TestTransactionGroup(txgroup []transactions.SignedTxn) error {
// Nothing to do if there are no transactions.
if len(txgroup) == 0 {
return nil
}
if len(txgroup) > eval.proto.MaxTxGroupSize {
return fmt.Errorf("group size %d exceeds maximum %d", len(txgroup), eval.proto.MaxTxGroupSize)
}
cow := eval.state.child()
var group transactions.TxGroup
for gi, txn := range txgroup {
err := eval.testTransaction(txn, cow)
if err != nil {
return err
}
// Make sure all transactions in group have the same group value
if txn.Txn.Group != txgroup[0].Txn.Group {
return fmt.Errorf("transactionGroup: inconsistent group values: %v != %v",
txn.Txn.Group, txgroup[0].Txn.Group)
}
if !txn.Txn.Group.IsZero() {
txWithoutGroup := txn.Txn
txWithoutGroup.Group = crypto.Digest{}
group.TxGroupHashes = append(group.TxGroupHashes, crypto.HashObj(txWithoutGroup))
} else if len(txgroup) > 1 {
return fmt.Errorf("transactionGroup: [%d] had zero Group but was submitted in a group of %d", gi, len(txgroup))
}
}
// If we had a non-zero Group value, check that all group members are present.
if group.TxGroupHashes != nil {
if txgroup[0].Txn.Group != crypto.HashObj(group) {
return fmt.Errorf("transactionGroup: incomplete group: %v != %v (%v)",
txgroup[0].Txn.Group, crypto.HashObj(group), group)
}
}
return nil
}
// testTransaction performs basic duplicate detection and well-formedness checks
// on a single transaction, but does not actually add the transaction to the block
// evaluator, or modify the block evaluator state in any other visible way.
func (eval *BlockEvaluator) testTransaction(txn transactions.SignedTxn, cow *roundCowState) error {
// Transaction valid (not expired)?
err := txn.Txn.Alive(eval.block)
if err != nil {
return err
}
// Well-formed on its own?
spec := transactions.SpecialAddresses{
FeeSink: eval.block.BlockHeader.FeeSink,
RewardsPool: eval.block.BlockHeader.RewardsPool,
}
err = txn.Txn.WellFormed(spec, eval.proto)
if err != nil {
return fmt.Errorf("transaction %v: malformed: %v", txn.ID(), err)
}
// Transaction already in the ledger?
txid := txn.ID()
err = cow.checkDup(txn.Txn.First(), txn.Txn.Last(), txid, ledgercore.Txlease{Sender: txn.Txn.Sender, Lease: txn.Txn.Lease})
if err != nil {
return err
}
return nil
}
// Transaction tentatively adds a new transaction as part of this block evaluation.
// If the transaction cannot be added to the block without violating some constraints,
// an error is returned and the block evaluator state is unchanged.
func (eval *BlockEvaluator) Transaction(txn transactions.SignedTxn, ad transactions.ApplyData) error {
return eval.transactionGroup([]transactions.SignedTxnWithAD{
{
SignedTxn: txn,
ApplyData: ad,
},
})
}
// TransactionGroup tentatively adds a new transaction group as part of this block evaluation.
// If the transaction group cannot be added to the block without violating some constraints,
// an error is returned and the block evaluator state is unchanged.
func (eval *BlockEvaluator) TransactionGroup(txads []transactions.SignedTxnWithAD) error {
return eval.transactionGroup(txads)
}
// prepareEvalParams creates a logic.EvalParams for each ApplicationCall
// transaction in the group
func (eval *BlockEvaluator) prepareEvalParams(txgroup []transactions.SignedTxnWithAD) (res []*logic.EvalParams) {
var groupNoAD []transactions.SignedTxn
var minTealVersion uint64
res = make([]*logic.EvalParams, len(txgroup))
for i, txn := range txgroup {
// Ignore any non-ApplicationCall transactions
if txn.SignedTxn.Txn.Type != protocol.ApplicationCallTx {
continue
}
// Initialize group without ApplyData lazily
if groupNoAD == nil {
groupNoAD = make([]transactions.SignedTxn, len(txgroup))
for j := range txgroup {
groupNoAD[j] = txgroup[j].SignedTxn
}
minTealVersion = logic.ComputeMinTealVersion(groupNoAD)
}
res[i] = &logic.EvalParams{
Txn: &groupNoAD[i],
Proto: &eval.proto,
TxnGroup: groupNoAD,
GroupIndex: i,
MinTealVersion: &minTealVersion,
}
}
return
}
// transactionGroup tentatively executes a group of transactions as part of this block evaluation.
// If the transaction group cannot be added to the block without violating some constraints,
// an error is returned and the block evaluator state is unchanged.
func (eval *BlockEvaluator) transactionGroup(txgroup []transactions.SignedTxnWithAD) error {
// Nothing to do if there are no transactions.
if len(txgroup) == 0 {
return nil
}
if len(txgroup) > eval.proto.MaxTxGroupSize {
return fmt.Errorf("group size %d exceeds maximum %d", len(txgroup), eval.proto.MaxTxGroupSize)
}
var txibs []transactions.SignedTxnInBlock
var group transactions.TxGroup
var groupTxBytes int
cow := eval.state.child()
// Prepare eval params for any ApplicationCall transactions in the group
evalParams := eval.prepareEvalParams(txgroup)
// Evaluate each transaction in the group
txibs = make([]transactions.SignedTxnInBlock, 0, len(txgroup))
for gi, txad := range txgroup {
var txib transactions.SignedTxnInBlock
err := eval.transaction(txad.SignedTxn, evalParams[gi], txad.ApplyData, cow, &txib)
if err != nil {
return err
}
txibs = append(txibs, txib)
if eval.validate {
groupTxBytes += len(protocol.Encode(&txib))
if eval.blockTxBytes+groupTxBytes > eval.proto.MaxTxnBytesPerBlock {
return ErrNoSpace
}
}
// Make sure all transactions in group have the same group value
if txad.SignedTxn.Txn.Group != txgroup[0].SignedTxn.Txn.Group {
return fmt.Errorf("transactionGroup: inconsistent group values: %v != %v",
txad.SignedTxn.Txn.Group, txgroup[0].SignedTxn.Txn.Group)
}
if !txad.SignedTxn.Txn.Group.IsZero() {
txWithoutGroup := txad.SignedTxn.Txn
txWithoutGroup.Group = crypto.Digest{}
group.TxGroupHashes = append(group.TxGroupHashes, crypto.HashObj(txWithoutGroup))
} else if len(txgroup) > 1 {
return fmt.Errorf("transactionGroup: [%d] had zero Group but was submitted in a group of %d", gi, len(txgroup))
}
}
// If we had a non-zero Group value, check that all group members are present.
if group.TxGroupHashes != nil {
if txgroup[0].SignedTxn.Txn.Group != crypto.HashObj(group) {
return fmt.Errorf("transactionGroup: incomplete group: %v != %v (%v)",
txgroup[0].SignedTxn.Txn.Group, crypto.HashObj(group), group)
}
}
eval.block.Payset = append(eval.block.Payset, txibs...)
eval.blockTxBytes += groupTxBytes
cow.commitToParent()
return nil
}
// transaction tentatively executes a new transaction as part of this block evaluation.
// If the transaction cannot be added to the block without violating some constraints,
// an error is returned and the block evaluator state is unchanged.
func (eval *BlockEvaluator) transaction(txn transactions.SignedTxn, evalParams *logic.EvalParams, ad transactions.ApplyData, cow *roundCowState, txib *transactions.SignedTxnInBlock) error {
var err error
// Only compute the TxID once
txid := txn.ID()
if eval.validate {
err = txn.Txn.Alive(eval.block)
if err != nil {
return err
}
// Transaction already in the ledger?
err := cow.checkDup(txn.Txn.First(), txn.Txn.Last(), txid, ledgercore.Txlease{Sender: txn.Txn.Sender, Lease: txn.Txn.Lease})
if err != nil {
return err
}
// Does the address that authorized the transaction actually match whatever address the sender has rekeyed to?
// i.e., the sig/lsig/msig was checked against the txn.Authorizer() address, but does this match the sender's balrecord.AuthAddr?
acctdata, err := cow.lookup(txn.Txn.Sender)
if err != nil {
return err
}
correctAuthorizer := acctdata.AuthAddr
if (correctAuthorizer == basics.Address{}) {
correctAuthorizer = txn.Txn.Sender
}
if txn.Authorizer() != correctAuthorizer {
return fmt.Errorf("transaction %v: should have been authorized by %v but was actually authorized by %v", txn.ID(), correctAuthorizer, txn.Authorizer())
}
}
spec := transactions.SpecialAddresses{
FeeSink: eval.block.BlockHeader.FeeSink,
RewardsPool: eval.block.BlockHeader.RewardsPool,
}
// Apply the transaction, updating the cow balances
applyData, err := applyTransaction(txn.Txn, cow, evalParams, spec, cow.txnCounter())
if err != nil {
return fmt.Errorf("transaction %v: %v", txid, err)
}
// Validate applyData if we are validating an existing block.
// If we are validating and generating, we have no ApplyData yet.
if eval.validate && !eval.generate {
if eval.proto.ApplyData {
if !ad.Equal(applyData) {
return fmt.Errorf("transaction %v: applyData mismatch: %v != %v", txid, ad, applyData)
}
} else {
if !ad.Equal(transactions.ApplyData{}) {
return fmt.Errorf("transaction %v: applyData not supported", txid)
}
}
}
// Check if the transaction fits in the block, now that we can encode it.
*txib, err = eval.block.EncodeSignedTxn(txn, applyData)
if err != nil {
return err
}
// Check if any affected accounts dipped below MinBalance (unless they are
// completely zero, which means the account will be deleted.)
rewardlvl := cow.rewardsLevel()
for _, addr := range cow.modifiedAccounts() {
// Skip FeeSink, RewardsPool, and CompactCertSender MinBalance checks here.
// There's only a few accounts, so space isn't an issue, and we don't
// expect them to have low balances, but if they do, it may cause
// surprises.
if addr == spec.FeeSink || addr == spec.RewardsPool || addr == transactions.CompactCertSender {
continue
}
data, err := cow.lookup(addr)
if err != nil {
return err
}
// It's always OK to have the account move to an empty state,
// because the accounts DB can delete it. Otherwise, we will
// enforce MinBalance.
if data.IsZero() {
continue
}
dataNew := data.WithUpdatedRewards(eval.proto, rewardlvl)
effectiveMinBalance := dataNew.MinBalance(&eval.proto)
if dataNew.MicroAlgos.Raw < effectiveMinBalance.Raw {
return fmt.Errorf("transaction %v: account %v balance %d below min %d (%d assets)",
txid, addr, dataNew.MicroAlgos.Raw, effectiveMinBalance.Raw, len(dataNew.Assets))
}
// Check if we have exceeded the maximum minimum balance
if eval.proto.MaximumMinimumBalance != 0 {
if effectiveMinBalance.Raw > eval.proto.MaximumMinimumBalance {
return fmt.Errorf("transaction %v: account %v would use too much space after this transaction. Minimum balance requirements would be %d (greater than max %d)", txid, addr, effectiveMinBalance.Raw, eval.proto.MaximumMinimumBalance)
}
}
}
// Remember this txn
cow.addTx(txn.Txn, txid)
return nil
}
// applyTransaction changes the balances according to this transaction.
func applyTransaction(tx transactions.Transaction, balances *roundCowState, evalParams *logic.EvalParams, spec transactions.SpecialAddresses, ctr uint64) (ad transactions.ApplyData, err error) {
params := balances.ConsensusParams()
// move fee to pool
err = balances.Move(tx.Sender, spec.FeeSink, tx.Fee, &ad.SenderRewards, nil)
if err != nil {
return
}
// rekeying: update balrecord.AuthAddr to tx.RekeyTo if provided
if (tx.RekeyTo != basics.Address{}) {
var acct basics.AccountData
acct, err = balances.Get(tx.Sender, false)
if err != nil {
return
}
// Special case: rekeying to the account's actual address just sets acct.AuthAddr to 0
// This saves 32 bytes in your balance record if you want to go back to using your original key
if tx.RekeyTo == tx.Sender {
acct.AuthAddr = basics.Address{}
} else {
acct.AuthAddr = tx.RekeyTo
}
err = balances.Put(tx.Sender, acct)
if err != nil {
return
}
}
switch tx.Type {
case protocol.PaymentTx:
err = apply.Payment(tx.PaymentTxnFields, tx.Header, balances, spec, &ad)
case protocol.KeyRegistrationTx:
err = apply.Keyreg(tx.KeyregTxnFields, tx.Header, balances, spec, &ad)
case protocol.AssetConfigTx:
err = apply.AssetConfig(tx.AssetConfigTxnFields, tx.Header, balances, spec, &ad, ctr)
case protocol.AssetTransferTx:
err = apply.AssetTransfer(tx.AssetTransferTxnFields, tx.Header, balances, spec, &ad)
case protocol.AssetFreezeTx:
err = apply.AssetFreeze(tx.AssetFreezeTxnFields, tx.Header, balances, spec, &ad)
case protocol.ApplicationCallTx:
err = apply.ApplicationCall(tx.ApplicationCallTxnFields, tx.Header, balances, &ad, evalParams, ctr)
case protocol.CompactCertTx:
err = balances.compactCert(tx.CertRound, tx.CertType, tx.Cert, tx.Header.FirstValid)
default:
err = fmt.Errorf("Unknown transaction type %v", tx.Type)
}
// If the protocol does not support rewards in ApplyData,
// clear them out.
if !params.RewardsInApplyData {
ad.SenderRewards = basics.MicroAlgos{}
ad.ReceiverRewards = basics.MicroAlgos{}
ad.CloseRewards = basics.MicroAlgos{}
}
return
}
// compactCertVotersAndTotal returns the expected values of CompactCertVoters
// and CompactCertVotersTotal for a block.
func (eval *BlockEvaluator) compactCertVotersAndTotal() (root crypto.Digest, total basics.MicroAlgos, err error) {
if eval.proto.CompactCertRounds == 0 {
return
}
if eval.block.Round()%basics.Round(eval.proto.CompactCertRounds) != 0 {
return
}
lookback := eval.block.Round().SubSaturate(basics.Round(eval.proto.CompactCertVotersLookback))
voters, err := eval.l.CompactCertVoters(lookback)
if err != nil {
return
}
if voters != nil {
root = voters.Tree.Root()
total = voters.TotalWeight
}
return
}
// Call "endOfBlock" after all the block's rewards and transactions are processed.
func (eval *BlockEvaluator) endOfBlock() error {
if eval.generate {
eval.block.TxnRoot = eval.block.Payset.Commit(eval.proto.PaysetCommitFlat)
if eval.proto.TxnCounter {
eval.block.TxnCounter = eval.state.txnCounter()
} else {
eval.block.TxnCounter = 0
}
if eval.proto.CompactCertRounds > 0 {
var basicCompactCert bookkeeping.CompactCertState
var err error
basicCompactCert.CompactCertVoters, basicCompactCert.CompactCertVotersTotal, err = eval.compactCertVotersAndTotal()
if err != nil {
return err
}
basicCompactCert.CompactCertNextRound = eval.state.compactCertNext()
eval.block.CompactCert = make(map[protocol.CompactCertType]bookkeeping.CompactCertState)
eval.block.CompactCert[protocol.CompactCertBasic] = basicCompactCert
}
}
return nil
}
// FinalValidation does the validation that must happen after the block is built and all state updates are computed
func (eval *BlockEvaluator) finalValidation() error {
if eval.validate {
// check commitments
txnRoot := eval.block.Payset.Commit(eval.proto.PaysetCommitFlat)
if txnRoot != eval.block.TxnRoot {
return fmt.Errorf("txn root wrong: %v != %v", txnRoot, eval.block.TxnRoot)
}
var expectedTxnCount uint64
if eval.proto.TxnCounter {
expectedTxnCount = eval.state.txnCounter()
}
if eval.block.TxnCounter != expectedTxnCount {
return fmt.Errorf("txn count wrong: %d != %d", eval.block.TxnCounter, expectedTxnCount)
}
expectedVoters, expectedVotersWeight, err := eval.compactCertVotersAndTotal()
if err != nil {
return err
}
if eval.block.CompactCert[protocol.CompactCertBasic].CompactCertVoters != expectedVoters {
return fmt.Errorf("CompactCertVoters wrong: %v != %v", eval.block.CompactCert[protocol.CompactCertBasic].CompactCertVoters, expectedVoters)
}
if eval.block.CompactCert[protocol.CompactCertBasic].CompactCertVotersTotal != expectedVotersWeight {
return fmt.Errorf("CompactCertVotersTotal wrong: %v != %v", eval.block.CompactCert[protocol.CompactCertBasic].CompactCertVotersTotal, expectedVotersWeight)
}
if eval.block.CompactCert[protocol.CompactCertBasic].CompactCertNextRound != eval.state.compactCertNext() {
return fmt.Errorf("CompactCertNextRound wrong: %v != %v", eval.block.CompactCert[protocol.CompactCertBasic].CompactCertNextRound, eval.state.compactCertNext())
}
for ccType := range eval.block.CompactCert {
if ccType != protocol.CompactCertBasic {
return fmt.Errorf("CompactCertType %d unexpected", ccType)
}
}
}
return nil
}
// GenerateBlock produces a complete block from the BlockEvaluator. This is
// used during proposal to get an actual block that will be proposed, after
// feeding in tentative transactions into this block evaluator.
//
// After a call to GenerateBlock, the BlockEvaluator can still be used to
// accept transactions. However, to guard against reuse, subsequent calls
// to GenerateBlock on the same BlockEvaluator will fail.
func (eval *BlockEvaluator) GenerateBlock() (*ValidatedBlock, error) {
if !eval.generate {
logging.Base().Panicf("GenerateBlock() called but generate is false")
}
if eval.blockGenerated {
return nil, fmt.Errorf("GenerateBlock already called on this BlockEvaluator")
}
err := eval.endOfBlock()
if err != nil {
return nil, err
}
err = eval.finalValidation()
if err != nil {
return nil, err
}
vb := ValidatedBlock{
blk: eval.block,
delta: eval.state.deltas(),
}
eval.blockGenerated = true
eval.state = makeRoundCowState(eval.state, eval.block.BlockHeader, eval.prevHeader.TimeStamp, len(eval.block.Payset))
return &vb, nil
}
type evalTxValidator struct {
txcache verify.VerifiedTransactionCache
block bookkeeping.Block
verificationPool execpool.BacklogPool
ctx context.Context
txgroups [][]transactions.SignedTxnWithAD
done chan error
}
func (validator *evalTxValidator) run() {
defer close(validator.done)
specialAddresses := transactions.SpecialAddresses{
FeeSink: validator.block.BlockHeader.FeeSink,
RewardsPool: validator.block.BlockHeader.RewardsPool,
}
var unverifiedTxnGroups [][]transactions.SignedTxn
unverifiedTxnGroups = make([][]transactions.SignedTxn, 0, len(validator.txgroups))
for _, group := range validator.txgroups {
signedTxnGroup := make([]transactions.SignedTxn, len(group))
for j, txn := range group {
signedTxnGroup[j] = txn.SignedTxn
err := txn.SignedTxn.Txn.Alive(validator.block)
if err != nil {
validator.done <- err
return
}
}
unverifiedTxnGroups = append(unverifiedTxnGroups, signedTxnGroup)
}
unverifiedTxnGroups = validator.txcache.GetUnverifiedTranscationGroups(unverifiedTxnGroups, specialAddresses, validator.block.BlockHeader.CurrentProtocol)
err := verify.PaysetGroups(validator.ctx, unverifiedTxnGroups, validator.block.BlockHeader, validator.verificationPool, validator.txcache)
if err != nil {
validator.done <- err
}
}
// used by Ledger.Validate() Ledger.AddBlock() Ledger.trackerEvalVerified()(accountUpdates.loadFromDisk())
//
// Validate: eval(ctx, l, blk, true, txcache, executionPool, true)
// AddBlock: eval(context.Background(), l, blk, false, txcache, nil, true)
// tracker: eval(context.Background(), l, blk, false, txcache, nil, false)
func eval(ctx context.Context, l ledgerForEvaluator, blk bookkeeping.Block, validate bool, txcache verify.VerifiedTransactionCache, executionPool execpool.BacklogPool, usePrefetch bool) (ledgercore.StateDelta, error) {
eval, err := startEvaluator(l, blk.BlockHeader, len(blk.Payset), validate, false)
if err != nil {
return ledgercore.StateDelta{}, err
}
validationCtx, validationCancel := context.WithCancel(ctx)
var wg sync.WaitGroup
defer func() {
validationCancel()
wg.Wait()
}()
// If validationCtx or underlying ctx are Done, end prefetch
if usePrefetch {
wg.Add(1)
go prefetchThread(validationCtx, eval.state.lookupParent, blk.Payset, &wg)
}
// Next, transactions
paysetgroups, err := blk.DecodePaysetGroups()
if err != nil {
return ledgercore.StateDelta{}, err
}
var txvalidator evalTxValidator
if validate {
_, ok := config.Consensus[blk.CurrentProtocol]
if !ok {
return ledgercore.StateDelta{}, protocol.Error(blk.CurrentProtocol)
}
txvalidator.txcache = txcache
txvalidator.block = blk
txvalidator.verificationPool = executionPool
txvalidator.ctx = validationCtx
txvalidator.txgroups = paysetgroups
txvalidator.done = make(chan error, 1)
go txvalidator.run()
}
for _, txgroup := range paysetgroups {
select {
case <-ctx.Done():
return ledgercore.StateDelta{}, ctx.Err()
case err, open := <-txvalidator.done:
// if we're not validating, then `txvalidator.done` would be nil, in which case this case statement would never be executed.
if open && err != nil {
return ledgercore.StateDelta{}, err
}
default:
}
err = eval.TransactionGroup(txgroup)
if err != nil {
return ledgercore.StateDelta{}, err
}
}
// Finally, procees any pending end-of-block state changes
err = eval.endOfBlock()
if err != nil {
return ledgercore.StateDelta{}, err
}
// If validating, do final block checks that depend on our new state
if validate {
// wait for the validation to complete.
select {
case <-ctx.Done():
return ledgercore.StateDelta{}, ctx.Err()
case err, open := <-txvalidator.done:
if !open {
break
}
if err != nil {
return ledgercore.StateDelta{}, err
}
}
err = eval.finalValidation()
if err != nil {
return ledgercore.StateDelta{}, err
}
}
return eval.state.deltas(), nil
}
func prefetchThread(ctx context.Context, state roundCowParent, payset []transactions.SignedTxnInBlock, wg *sync.WaitGroup) {
defer wg.Done()
maybelookup := func(addr basics.Address) {
if addr.IsZero() {
return
}
state.lookup(addr)
}
for _, stxn := range payset {
select {
case <-ctx.Done():
return
default:
}
state.lookup(stxn.Txn.Sender)
maybelookup(stxn.Txn.Receiver)
maybelookup(stxn.Txn.CloseRemainderTo)
maybelookup(stxn.Txn.AssetSender)
maybelookup(stxn.Txn.AssetReceiver)
maybelookup(stxn.Txn.AssetCloseTo)
maybelookup(stxn.Txn.FreezeAccount)
for _, xa := range stxn.Txn.Accounts {
maybelookup(xa)
}
}
}
// Validate uses the ledger to validate block blk as a candidate next block.
// It returns an error if blk is not the expected next block, or if blk is
// not a valid block (e.g., it has duplicate transactions, overspends some
// account, etc).
func (l *Ledger) Validate(ctx context.Context, blk bookkeeping.Block, executionPool execpool.BacklogPool) (*ValidatedBlock, error) {
delta, err := eval(ctx, l, blk, true, l.verifiedTxnCache, executionPool, true)
if err != nil {
return nil, err
}
vb := ValidatedBlock{
blk: blk,
delta: delta,
}
return &vb, nil
}
// ValidatedBlock represents the result of a block validation. It can
// be used to efficiently add the block to the ledger, without repeating
// the work of applying the block's changes to the ledger state.
type ValidatedBlock struct {
blk bookkeeping.Block
delta ledgercore.StateDelta
}
// Block returns the underlying Block for a ValidatedBlock.
func (vb ValidatedBlock) Block() bookkeeping.Block {
return vb.blk
}
// WithSeed returns a copy of the ValidatedBlock with a modified seed.
func (vb ValidatedBlock) WithSeed(s committee.Seed) ValidatedBlock {
newblock := vb.blk
newblock.BlockHeader.Seed = s
return ValidatedBlock{
blk: newblock,
delta: vb.delta,
}
}
| 1 | 41,662 | extra brownie points ( overall solution ): we've currently triple-encoding the payset - 1. we encode it to calculate the block size. 2. we encode it to calculate the commit hash ( either via flat, or as Merkle tree ). 3. we encode it as a whole for the purpose of preparing the proposal ( I know that this isn't always the case, but this case happens to be on the critical path ). Caching the encoded data of the *first* block could help us repeating the process. | algorand-go-algorand | go |
@@ -849,8 +849,11 @@ describe Mongoid::Association::Depending do
it 'adds an error to the parent object' do
expect(person.delete).to be(false)
- expect(person.errors[:restrictable_posts].first).to be(
- Mongoid::Association::Depending::RESTRICT_ERROR_MSG)
+
+ key_message = "#{Mongoid::Errors::MongoidError::BASE_KEY}.restrict_with_error_dependent_destroy"
+ expect(person.errors[:base].first).to eq(
+ ::I18n.translate(key_message, association: :restrictable_posts)
+ )
end
end
| 1 | # frozen_string_literal: true
# encoding: utf-8
require "spec_helper"
describe Mongoid::Association::Depending do
describe '#self.included' do
context 'when a destroy dependent is defined' do
context 'when the model is a subclass' do
context 'when transitive dependents are defined' do
let(:define_classes) do
class DependentReportCard
include Mongoid::Document
belongs_to :dependent_student
end
class DependentUser
include Mongoid::Document
end
class DependentStudent < DependentUser
belongs_to :dependent_teacher
has_many :dependent_report_cards, dependent: :destroy
end
class DependentDerivedStudent < DependentStudent; end
class DependentTeacher
include Mongoid::Document
has_many :dependent_students, dependent: :destroy
end
class DependentCollegeUser < DependentUser; end
end
it "does not add the dependent to superclass" do
define_classes
expect(DependentUser.dependents).to be_empty
u = DependentUser.create!
expect(u.dependents).to be_empty
end
it 'does not impede destroying the superclass' do
define_classes
u = DependentUser.create!
expect { u.destroy! }.not_to raise_error
end
it 'adds the dependent' do
define_classes
expect(DependentStudent.dependents.length).to be(1)
expect(DependentStudent.dependents.first.name).to be(:dependent_report_cards)
s = DependentStudent.create!
expect(s.dependents.length).to be(1)
expect(s.dependents.first.name).to be(:dependent_report_cards)
end
it 'facilitates proper destroying of the object' do
define_classes
s = DependentStudent.create!
r = DependentReportCard.create!(dependent_student: s)
s.destroy!
expect { DependentReportCard.find(r.id) }.to raise_error(Mongoid::Errors::DocumentNotFound)
end
it 'facilitates proper transitive destroying of the object' do
define_classes
t = DependentTeacher.create!
s = DependentStudent.create!(dependent_teacher: t)
r = DependentReportCard.create!(dependent_student: s)
s.destroy!
expect { DependentReportCard.find(r.id) }.to raise_error(Mongoid::Errors::DocumentNotFound)
end
it 'adds the dependent to subclasses' do
define_classes
expect(DependentDerivedStudent.dependents.length).to be(1)
expect(DependentDerivedStudent.dependents.first.name).to be(:dependent_report_cards)
s = DependentDerivedStudent.create!
expect(s.dependents.length).to be(1)
expect(s.dependents.first.name).to be(:dependent_report_cards)
end
it 'facilitates proper destroying of the object from subclasses' do
define_classes
s = DependentDerivedStudent.create!
r = DependentReportCard.create!(dependent_student: s)
s.destroy!
expect { DependentReportCard.find(r.id) }.to raise_error(Mongoid::Errors::DocumentNotFound)
end
it "doesn't add the dependent to sibling classes" do
define_classes
expect(DependentCollegeUser.dependents).to be_empty
c = DependentCollegeUser.create!
expect(c.dependents).to be_empty
end
it 'does not impede destroying the sibling class' do
define_classes
c = DependentCollegeUser.create!
expect { c.destroy! }.not_to raise_error
end
end
context 'when a superclass is reopened and a new dependent is added' do
let(:define_classes) do
class DependentOwnedOne
include Mongoid::Document
belongs_to :dependent_superclass
end
class DependentOwnedTwo
include Mongoid::Document
belongs_to :dependent_superclass
end
class DependentSuperclass
include Mongoid::Document
has_one :dependent_owned_one
has_one :dependent_owned_two
end
class DependentSubclass < DependentSuperclass
has_one :dependent_owned_two, dependent: :nullify
end
class DependentSuperclass
has_one :dependent_owned_one, dependent: :destroy
end
end
it 'defines the dependent from the reopened superclass on the subclass' do
define_classes
DependentSubclass.create!.destroy!
expect(DependentSubclass.dependents.length).to be(1)
expect(DependentSubclass.dependents.last.name).to be(:dependent_owned_two)
expect(DependentSubclass.dependents.last.options[:dependent]).to be(:nullify)
subclass = DependentSubclass.create!
expect(subclass.dependents.last.name).to be(:dependent_owned_two)
expect(subclass.dependents.last.options[:dependent]).to be(:nullify)
end
it 'causes the destruction of the inherited destroy dependent' do
define_classes
subclass = DependentSubclass.create!
owned = DependentOwnedOne.create!(dependent_superclass: subclass)
subclass.destroy!
expect {
DependentOwnedOne.find(owned.id)
}.to raise_error(Mongoid::Errors::DocumentNotFound)
end
end
context 'when a separate subclass overrides the destroy dependent' do
let(:define_classes) do
class Dep
include Mongoid::Document
belongs_to :double_assoc
end
class DoubleAssoc
include Mongoid::Document
has_many :deps, dependent: :destroy
end
class DoubleAssocOne < DoubleAssoc
has_many :deps, dependent: :nullify, inverse_of: :double_assoc
end
class DoubleAssocTwo < DoubleAssocOne
has_many :deps, dependent: :destroy, inverse_of: :double_assoc
end
class DoubleAssocThree < DoubleAssoc; end
end
it 'adds the non-destroy dependent correctly to the subclass with the override' do
define_classes
expect(DoubleAssocOne.dependents.length).to be(1)
expect(DoubleAssocOne.dependents.first.name).to be(:deps)
expect(DoubleAssocOne.dependents.first.options[:dependent]).to be(:nullify)
one = DoubleAssocOne.create!
expect(one.dependents.length).to be(1)
expect(one.dependents.first.name).to be(:deps)
expect(one.dependents.first.options[:dependent]).to be(:nullify)
end
it 'does not cause the destruction of the non-destroy dependent' do
define_classes
one = DoubleAssocOne.create!
dep = Dep.create!(double_assoc: one)
one.destroy!
expect { Dep.find(dep.id) }.not_to raise_error
expect(dep.double_assoc).to be_nil
end
it 'adds the destroy dependent correctly to the subclass without the override' do
define_classes
expect(DoubleAssocTwo.dependents.length).to be(1)
expect(DoubleAssocTwo.dependents.first.name).to be(:deps)
expect(DoubleAssocTwo.dependents.first.options[:dependent]).to be(:destroy)
two = DoubleAssocTwo.create!
expect(two.dependents.length).to be(1)
expect(two.dependents.first.name).to be(:deps)
expect(two.dependents.first.options[:dependent]).to be(:destroy)
end
it 'causes the destruction of the destroy dependent' do
define_classes
two = DoubleAssocTwo.create!
dep = Dep.create!(double_assoc: two)
two.destroy!
expect { Dep.find(dep.id) }.to raise_error(Mongoid::Errors::DocumentNotFound)
end
end
end
end
end
around(:each) do |example|
relations_before = Person.relations
example.run
Person.relations = relations_before
end
describe "#apply_delete_dependencies!" do
let(:band) do
Band.new
end
context "when the association exists in the list of dependencies" do
context "when the association has no dependent strategy" do
before do
band.dependents.push(Band.relations["records"])
end
after do
band.dependents.delete(Band.relations["records"])
end
it "ignores the dependency" do
expect(band.apply_delete_dependencies!).to eq([Band.relations["records"]])
end
end
end
end
describe ".define_dependency!" do
let(:klass) do
Class.new.tap { |c| c.send(:include, Mongoid::Document) }
end
context "when the association metadata doesnt exist" do
before do
klass.dependents.push("nothing")
end
it "does not raise an error" do
expect {
klass.new.apply_delete_dependencies!
}.not_to raise_error
end
end
context "when a dependent option is provided" do
let!(:association) do
klass.has_many :posts, dependent: :destroy
end
after do
klass.relations.delete(association.name.to_s)
end
it "adds the relation to the dependents" do
expect(klass.dependents).to include(klass.relations["posts"])
end
end
context "when no dependent option is provided" do
let!(:association) do
klass.has_many :posts
end
after do
klass.relations.delete(association.name.to_s)
end
it "does not add a relation to the dependents" do
expect(klass.dependents).to_not include(association)
end
end
context 'when the class is defined more than once' do
let!(:association) do
klass.has_many :posts, dependent: :destroy
klass.has_many :posts, dependent: :destroy
end
it 'only creates the dependency once' do
expect(klass.dependents.size).to eq(1)
end
end
end
[:delete, :destroy].each do |method|
describe "##{method}" do
context "when cascading removals" do
context "when strategy is delete" do
let(:person) do
Person.create
end
let!(:post) do
person.posts.create(title: "Testing")
end
before do
person.send(method)
end
it "deletes the associated documents" do
expect {
Post.find(post.id)
}.to raise_error(Mongoid::Errors::DocumentNotFound)
end
end
context "when strategy is destroy" do
let(:person) do
Person.create
end
let!(:game) do
person.create_game(name: "Pong")
end
before do
person.send(method)
end
it "destroys the associated documents" do
expect {
Game.find(game.id)
}.to raise_error(Mongoid::Errors::DocumentNotFound)
end
end
context "when strategy is nullify" do
context "when nullifying a references many" do
let(:movie) do
Movie.create(title: "Bladerunner")
end
let!(:rating) do
movie.ratings.create(value: 10)
end
let(:from_db) do
Rating.find(rating.id)
end
before do
movie.send(method)
end
it "removes the references to the removed document" do
expect(from_db.ratable_id).to be_nil
end
end
context "when nullifying a references one" do
context "when the relation exists" do
let(:book) do
Book.create(title: "Neuromancer")
end
let!(:rating) do
book.create_rating(value: 10)
end
let(:from_db) do
Rating.find(rating.id)
end
before do
book.send(method)
end
it "removes the references to the removed document" do
expect(from_db.ratable_id).to be_nil
end
end
context "when the relation is nil" do
let(:book) do
Book.create(title: "Neuromancer")
end
it "returns nil" do
expect(book.send(method)).to be true
end
end
end
context "when nullifying a many to many" do
let(:person) do
Person.create
end
let!(:preference) do
person.preferences.create(name: "Setting")
end
let(:from_db) do
Preference.find(preference.id)
end
before do
person.send(method)
end
it "removes the references from the removed document" do
expect(person.preference_ids).to_not include(preference.id)
end
it "removes the references to the removed document" do
expect(from_db.person_ids).to_not include(person.id)
end
end
end
context "when dependent is restrict_with_error" do
context "when restricting a references many" do
let!(:association) do
Person.has_many :drugs, dependent: :restrict_with_exception
end
after do
Person.dependents.delete(association)
Person.has_many :drugs, validate: false
end
context "when the relation is empty" do
let(:person) do
Person.new drugs: []
end
it "raises no error" do
expect { person.send(method) }.to_not raise_error
end
it "deletes the parent" do
person.send(method)
expect(person).to be_destroyed
end
end
context "when the relation is not empty" do
let(:person) do
Person.new drugs: [Drug.new]
end
it "raises DeleteRestriction error" do
expect { person.send(method) }.to raise_error(Mongoid::Errors::DeleteRestriction)
end
end
end
context "when restricting a references one" do
let!(:association) do
Person.has_one :account, dependent: :restrict_with_exception
end
after do
Person.dependents.delete(association)
Person.has_one :account, validate: false
end
context "when the relation is empty" do
let(:person) do
Person.new account: nil
end
it "raises no error" do
expect { person.send(method) }.to_not raise_error
end
it "deletes the parent" do
person.send(method)
expect(person).to be_destroyed
end
end
context "when the relation is not empty" do
let(:person) do
Person.new account: Account.new(name: 'test')
end
it "raises DeleteRestriction error" do
expect { person.send(method) }.to raise_error(Mongoid::Errors::DeleteRestriction)
end
end
end
context "when restricting a many to many" do
let!(:association) do
Person.has_and_belongs_to_many :houses, dependent: :restrict_with_exception
end
after do
Person.dependents.delete(association)
Person.has_and_belongs_to_many :houses, validate: false
end
context "when the relation is empty" do
let(:person) do
Person.new houses: []
end
it "raises no error" do
expect { person.send(method) }.to_not raise_error
end
it "deletes the parent" do
person.send(method)
expect(person).to be_destroyed
end
end
context "when the relation is not empty" do
let(:person) do
Person.new houses: [House.new]
end
it "raises DeleteRestriction error" do
expect { person.send(method) }.to raise_error(Mongoid::Errors::DeleteRestriction)
end
end
end
end
end
end
end
context 'when the strategy is :delete_all' do
let(:person) do
Person.create
end
context "when cascading a has one" do
context "when the relation exists" do
let!(:home) do
person.create_home
end
before do
person.delete
end
it "deletes the relation" do
expect(home).to be_destroyed
end
it "persists the deletion" do
expect {
home.reload
}.to raise_error(Mongoid::Errors::DocumentNotFound)
end
end
context "when the relation does not exist" do
before do
person.delete
end
it "deletes the base document" do
expect(person).to be_destroyed
end
end
end
context "when cascading a has many" do
context "when the relation has documents" do
let!(:post_one) do
person.posts.create(title: "one")
end
let!(:post_two) do
person.posts.create(title: "two")
end
context "when the documents are in memory" do
before do
expect(post_one).to receive(:delete).never
expect(post_two).to receive(:delete).never
person.delete
end
it "deletes the first document" do
expect(post_one).to be_destroyed
end
it "deletes the second document" do
expect(post_two).to be_destroyed
end
it "unbinds the first document" do
expect(post_one.person).to be_nil
end
it "unbinds the second document" do
expect(post_two.person).to be_nil
end
it "removes the documents from the relation" do
expect(person.posts).to be_empty
end
it "persists the first deletion" do
expect {
post_one.reload
}.to raise_error(Mongoid::Errors::DocumentNotFound)
end
it "persists the second deletion" do
expect {
post_two.reload
}.to raise_error(Mongoid::Errors::DocumentNotFound)
end
end
end
end
end
context 'when the strategy is :destroy' do
let!(:association) do
Person.has_many :destroyable_posts, class_name: "Post", dependent: :destroy
end
after do
Person.dependents.delete(association)
end
let(:person) do
Person.new
end
let(:post) do
Post.new
end
context "when the documents exist" do
before do
expect(post).to receive(:destroy)
person.destroyable_posts << post
end
it "destroys all documents in the relation" do
person.delete
end
end
context "when no documents exist" do
before do
expect(post).to receive(:destroy).never
end
it "it does not destroy the relation" do
person.delete
end
end
end
context 'when the strategy is :nullify' do
let!(:association) do
Person.has_many :nullifyable_posts, class_name: "Post", dependent: :nullify
end
after do
Person.dependents.delete(association)
end
let(:person) do
Person.new
end
let(:posts_relation) do
person.posts
end
before do
allow(person).to receive(:nullifyable_posts).and_return(posts_relation)
expect(posts_relation).to receive(:nullify)
end
it "nullifies the relation" do
person.delete
end
end
context 'when the strategy is :restrict_with_exception' do
let(:person) do
Person.new
end
let(:post) do
Post.new
end
let!(:association) do
Person.has_many :restrictable_posts, class_name: "Post", dependent: :restrict_with_exception
end
after do
Person.dependents.delete(association)
end
context 'when there are related objects' do
before do
person.restrictable_posts << post
expect(post).to receive(:delete).never
expect(post).to receive(:destroy).never
end
it 'raises an exception and leaves the related one intact' do
expect { person.delete }.to raise_exception(Mongoid::Errors::DeleteRestriction)
end
end
context 'when there are no related objects' do
before do
expect(post).to receive(:delete).never
expect(post).to receive(:destroy).never
end
it 'deletes the object and leaves the other one intact' do
expect(person.delete).to be(true)
end
end
end
context 'when the strategy is :restrict_with_error' do
let(:person) do
Person.new
end
let(:post) do
Post.new
end
let!(:association) do
Person.has_many :restrictable_posts, class_name: "Post", dependent: :restrict_with_error
end
after do
Person.dependents.delete(association)
end
context 'when there are related objects' do
before do
person.restrictable_posts << post
end
it 'adds an error to the parent object' do
expect(person.delete).to be(false)
expect(person.errors[:restrictable_posts].first).to be(
Mongoid::Association::Depending::RESTRICT_ERROR_MSG)
end
end
context 'when there are no related objects' do
before do
expect(post).to receive(:delete).never
expect(post).to receive(:destroy).never
end
it 'deletes the object and leaves the other one intact' do
expect(person.delete).to be(true)
end
end
end
end
| 1 | 12,424 | This assertion should use the actual expanded string, so that it is clear what the message produced looks like. Right now one has to run the code to determine what the message is. | mongodb-mongoid | rb |
@@ -18,6 +18,7 @@ package ec2
import (
"fmt"
+
"sigs.k8s.io/cluster-api/util/conditions"
errlist "k8s.io/apimachinery/pkg/util/errors" | 1 | /*
Copyright 2018 The Kubernetes 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.
*/
package ec2
import (
"fmt"
"sigs.k8s.io/cluster-api/util/conditions"
errlist "k8s.io/apimachinery/pkg/util/errors"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/converters"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/filter"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services/wait"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/tags"
"sigs.k8s.io/cluster-api-provider-aws/pkg/record"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/pkg/errors"
infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha3"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/awserrors"
)
const (
// IPProtocolTCP is how EC2 represents the TCP protocol in ingress rules
IPProtocolTCP = "tcp"
// IPProtocolUDP is how EC2 represents the UDP protocol in ingress rules
IPProtocolUDP = "udp"
// IPProtocolICMP is how EC2 represents the ICMP protocol in ingress rules
IPProtocolICMP = "icmp"
// IPProtocolICMPv6 is how EC2 represents the ICMPv6 protocol in ingress rules
IPProtocolICMPv6 = "58"
)
func (s *Service) reconcileSecurityGroups() error {
s.scope.V(2).Info("Reconciling security groups")
if s.scope.Network().SecurityGroups == nil {
s.scope.Network().SecurityGroups = make(map[infrav1.SecurityGroupRole]infrav1.SecurityGroup)
}
sgs, err := s.describeSecurityGroupsByName()
if err != nil {
return err
}
// Declare all security group roles that the reconcile loop takes care of.
roles := []infrav1.SecurityGroupRole{
infrav1.SecurityGroupBastion,
infrav1.SecurityGroupAPIServerLB,
infrav1.SecurityGroupLB,
infrav1.SecurityGroupControlPlane,
infrav1.SecurityGroupNode,
}
// First iteration makes sure that the security group are valid and fully created.
for i := range roles {
role := roles[i]
sg := s.getDefaultSecurityGroup(role)
existing, ok := sgs[*sg.GroupName]
if !ok {
if err := s.createSecurityGroup(role, sg); err != nil {
return err
}
s.scope.SecurityGroups()[role] = infrav1.SecurityGroup{
ID: *sg.GroupId,
Name: *sg.GroupName,
}
s.scope.V(2).Info("Created security group for role", "role", role, "security-group", s.scope.SecurityGroups()[role])
continue
}
// TODO(vincepri): validate / update security group if necessary.
s.scope.SecurityGroups()[role] = existing
// Make sure tags are up to date.
if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) {
if err := tags.Ensure(existing.Tags, &tags.ApplyParams{
EC2Client: s.scope.EC2,
BuildParams: s.getSecurityGroupTagParams(existing.Name, existing.ID, role),
}); err != nil {
return false, err
}
return true, nil
}, awserrors.GroupNotFound); err != nil {
return errors.Wrapf(err, "failed to ensure tags on security group %q", existing.ID)
}
}
// Second iteration creates or updates all permissions on the security group to match
// the specified ingress rules.
for i := range s.scope.SecurityGroups() {
sg := s.scope.SecurityGroups()[i]
if sg.Tags.HasAWSCloudProviderOwned(s.scope.Name()) {
// skip rule reconciliation, as we expect the in-cluster cloud integration to manage them
continue
}
current := sg.IngressRules
want, err := s.getSecurityGroupIngressRules(i)
if err != nil {
return err
}
toRevoke := current.Difference(want)
if len(toRevoke) > 0 {
if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) {
if err := s.revokeSecurityGroupIngressRules(sg.ID, toRevoke); err != nil {
return false, err
}
return true, nil
}, awserrors.GroupNotFound); err != nil {
return errors.Wrapf(err, "failed to revoke security group ingress rules for %q", sg.ID)
}
s.scope.V(2).Info("Revoked ingress rules from security group", "revoked-ingress-rules", toRevoke, "security-group-id", sg.ID)
}
toAuthorize := want.Difference(current)
if len(toAuthorize) > 0 {
if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) {
if err := s.authorizeSecurityGroupIngressRules(sg.ID, toAuthorize); err != nil {
return false, err
}
return true, nil
}, awserrors.GroupNotFound); err != nil {
return err
}
s.scope.V(2).Info("Authorized ingress rules in security group", "authorized-ingress-rules", toAuthorize, "security-group-id", sg.ID)
}
}
conditions.MarkTrue(s.scope.AWSCluster, infrav1.ClusterSecurityGroupsReadyCondition)
return nil
}
func (s *Service) deleteSecurityGroups() error {
for _, sg := range s.scope.SecurityGroups() {
current := sg.IngressRules
if err := s.revokeAllSecurityGroupIngressRules(sg.ID); awserrors.IsIgnorableSecurityGroupError(err) != nil {
return err
}
s.scope.V(2).Info("Revoked ingress rules from security group", "revoked-ingress-rules", current, "security-group-id", sg.ID)
}
for i := range s.scope.SecurityGroups() {
sg := s.scope.SecurityGroups()[i]
if err := s.deleteSecurityGroup(&sg, "managed"); err != nil {
return err
}
}
clusterGroups, err := s.describeClusterOwnedSecurityGroups()
if err != nil {
return err
}
errs := []error{}
for i := range clusterGroups {
sg := clusterGroups[i]
if err := s.deleteSecurityGroup(&sg, "cluster managed"); err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errlist.NewAggregate(errs)
}
return nil
}
func (s *Service) deleteSecurityGroup(sg *infrav1.SecurityGroup, typ string) error {
input := &ec2.DeleteSecurityGroupInput{
GroupId: aws.String(sg.ID),
}
if _, err := s.scope.EC2.DeleteSecurityGroup(input); awserrors.IsIgnorableSecurityGroupError(err) != nil {
record.Warnf(s.scope.AWSCluster, "FailedDeleteSecurityGroup", "Failed to delete %s SecurityGroup %q: %v", typ, sg.ID, err)
return errors.Wrapf(err, "failed to delete security group %q", sg.ID)
}
record.Eventf(s.scope.AWSCluster, "SuccessfulDeleteSecurityGroup", "Deleted %s SecurityGroup %q", typ, sg.ID)
s.scope.V(2).Info("Deleted security group", "security-group-id", sg.ID, "kind", typ)
return nil
}
func (s *Service) describeClusterOwnedSecurityGroups() ([]infrav1.SecurityGroup, error) {
input := &ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{
filter.EC2.VPC(s.scope.VPC().ID),
filter.EC2.ProviderOwned(s.scope.Name()),
},
}
groups := []infrav1.SecurityGroup{}
err := s.scope.EC2.DescribeSecurityGroupsPages(input, func(out *ec2.DescribeSecurityGroupsOutput, last bool) bool {
for _, group := range out.SecurityGroups {
if group != nil {
groups = append(groups, makeInfraSecurityGroup(group))
}
}
return true
})
if err != nil {
return nil, errors.Wrapf(err, "failed to describe cluster-owned security groups in vpc %q", s.scope.VPC().ID)
}
return groups, nil
}
func (s *Service) describeSecurityGroupsByName() (map[string]infrav1.SecurityGroup, error) {
input := &ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{
filter.EC2.VPC(s.scope.VPC().ID),
filter.EC2.Cluster(s.scope.Name()),
},
}
out, err := s.scope.EC2.DescribeSecurityGroups(input)
if err != nil {
return nil, errors.Wrapf(err, "failed to describe security groups in vpc %q", s.scope.VPC().ID)
}
res := make(map[string]infrav1.SecurityGroup, len(out.SecurityGroups))
for _, ec2sg := range out.SecurityGroups {
sg := makeInfraSecurityGroup(ec2sg)
for _, ec2rule := range ec2sg.IpPermissions {
sg.IngressRules = append(sg.IngressRules, ingressRuleFromSDKType(ec2rule))
}
res[sg.Name] = sg
}
return res, nil
}
func makeInfraSecurityGroup(ec2sg *ec2.SecurityGroup) infrav1.SecurityGroup {
return infrav1.SecurityGroup{
ID: *ec2sg.GroupId,
Name: *ec2sg.GroupName,
Tags: converters.TagsToMap(ec2sg.Tags),
}
}
func (s *Service) createSecurityGroup(role infrav1.SecurityGroupRole, input *ec2.SecurityGroup) error {
sgTags := s.getSecurityGroupTagParams(aws.StringValue(input.GroupName), temporaryResourceID, role)
out, err := s.scope.EC2.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{
VpcId: input.VpcId,
GroupName: input.GroupName,
Description: aws.String(fmt.Sprintf("Kubernetes cluster %s: %s", s.scope.Name(), role)),
TagSpecifications: []*ec2.TagSpecification{
tags.BuildParamsToTagSpecification(ec2.ResourceTypeSecurityGroup, sgTags),
},
})
if err != nil {
record.Warnf(s.scope.AWSCluster, "FailedCreateSecurityGroup", "Failed to create managed SecurityGroup for Role %q: %v", role, err)
return errors.Wrapf(err, "failed to create security group %q in vpc %q", role, aws.StringValue(input.VpcId))
}
record.Eventf(s.scope.AWSCluster, "SuccessfulCreateSecurityGroup", "Created managed SecurityGroup %q for Role %q", aws.StringValue(out.GroupId), role)
// Set the group id.
input.GroupId = out.GroupId
return nil
}
func (s *Service) authorizeSecurityGroupIngressRules(id string, rules infrav1.IngressRules) error {
input := &ec2.AuthorizeSecurityGroupIngressInput{GroupId: aws.String(id)}
for _, rule := range rules {
input.IpPermissions = append(input.IpPermissions, ingressRuleToSDKType(rule))
}
if _, err := s.scope.EC2.AuthorizeSecurityGroupIngress(input); err != nil {
record.Warnf(s.scope.AWSCluster, "FailedAuthorizeSecurityGroupIngressRules", "Failed to authorize security group ingress rules %v for SecurityGroup %q: %v", rules, id, err)
return errors.Wrapf(err, "failed to authorize security group %q ingress rules: %v", id, rules)
}
record.Eventf(s.scope.AWSCluster, "SuccessfulAuthorizeSecurityGroupIngressRules", "Authorized security group ingress rules %v for SecurityGroup %q", rules, id)
return nil
}
func (s *Service) revokeSecurityGroupIngressRules(id string, rules infrav1.IngressRules) error {
input := &ec2.RevokeSecurityGroupIngressInput{GroupId: aws.String(id)}
for _, rule := range rules {
input.IpPermissions = append(input.IpPermissions, ingressRuleToSDKType(rule))
}
if _, err := s.scope.EC2.RevokeSecurityGroupIngress(input); err != nil {
record.Warnf(s.scope.AWSCluster, "FailedRevokeSecurityGroupIngressRules", "Failed to revoke security group ingress rules %v for SecurityGroup %q: %v", rules, id, err)
return errors.Wrapf(err, "failed to revoke security group %q ingress rules: %v", id, rules)
}
record.Eventf(s.scope.AWSCluster, "SuccessfulRevokeSecurityGroupIngressRules", "Revoked security group ingress rules %v for SecurityGroup %q", rules, id)
return nil
}
func (s *Service) revokeAllSecurityGroupIngressRules(id string) error {
describeInput := &ec2.DescribeSecurityGroupsInput{GroupIds: []*string{aws.String(id)}}
securityGroups, err := s.scope.EC2.DescribeSecurityGroups(describeInput)
if err != nil {
return errors.Wrapf(err, "failed to query security group %q", id)
}
for _, sg := range securityGroups.SecurityGroups {
if len(sg.IpPermissions) > 0 {
revokeInput := &ec2.RevokeSecurityGroupIngressInput{
GroupId: aws.String(id),
IpPermissions: sg.IpPermissions,
}
if _, err := s.scope.EC2.RevokeSecurityGroupIngress(revokeInput); err != nil {
record.Warnf(s.scope.AWSCluster, "FailedRevokeSecurityGroupIngressRules", "Failed to revoke all security group ingress rules for SecurityGroup %q: %v", *sg.GroupId, err)
return errors.Wrapf(err, "failed to revoke security group %q ingress rules", id)
}
record.Eventf(s.scope.AWSCluster, "SuccessfulRevokeSecurityGroupIngressRules", "Revoked all security group ingress rules for SecurityGroup %q", *sg.GroupId)
}
}
return nil
}
func (s *Service) defaultSSHIngressRule(sourceSecurityGroupID string) *infrav1.IngressRule {
return &infrav1.IngressRule{
Description: "SSH",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: 22,
ToPort: 22,
SourceSecurityGroupIDs: []string{sourceSecurityGroupID},
}
}
func (s *Service) getSecurityGroupIngressRules(role infrav1.SecurityGroupRole) (infrav1.IngressRules, error) {
// Set source of CNI ingress rules to be control plane and node security groups
cniRules := make(infrav1.IngressRules, len(s.scope.CNIIngressRules()))
for i, r := range s.scope.CNIIngressRules() {
cniRules[i] = &infrav1.IngressRule{
Description: r.Description,
Protocol: r.Protocol,
FromPort: r.FromPort,
ToPort: r.ToPort,
SourceSecurityGroupIDs: []string{
s.scope.SecurityGroups()[infrav1.SecurityGroupControlPlane].ID,
s.scope.SecurityGroups()[infrav1.SecurityGroupNode].ID,
},
}
}
switch role {
case infrav1.SecurityGroupBastion:
return infrav1.IngressRules{
{
Description: "SSH",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: 22,
ToPort: 22,
CidrBlocks: s.scope.AWSCluster.Spec.Bastion.AllowedCIDRBlocks,
},
}, nil
case infrav1.SecurityGroupControlPlane:
rules := infrav1.IngressRules{
s.defaultSSHIngressRule(s.scope.SecurityGroups()[infrav1.SecurityGroupBastion].ID),
{
Description: "Kubernetes API",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: 6443,
ToPort: 6443,
SourceSecurityGroupIDs: []string{
s.scope.SecurityGroups()[infrav1.SecurityGroupAPIServerLB].ID,
s.scope.SecurityGroups()[infrav1.SecurityGroupControlPlane].ID,
s.scope.SecurityGroups()[infrav1.SecurityGroupNode].ID,
},
},
{
Description: "etcd",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: 2379,
ToPort: 2379,
SourceSecurityGroupIDs: []string{s.scope.SecurityGroups()[infrav1.SecurityGroupControlPlane].ID},
},
{
Description: "etcd peer",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: 2380,
ToPort: 2380,
SourceSecurityGroupIDs: []string{s.scope.SecurityGroups()[infrav1.SecurityGroupControlPlane].ID},
},
}
return append(cniRules, rules...), nil
case infrav1.SecurityGroupNode:
rules := infrav1.IngressRules{
s.defaultSSHIngressRule(s.scope.SecurityGroups()[infrav1.SecurityGroupBastion].ID),
{
Description: "Node Port Services",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: 30000,
ToPort: 32767,
CidrBlocks: []string{anyIPv4CidrBlock},
},
{
Description: "Kubelet API",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: 10250,
ToPort: 10250,
SourceSecurityGroupIDs: []string{
s.scope.SecurityGroups()[infrav1.SecurityGroupControlPlane].ID,
// This is needed to support metrics-server deployments
s.scope.SecurityGroups()[infrav1.SecurityGroupNode].ID,
},
},
}
return append(cniRules, rules...), nil
case infrav1.SecurityGroupAPIServerLB:
return infrav1.IngressRules{
{
Description: "Kubernetes API",
Protocol: infrav1.SecurityGroupProtocolTCP,
FromPort: int64(s.scope.APIServerPort()),
ToPort: int64(s.scope.APIServerPort()),
CidrBlocks: []string{anyIPv4CidrBlock},
},
}, nil
case infrav1.SecurityGroupLB:
// We hand this group off to the in-cluster cloud provider, so these rules aren't used
return infrav1.IngressRules{}, nil
}
return nil, errors.Errorf("Cannot determine ingress rules for unknown security group role %q", role)
}
func (s *Service) getSecurityGroupName(clusterName string, role infrav1.SecurityGroupRole) string {
return fmt.Sprintf("%s-%v", clusterName, role)
}
func (s *Service) getDefaultSecurityGroup(role infrav1.SecurityGroupRole) *ec2.SecurityGroup {
name := s.getSecurityGroupName(s.scope.Name(), role)
return &ec2.SecurityGroup{
GroupName: aws.String(name),
VpcId: aws.String(s.scope.VPC().ID),
Tags: converters.MapToTags(infrav1.Build(s.getSecurityGroupTagParams(name, "", role))),
}
}
func (s *Service) getSecurityGroupTagParams(name string, id string, role infrav1.SecurityGroupRole) infrav1.BuildParams {
additional := s.scope.AdditionalTags()
if role == infrav1.SecurityGroupLB {
additional[infrav1.ClusterAWSCloudProviderTagKey(s.scope.Name())] = string(infrav1.ResourceLifecycleOwned)
}
return infrav1.BuildParams{
ClusterName: s.scope.Name(),
Lifecycle: infrav1.ResourceLifecycleOwned,
Name: aws.String(name),
ResourceID: id,
Role: aws.String(string(role)),
Additional: additional,
}
}
func ingressRuleToSDKType(i *infrav1.IngressRule) (res *ec2.IpPermission) {
// AWS seems to ignore the From/To port when set on protocols where it doesn't apply, but
// we avoid serializing it out for clarity's sake.
// See: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IpPermission.html
switch i.Protocol {
case infrav1.SecurityGroupProtocolTCP,
infrav1.SecurityGroupProtocolUDP,
infrav1.SecurityGroupProtocolICMP,
infrav1.SecurityGroupProtocolICMPv6:
res = &ec2.IpPermission{
IpProtocol: aws.String(string(i.Protocol)),
FromPort: aws.Int64(i.FromPort),
ToPort: aws.Int64(i.ToPort),
}
default:
res = &ec2.IpPermission{
IpProtocol: aws.String(string(i.Protocol)),
}
}
for _, cidr := range i.CidrBlocks {
ipRange := &ec2.IpRange{
CidrIp: aws.String(cidr),
}
if i.Description != "" {
ipRange.Description = aws.String(i.Description)
}
res.IpRanges = append(res.IpRanges, ipRange)
}
for _, groupID := range i.SourceSecurityGroupIDs {
userIDGroupPair := &ec2.UserIdGroupPair{
GroupId: aws.String(groupID),
}
if i.Description != "" {
userIDGroupPair.Description = aws.String(i.Description)
}
res.UserIdGroupPairs = append(res.UserIdGroupPairs, userIDGroupPair)
}
return res
}
func ingressRuleFromSDKType(v *ec2.IpPermission) (res *infrav1.IngressRule) {
// Ports are only well-defined for TCP and UDP protocols, but EC2 overloads the port range
// in the case of ICMP(v6) traffic to indicate which codes are allowed. For all other protocols,
// including the custom "-1" All Traffic protcol, FromPort and ToPort are omitted from the response.
// See: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IpPermission.html
switch *v.IpProtocol {
case IPProtocolTCP,
IPProtocolUDP,
IPProtocolICMP,
IPProtocolICMPv6:
res = &infrav1.IngressRule{
Protocol: infrav1.SecurityGroupProtocol(*v.IpProtocol),
FromPort: *v.FromPort,
ToPort: *v.ToPort,
}
default:
res = &infrav1.IngressRule{
Protocol: infrav1.SecurityGroupProtocol(*v.IpProtocol),
}
}
for _, ec2range := range v.IpRanges {
if ec2range.Description != nil && *ec2range.Description != "" {
res.Description = *ec2range.Description
}
res.CidrBlocks = append(res.CidrBlocks, *ec2range.CidrIp)
}
for _, pair := range v.UserIdGroupPairs {
if pair.GroupId == nil {
continue
}
if pair.Description != nil && *pair.Description != "" {
res.Description = *pair.Description
}
res.SourceSecurityGroupIDs = append(res.SourceSecurityGroupIDs, *pair.GroupId)
}
return res
}
| 1 | 15,502 | similar here for imports, these should be consolidated (and also consolidated with the grouping below) | kubernetes-sigs-cluster-api-provider-aws | go |
@@ -231,7 +231,7 @@ class LoadAnnotations:
self.with_seg = with_seg
self.poly2mask = poly2mask
self.file_client_args = file_client_args.copy()
- self.file_client = None
+ self.file_client = mmcv.FileClient(**self.file_client_args)
def _load_bboxes(self, results):
"""Private function to load bounding box annotations. | 1 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
from mmdet.core import BitmapMasks, PolygonMasks
from ..builder import PIPELINES
try:
from panopticapi.utils import rgb2id
except ImportError:
rgb2id = None
@PIPELINES.register_module()
class LoadImageFromFile:
"""Load an image from file.
Required keys are "img_prefix" and "img_info" (a dict that must contain the
key "filename"). Added or updated keys are "filename", "img", "img_shape",
"ori_shape" (same as `img_shape`), "pad_shape" (same as `img_shape`),
"scale_factor" (1.0) and "img_norm_cfg" (means=0 and stds=1).
Args:
to_float32 (bool): Whether to convert the loaded image to a float32
numpy array. If set to False, the loaded image is an uint8 array.
Defaults to False.
color_type (str): The flag argument for :func:`mmcv.imfrombytes`.
Defaults to 'color'.
file_client_args (dict): Arguments to instantiate a FileClient.
See :class:`mmcv.fileio.FileClient` for details.
Defaults to ``dict(backend='disk')``.
"""
def __init__(self,
to_float32=False,
color_type='color',
file_client_args=dict(backend='disk')):
self.to_float32 = to_float32
self.color_type = color_type
self.file_client_args = file_client_args.copy()
self.file_client = None
def __call__(self, results):
"""Call functions to load image and get image meta information.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded image and meta information.
"""
if self.file_client is None:
self.file_client = mmcv.FileClient(**self.file_client_args)
if results['img_prefix'] is not None:
filename = osp.join(results['img_prefix'],
results['img_info']['filename'])
else:
filename = results['img_info']['filename']
img_bytes = self.file_client.get(filename)
img = mmcv.imfrombytes(img_bytes, flag=self.color_type)
if self.to_float32:
img = img.astype(np.float32)
results['filename'] = filename
results['ori_filename'] = results['img_info']['filename']
results['img'] = img
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
results['img_fields'] = ['img']
return results
def __repr__(self):
repr_str = (f'{self.__class__.__name__}('
f'to_float32={self.to_float32}, '
f"color_type='{self.color_type}', "
f'file_client_args={self.file_client_args})')
return repr_str
@PIPELINES.register_module()
class LoadImageFromWebcam(LoadImageFromFile):
"""Load an image from webcam.
Similar with :obj:`LoadImageFromFile`, but the image read from webcam is in
``results['img']``.
"""
def __call__(self, results):
"""Call functions to add image meta information.
Args:
results (dict): Result dict with Webcam read image in
``results['img']``.
Returns:
dict: The dict contains loaded image and meta information.
"""
img = results['img']
if self.to_float32:
img = img.astype(np.float32)
results['filename'] = None
results['ori_filename'] = None
results['img'] = img
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
results['img_fields'] = ['img']
return results
@PIPELINES.register_module()
class LoadMultiChannelImageFromFiles:
"""Load multi-channel images from a list of separate channel files.
Required keys are "img_prefix" and "img_info" (a dict that must contain the
key "filename", which is expected to be a list of filenames).
Added or updated keys are "filename", "img", "img_shape",
"ori_shape" (same as `img_shape`), "pad_shape" (same as `img_shape`),
"scale_factor" (1.0) and "img_norm_cfg" (means=0 and stds=1).
Args:
to_float32 (bool): Whether to convert the loaded image to a float32
numpy array. If set to False, the loaded image is an uint8 array.
Defaults to False.
color_type (str): The flag argument for :func:`mmcv.imfrombytes`.
Defaults to 'color'.
file_client_args (dict): Arguments to instantiate a FileClient.
See :class:`mmcv.fileio.FileClient` for details.
Defaults to ``dict(backend='disk')``.
"""
def __init__(self,
to_float32=False,
color_type='unchanged',
file_client_args=dict(backend='disk')):
self.to_float32 = to_float32
self.color_type = color_type
self.file_client_args = file_client_args.copy()
self.file_client = None
def __call__(self, results):
"""Call functions to load multiple images and get images meta
information.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded images and meta information.
"""
if self.file_client is None:
self.file_client = mmcv.FileClient(**self.file_client_args)
if results['img_prefix'] is not None:
filename = [
osp.join(results['img_prefix'], fname)
for fname in results['img_info']['filename']
]
else:
filename = results['img_info']['filename']
img = []
for name in filename:
img_bytes = self.file_client.get(name)
img.append(mmcv.imfrombytes(img_bytes, flag=self.color_type))
img = np.stack(img, axis=-1)
if self.to_float32:
img = img.astype(np.float32)
results['filename'] = filename
results['ori_filename'] = results['img_info']['filename']
results['img'] = img
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
# Set initial values for default meta_keys
results['pad_shape'] = img.shape
results['scale_factor'] = 1.0
num_channels = 1 if len(img.shape) < 3 else img.shape[2]
results['img_norm_cfg'] = dict(
mean=np.zeros(num_channels, dtype=np.float32),
std=np.ones(num_channels, dtype=np.float32),
to_rgb=False)
return results
def __repr__(self):
repr_str = (f'{self.__class__.__name__}('
f'to_float32={self.to_float32}, '
f"color_type='{self.color_type}', "
f'file_client_args={self.file_client_args})')
return repr_str
@PIPELINES.register_module()
class LoadAnnotations:
"""Load multiple types of annotations.
Args:
with_bbox (bool): Whether to parse and load the bbox annotation.
Default: True.
with_label (bool): Whether to parse and load the label annotation.
Default: True.
with_mask (bool): Whether to parse and load the mask annotation.
Default: False.
with_seg (bool): Whether to parse and load the semantic segmentation
annotation. Default: False.
poly2mask (bool): Whether to convert the instance masks from polygons
to bitmaps. Default: True.
file_client_args (dict): Arguments to instantiate a FileClient.
See :class:`mmcv.fileio.FileClient` for details.
Defaults to ``dict(backend='disk')``.
"""
def __init__(self,
with_bbox=True,
with_label=True,
with_mask=False,
with_seg=False,
poly2mask=True,
file_client_args=dict(backend='disk')):
self.with_bbox = with_bbox
self.with_label = with_label
self.with_mask = with_mask
self.with_seg = with_seg
self.poly2mask = poly2mask
self.file_client_args = file_client_args.copy()
self.file_client = None
def _load_bboxes(self, results):
"""Private function to load bounding box annotations.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded bounding box annotations.
"""
ann_info = results['ann_info']
results['gt_bboxes'] = ann_info['bboxes'].copy()
gt_bboxes_ignore = ann_info.get('bboxes_ignore', None)
if gt_bboxes_ignore is not None:
results['gt_bboxes_ignore'] = gt_bboxes_ignore.copy()
results['bbox_fields'].append('gt_bboxes_ignore')
results['bbox_fields'].append('gt_bboxes')
return results
def _load_labels(self, results):
"""Private function to load label annotations.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded label annotations.
"""
results['gt_labels'] = results['ann_info']['labels'].copy()
return results
def _poly2mask(self, mask_ann, img_h, img_w):
"""Private function to convert masks represented with polygon to
bitmaps.
Args:
mask_ann (list | dict): Polygon mask annotation input.
img_h (int): The height of output mask.
img_w (int): The width of output mask.
Returns:
numpy.ndarray: The decode bitmap mask of shape (img_h, img_w).
"""
if isinstance(mask_ann, list):
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = maskUtils.frPyObjects(mask_ann, img_h, img_w)
rle = maskUtils.merge(rles)
elif isinstance(mask_ann['counts'], list):
# uncompressed RLE
rle = maskUtils.frPyObjects(mask_ann, img_h, img_w)
else:
# rle
rle = mask_ann
mask = maskUtils.decode(rle)
return mask
def process_polygons(self, polygons):
"""Convert polygons to list of ndarray and filter invalid polygons.
Args:
polygons (list[list]): Polygons of one instance.
Returns:
list[numpy.ndarray]: Processed polygons.
"""
polygons = [np.array(p) for p in polygons]
valid_polygons = []
for polygon in polygons:
if len(polygon) % 2 == 0 and len(polygon) >= 6:
valid_polygons.append(polygon)
return valid_polygons
def _load_masks(self, results):
"""Private function to load mask annotations.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded mask annotations.
If ``self.poly2mask`` is set ``True``, `gt_mask` will contain
:obj:`PolygonMasks`. Otherwise, :obj:`BitmapMasks` is used.
"""
h, w = results['img_info']['height'], results['img_info']['width']
gt_masks = results['ann_info']['masks']
if self.poly2mask:
gt_masks = BitmapMasks(
[self._poly2mask(mask, h, w) for mask in gt_masks], h, w)
else:
gt_masks = PolygonMasks(
[self.process_polygons(polygons) for polygons in gt_masks], h,
w)
results['gt_masks'] = gt_masks
results['mask_fields'].append('gt_masks')
return results
def _load_semantic_seg(self, results):
"""Private function to load semantic segmentation annotations.
Args:
results (dict): Result dict from :obj:`dataset`.
Returns:
dict: The dict contains loaded semantic segmentation annotations.
"""
if self.file_client is None:
self.file_client = mmcv.FileClient(**self.file_client_args)
filename = osp.join(results['seg_prefix'],
results['ann_info']['seg_map'])
img_bytes = self.file_client.get(filename)
results['gt_semantic_seg'] = mmcv.imfrombytes(
img_bytes, flag='unchanged').squeeze()
results['seg_fields'].append('gt_semantic_seg')
return results
def __call__(self, results):
"""Call function to load multiple types annotations.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded bounding box, label, mask and
semantic segmentation annotations.
"""
if self.with_bbox:
results = self._load_bboxes(results)
if results is None:
return None
if self.with_label:
results = self._load_labels(results)
if self.with_mask:
results = self._load_masks(results)
if self.with_seg:
results = self._load_semantic_seg(results)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(with_bbox={self.with_bbox}, '
repr_str += f'with_label={self.with_label}, '
repr_str += f'with_mask={self.with_mask}, '
repr_str += f'with_seg={self.with_seg}, '
repr_str += f'poly2mask={self.poly2mask}, '
repr_str += f'poly2mask={self.file_client_args})'
return repr_str
@PIPELINES.register_module()
class LoadPanopticAnnotations(LoadAnnotations):
"""Load multiple types of panoptic annotations.
Args:
with_bbox (bool): Whether to parse and load the bbox annotation.
Default: True.
with_label (bool): Whether to parse and load the label annotation.
Default: True.
with_mask (bool): Whether to parse and load the mask annotation.
Default: True.
with_seg (bool): Whether to parse and load the semantic segmentation
annotation. Default: True.
file_client_args (dict): Arguments to instantiate a FileClient.
See :class:`mmcv.fileio.FileClient` for details.
Defaults to ``dict(backend='disk')``.
"""
def __init__(self,
with_bbox=True,
with_label=True,
with_mask=True,
with_seg=True,
file_client_args=dict(backend='disk')):
if rgb2id is None:
raise RuntimeError(
'panopticapi is not installed, please install it by: '
'pip install git+https://github.com/cocodataset/'
'panopticapi.git.')
super(LoadPanopticAnnotations,
self).__init__(with_bbox, with_label, with_mask, with_seg, True,
file_client_args)
def _load_masks_and_semantic_segs(self, results):
"""Private function to load mask and semantic segmentation annotations.
In gt_semantic_seg, the foreground label is from `0` to
`num_things - 1`, the background label is from `num_things` to
`num_things + num_stuff - 1`, 255 means the ignored label (`VOID`).
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded mask and semantic segmentation
annotations. `BitmapMasks` is used for mask annotations.
"""
if self.file_client is None:
self.file_client = mmcv.FileClient(**self.file_client_args)
filename = osp.join(results['seg_prefix'],
results['ann_info']['seg_map'])
img_bytes = self.file_client.get(filename)
pan_png = mmcv.imfrombytes(
img_bytes, flag='color', channel_order='rgb').squeeze()
pan_png = rgb2id(pan_png)
gt_masks = []
gt_seg = np.zeros_like(pan_png) + 255 # 255 as ignore
for mask_info in results['ann_info']['masks']:
mask = (pan_png == mask_info['id'])
gt_seg = np.where(mask, mask_info['category'], gt_seg)
# The legal thing masks
if mask_info.get('is_thing'):
gt_masks.append(mask.astype(np.uint8))
if self.with_mask:
h, w = results['img_info']['height'], results['img_info']['width']
gt_masks = BitmapMasks(gt_masks, h, w)
results['gt_masks'] = gt_masks
results['mask_fields'].append('gt_masks')
if self.with_seg:
results['gt_semantic_seg'] = gt_seg
results['seg_fields'].append('gt_semantic_seg')
return results
def __call__(self, results):
"""Call function to load multiple types panoptic annotations.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded bounding box, label, mask and
semantic segmentation annotations.
"""
if self.with_bbox:
results = self._load_bboxes(results)
if results is None:
return None
if self.with_label:
results = self._load_labels(results)
if self.with_mask or self.with_seg:
# The tasks completed by '_load_masks' and '_load_semantic_segs'
# in LoadAnnotations are merged to one function.
results = self._load_masks_and_semantic_segs(results)
return results
@PIPELINES.register_module()
class LoadProposals:
"""Load proposal pipeline.
Required key is "proposals". Updated keys are "proposals", "bbox_fields".
Args:
num_max_proposals (int, optional): Maximum number of proposals to load.
If not specified, all proposals will be loaded.
"""
def __init__(self, num_max_proposals=None):
self.num_max_proposals = num_max_proposals
def __call__(self, results):
"""Call function to load proposals from file.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded proposal annotations.
"""
proposals = results['proposals']
if proposals.shape[1] not in (4, 5):
raise AssertionError(
'proposals should have shapes (n, 4) or (n, 5), '
f'but found {proposals.shape}')
proposals = proposals[:, :4]
if self.num_max_proposals is not None:
proposals = proposals[:self.num_max_proposals]
if len(proposals) == 0:
proposals = np.array([[0, 0, 0, 0]], dtype=np.float32)
results['proposals'] = proposals
results['bbox_fields'].append('proposals')
return results
def __repr__(self):
return self.__class__.__name__ + \
f'(num_max_proposals={self.num_max_proposals})'
@PIPELINES.register_module()
class FilterAnnotations:
"""Filter invalid annotations.
Args:
min_gt_bbox_wh (tuple[int]): Minimum width and height of ground truth
boxes.
"""
def __init__(self, min_gt_bbox_wh):
# TODO: add more filter options
self.min_gt_bbox_wh = min_gt_bbox_wh
def __call__(self, results):
assert 'gt_bboxes' in results
gt_bboxes = results['gt_bboxes']
w = gt_bboxes[:, 2] - gt_bboxes[:, 0]
h = gt_bboxes[:, 3] - gt_bboxes[:, 1]
keep = (w > self.min_gt_bbox_wh[0]) & (h > self.min_gt_bbox_wh[1])
if not keep.any():
return None
else:
keys = ('gt_bboxes', 'gt_labels', 'gt_masks', 'gt_semantic_seg')
for key in keys:
if key in results:
results[key] = results[key][keep]
return results
| 1 | 26,483 | Maybe there is no need to modify it. Because if you don't use the mask, it won't be initialized. | open-mmlab-mmdetection | py |
@@ -104,8 +104,7 @@ final class SelectTraceIdsFromSpan extends ResultSetFutureCall {
Input input =
new AutoValue_SelectTraceIdsFromSpan_Input(
serviceName,
- // % for like, bracing with ░ to ensure no accidental substring match
- "%░" + annotationKey + "░%",
+ annotationKey,
timestampRange.startUUID,
timestampRange.endUUID,
limit); | 1 | /*
* Copyright 2015-2018 The OpenZipkin 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.
*/
package zipkin2.storage.cassandra;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.google.auto.value.AutoValue;
import java.util.AbstractMap;
import java.util.LinkedHashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import zipkin2.Call;
import zipkin2.internal.Nullable;
import zipkin2.storage.cassandra.CassandraSpanStore.TimestampRange;
import zipkin2.storage.cassandra.internal.call.AccumulateAllResults;
import zipkin2.storage.cassandra.internal.call.ResultSetFutureCall;
import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
import static zipkin2.storage.cassandra.Schema.TABLE_SPAN;
/**
* Selects from the {@link Schema#TABLE_SPAN} using data in the partition key or SASI indexes.
*
* <p>Note: While queries here use {@link Select#allowFiltering()}, they do so within a SASI clause,
* and only return (traceId, timestamp) tuples. This means the entire spans table is not scanned,
* unless the time range implies that.
*
* <p>The spans table is sorted descending by timestamp. When a query includes only a time range,
* the first N rows are already in the correct order. However, the cardinality of rows is a function
* of span count, not trace count. This implies an over-fetch function based on average span count
* per trace in order to achieve N distinct trace IDs. For example if there are 3 spans per trace,
* and over-fetch function of 3 * intended limit will work. See {@link
* CassandraStorage#indexFetchMultiplier()} for an associated parameter.
*/
final class SelectTraceIdsFromSpan extends ResultSetFutureCall {
@AutoValue
abstract static class Input {
@Nullable
abstract String l_service();
@Nullable
abstract String annotation_query();
abstract UUID start_ts();
abstract UUID end_ts();
abstract int limit_();
}
static class Factory {
final Session session;
final PreparedStatement withAnnotationQuery, withServiceAndAnnotationQuery;
Factory(Session session) {
this.session = session;
// separate to avoid: "Unsupported unset value for column duration" maybe SASI related
// TODO: revisit on next driver update
this.withAnnotationQuery =
session.prepare(
QueryBuilder.select("ts", "trace_id")
.from(TABLE_SPAN)
.where(QueryBuilder.like("annotation_query", bindMarker("annotation_query")))
.and(QueryBuilder.gte("ts_uuid", bindMarker("start_ts")))
.and(QueryBuilder.lte("ts_uuid", bindMarker("end_ts")))
.limit(bindMarker("limit_"))
.allowFiltering());
this.withServiceAndAnnotationQuery =
session.prepare(
QueryBuilder.select("ts", "trace_id")
.from(TABLE_SPAN)
.where(QueryBuilder.eq("l_service", bindMarker("l_service")))
.and(QueryBuilder.like("annotation_query", bindMarker("annotation_query")))
.and(QueryBuilder.gte("ts_uuid", bindMarker("start_ts")))
.and(QueryBuilder.lte("ts_uuid", bindMarker("end_ts")))
.limit(bindMarker("limit_"))
.allowFiltering());
}
Call<Set<Entry<String, Long>>> newCall(
@Nullable String serviceName,
String annotationKey,
TimestampRange timestampRange,
int limit) {
Input input =
new AutoValue_SelectTraceIdsFromSpan_Input(
serviceName,
// % for like, bracing with ░ to ensure no accidental substring match
"%░" + annotationKey + "░%",
timestampRange.startUUID,
timestampRange.endUUID,
limit);
return new SelectTraceIdsFromSpan(
this,
serviceName != null ? withServiceAndAnnotationQuery : withAnnotationQuery,
input)
.flatMap(new AccumulateTraceIdTsLong());
}
}
final Factory factory;
final PreparedStatement preparedStatement;
final Input input;
SelectTraceIdsFromSpan(Factory factory, PreparedStatement preparedStatement, Input input) {
this.factory = factory;
this.preparedStatement = preparedStatement;
this.input = input;
}
@Override
protected ResultSetFuture newFuture() {
BoundStatement bound = preparedStatement.bind();
if (input.l_service() != null) bound.setString("l_service", input.l_service());
if (input.annotation_query() != null) {
bound.setString("annotation_query", input.annotation_query());
}
bound
.setUUID("start_ts", input.start_ts())
.setUUID("end_ts", input.end_ts())
.setInt("limit_", input.limit_())
.setFetchSize(input.limit_());
return factory.session.executeAsync(bound);
}
@Override
public SelectTraceIdsFromSpan clone() {
return new SelectTraceIdsFromSpan(factory, preparedStatement, input);
}
@Override
public String toString() {
return input.toString().replace("Input", "SelectTraceIdsFromSpan");
}
static final class AccumulateTraceIdTsLong
extends AccumulateAllResults<Set<Entry<String, Long>>> {
@Override
protected Supplier<Set<Entry<String, Long>>> supplier() {
return LinkedHashSet::new; // because results are not distinct
}
@Override
protected BiConsumer<Row, Set<Entry<String, Long>>> accumulator() {
return (row, result) -> {
if (row.isNull("ts")) return;
result.add(new AbstractMap.SimpleEntry<>(row.getString("trace_id"), row.getLong("ts")));
};
}
@Override
public String toString() {
return "AccumulateTraceIdTsLong{}";
}
}
}
| 1 | 13,277 | Is there a reason we wouldn't want the trailing `%`? I'm guessing that without the trailing `%` it will just do a strict match vs a partial prefix right? | openzipkin-zipkin | java |
@@ -29,6 +29,13 @@
#include <opae/fpga.h>
#include <time.h>
#include "fpga_dma.h"
+#include <getopt.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <sys/stat.h>
+#include "safe_string/safe_string.h"
/**
* \fpga_dma_test.c
* \brief User-mode DMA test | 1 | // Copyright(c) 2017, Intel Corporation
//
// 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 Intel Corporation nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <string.h>
#include <uuid/uuid.h>
#include <opae/fpga.h>
#include <time.h>
#include "fpga_dma.h"
/**
* \fpga_dma_test.c
* \brief User-mode DMA test
*/
#include <stdlib.h>
#include <assert.h>
#define HELLO_AFU_ID "331DB30C-9885-41EA-9081-F88B8F655CAA"
#define TEST_BUF_SIZE (10*1024*1024)
#define ASE_TEST_BUF_SIZE (4*1024)
static int err_cnt;
/*
* macro for checking return codes
*/
#define ON_ERR_GOTO(res, label, desc)\
do {\
if ((res) != FPGA_OK) {\
err_cnt++;\
fprintf(stderr, "Error %s: %s\n", (desc), fpgaErrStr(res));\
goto label;\
} \
} while (0)
void fill_buffer(char *buf, size_t size)
{
size_t i = 0;
// use a deterministic seed to generate pseudo-random numbers
srand(99);
for (i = 0; i < size; i++) {
*buf = rand()%256;
buf++;
}
}
fpga_result verify_buffer(char *buf, size_t size)
{
size_t i, rnum = 0;
srand(99);
for (i = 0; i < size; i++) {
rnum = rand()%256;
if ((*buf&0xFF) != rnum) {
printf("Invalid data at %zx Expected = %zx Actual = %x\n", i, rnum, (*buf&0xFF));
return FPGA_INVALID_PARAM;
}
buf++;
}
printf("Buffer Verification Success!\n");
return FPGA_OK;
}
void clear_buffer(char *buf, size_t size)
{
memset(buf, 0, size);
}
void report_bandwidth(size_t size, double seconds)
{
double throughput = (double)size/((double)seconds*1000*1000);
printf("\rMeasured bandwidth = %lf Megabytes/sec\n", throughput);
}
// return elapsed time
double getTime(struct timespec start, struct timespec end)
{
uint64_t diff = 1000000000L * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
return (double) diff/(double)1000000000L;
}
fpga_result ddr_sweep(fpga_dma_handle dma_h)
{
int res;
struct timespec start, end;
ssize_t total_mem_size = (uint64_t)(4*1024)*(uint64_t)(1024*1024);
uint64_t *dma_buf_ptr = malloc(total_mem_size);
if (dma_buf_ptr == NULL) {
printf("Unable to allocate %ld bytes of memory", total_mem_size);
return FPGA_NO_MEMORY;
}
printf("Allocated test buffer\n");
printf("Fill test buffer\n");
fill_buffer((char *)dma_buf_ptr, total_mem_size);
uint64_t src = (uint64_t)dma_buf_ptr;
uint64_t dst = 0x0;
printf("DDR Sweep Host to FPGA\n");
clock_gettime(CLOCK_MONOTONIC, &start);
res = fpgaDmaTransferSync(dma_h, dst, src, total_mem_size, HOST_TO_FPGA_MM);
clock_gettime(CLOCK_MONOTONIC, &end);
if (res != FPGA_OK) {
printf(" fpgaDmaTransferSync Host to FPGA failed with error %s", fpgaErrStr(res));
free(dma_buf_ptr);
return FPGA_EXCEPTION;
}
report_bandwidth(total_mem_size, getTime(start, end));
printf("\rClear buffer\n");
clear_buffer((char *)dma_buf_ptr, total_mem_size);
src = 0x0;
dst = (uint64_t)dma_buf_ptr;
printf("DDR Sweep FPGA to Host\n");
clock_gettime(CLOCK_MONOTONIC, &start);
res = fpgaDmaTransferSync(dma_h, dst, src, total_mem_size, FPGA_TO_HOST_MM);
clock_gettime(CLOCK_MONOTONIC, &end);
if (res != FPGA_OK) {
printf(" fpgaDmaTransferSync FPGA to Host failed with error %s", fpgaErrStr(res));
free(dma_buf_ptr);
return FPGA_EXCEPTION;
}
report_bandwidth(total_mem_size, getTime(start, end));
printf("Verifying buffer..\n");
verify_buffer((char *)dma_buf_ptr, total_mem_size);
free(dma_buf_ptr);
return FPGA_OK;
}
int main(int argc, char *argv[])
{
fpga_result res = FPGA_OK;
fpga_dma_handle dma_h;
uint64_t count;
fpga_properties filter = NULL;
fpga_token afc_token;
fpga_handle afc_h;
fpga_guid guid;
uint32_t num_matches;
volatile uint64_t *mmio_ptr = NULL;
uint64_t *dma_buf_ptr = NULL;
uint32_t use_ase;
if (argc < 2) {
printf("Usage: fpga_dma_test <use_ase = 1 (simulation only), 0 (hardware)>");
return 1;
}
use_ase = atoi(argv[1]);
if (use_ase) {
printf("Running test in ASE mode\n");
} else {
printf("Running test in HW mode\n");
}
// enumerate the afc
if (uuid_parse(HELLO_AFU_ID, guid) < 0) {
return 1;
}
res = fpgaGetProperties(NULL, &filter);
ON_ERR_GOTO(res, out, "fpgaGetProperties");
res = fpgaPropertiesSetObjectType(filter, FPGA_ACCELERATOR);
ON_ERR_GOTO(res, out_destroy_prop, "fpgaPropertiesSetObjectType");
res = fpgaPropertiesSetGUID(filter, guid);
ON_ERR_GOTO(res, out_destroy_prop, "fpgaPropertiesSetGUID");
res = fpgaEnumerate(&filter, 1, &afc_token, 1, &num_matches);
ON_ERR_GOTO(res, out_destroy_prop, "fpgaEnumerate");
if (num_matches < 1) {
printf("Error: Number of matches < 1");
ON_ERR_GOTO(FPGA_INVALID_PARAM, out_destroy_prop, "num_matches<1");
}
// open the AFC
res = fpgaOpen(afc_token, &afc_h, 0);
ON_ERR_GOTO(res, out_destroy_tok, "fpgaOpen");
if (!use_ase) {
res = fpgaMapMMIO(afc_h, 0, (uint64_t **)&mmio_ptr);
ON_ERR_GOTO(res, out_close, "fpgaMapMMIO");
}
// reset AFC
res = fpgaReset(afc_h);
ON_ERR_GOTO(res, out_unmap, "fpgaReset");
res = fpgaDmaOpen(afc_h, &dma_h);
ON_ERR_GOTO(res, out_dma_close, "fpgaDmaOpen");
if (!dma_h) {
res = FPGA_EXCEPTION;
ON_ERR_GOTO(res, out_dma_close, "Invaid DMA Handle");
}
if (use_ase)
count = ASE_TEST_BUF_SIZE;
else
count = TEST_BUF_SIZE;
dma_buf_ptr = (uint64_t *)malloc(count);
if (!dma_buf_ptr) {
res = FPGA_NO_MEMORY;
ON_ERR_GOTO(res, out_dma_close, "Error allocating memory");
}
fill_buffer((char *)dma_buf_ptr, count);
// Test procedure
// - Fill host buffer with pseudo-random data
// - Copy from host buffer to FPGA buffer at address 0x0
// - Clear host buffer
// - Copy from FPGA buffer to host buffer
// - Verify host buffer data
// - Clear host buffer
// - Copy FPGA buffer at address 0x0 to FPGA buffer at addr "count"
// - Copy data from FPGA buffer at addr "count" to host buffer
// - Verify host buffer data
// copy from host to fpga
res = fpgaDmaTransferSync(dma_h, 0x0 /*dst*/, (uint64_t)dma_buf_ptr /*src*/, count, HOST_TO_FPGA_MM);
ON_ERR_GOTO(res, out_dma_close, "fpgaDmaTransferSync HOST_TO_FPGA_MM");
clear_buffer((char *)dma_buf_ptr, count);
// copy from fpga to host
res = fpgaDmaTransferSync(dma_h, (uint64_t)dma_buf_ptr /*dst*/, 0x0 /*src*/, count, FPGA_TO_HOST_MM);
ON_ERR_GOTO(res, out_dma_close, "fpgaDmaTransferSync FPGA_TO_HOST_MM");
res = verify_buffer((char *)dma_buf_ptr, count);
ON_ERR_GOTO(res, out_dma_close, "verify_buffer");
clear_buffer((char *)dma_buf_ptr, count);
// copy from fpga to fpga
res = fpgaDmaTransferSync(dma_h, count /*dst*/, 0x0 /*src*/, count, FPGA_TO_FPGA_MM);
ON_ERR_GOTO(res, out_dma_close, "fpgaDmaTransferSync FPGA_TO_FPGA_MM");
// copy from fpga to host
res = fpgaDmaTransferSync(dma_h, (uint64_t)dma_buf_ptr /*dst*/, count /*src*/, count, FPGA_TO_HOST_MM);
ON_ERR_GOTO(res, out_dma_close, "fpgaDmaTransferSync FPGA_TO_HOST_MM");
res = verify_buffer((char *)dma_buf_ptr, count);
ON_ERR_GOTO(res, out_dma_close, "verify_buffer");
if (!use_ase) {
printf("Running DDR sweep test\n");
res = ddr_sweep(dma_h);
ON_ERR_GOTO(res, out_dma_close, "ddr_sweep");
}
out_dma_close:
free(dma_buf_ptr);
if (dma_h)
res = fpgaDmaClose(dma_h);
ON_ERR_GOTO(res, out_unmap, "fpgaDmaClose");
out_unmap:
if (!use_ase) {
res = fpgaUnmapMMIO(afc_h, 0);
ON_ERR_GOTO(res, out_close, "fpgaUnmapMMIO");
}
out_close:
res = fpgaClose(afc_h);
ON_ERR_GOTO(res, out_destroy_tok, "fpgaClose");
out_destroy_tok:
res = fpgaDestroyToken(&afc_token);
ON_ERR_GOTO(res, out_destroy_prop, "fpgaDestroyToken");
out_destroy_prop:
res = fpgaDestroyProperties(&filter);
ON_ERR_GOTO(res, out, "fpgaDestroyProperties");
out:
return err_cnt;
}
| 1 | 15,864 | Please update the DMA test app in AFU repo once this gets approved. | OPAE-opae-sdk | c |
@@ -57,8 +57,8 @@ class SettingValueDataFixture extends AbstractReferenceFixture implements Depend
$manager->persist(new SettingValue(PricingSetting::DEFAULT_DOMAIN_CURRENCY, $defaultCurrency->getId(), Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::DEFAULT_AVAILABILITY_IN_STOCK, $defaultInStockAvailability->getId(), SettingValue::DOMAIN_ID_COMMON));
$manager->persist(new SettingValue(PricingSetting::FREE_TRANSPORT_AND_PAYMENT_PRICE_LIMIT, null, Domain::FIRST_DOMAIN_ID));
- $manager->persist(new SettingValue(SeoSettingFacade::SEO_META_DESCRIPTION_MAIN_PAGE, 'ShopSys Framework - the best solution for your eshop.', Domain::FIRST_DOMAIN_ID));
- $manager->persist(new SettingValue(SeoSettingFacade::SEO_TITLE_MAIN_PAGE, 'ShopSys Framework - Title page', Domain::FIRST_DOMAIN_ID));
+ $manager->persist(new SettingValue(SeoSettingFacade::SEO_META_DESCRIPTION_MAIN_PAGE, 'Shopsys Framework - the best solution for your eshop.', Domain::FIRST_DOMAIN_ID));
+ $manager->persist(new SettingValue(SeoSettingFacade::SEO_TITLE_MAIN_PAGE, 'Shopsys Framework - Title page', Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(SeoSettingFacade::SEO_TITLE_ADD_ON, '| Demo eshop', Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::TERMS_AND_CONDITIONS_ARTICLE_ID, null, Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::COOKIES_ARTICLE_ID, null, Domain::FIRST_DOMAIN_ID)); | 1 | <?php
namespace Shopsys\FrameworkBundle\DataFixtures\Base;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Shopsys\FrameworkBundle\Component\DataFixture\AbstractReferenceFixture;
use Shopsys\FrameworkBundle\Component\Domain\Domain;
use Shopsys\FrameworkBundle\Component\Setting\Setting;
use Shopsys\FrameworkBundle\Component\Setting\SettingValue;
use Shopsys\FrameworkBundle\Component\String\HashGenerator;
use Shopsys\FrameworkBundle\Model\Mail\Setting\MailSetting;
use Shopsys\FrameworkBundle\Model\Pricing\PricingSetting;
use Shopsys\FrameworkBundle\Model\Pricing\Vat\Vat;
use Shopsys\FrameworkBundle\Model\Seo\SeoSettingFacade;
class SettingValueDataFixture extends AbstractReferenceFixture implements DependentFixtureInterface
{
/**
* @param \Doctrine\Common\Persistence\ObjectManager $manager
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function load(ObjectManager $manager)
{
$vat = $this->getReference(VatDataFixture::VAT_HIGH);
/* @var $vat \Shopsys\FrameworkBundle\Model\Pricing\Vat\Vat */
$pricingGroup1 = $this->getReference(PricingGroupDataFixture::PRICING_GROUP_ORDINARY_DOMAIN_1);
/* @var $pricingGroup2 \Shopsys\FrameworkBundle\Model\Pricing\Group\PricingGroup */
$defaultCurrency = $this->getReference(CurrencyDataFixture::CURRENCY_CZK);
/* @var $defaultCurrency \Shopsys\FrameworkBundle\Model\Pricing\Currency\Currency */
$defaultInStockAvailability = $this->getReference(AvailabilityDataFixture::AVAILABILITY_IN_STOCK);
/* @var $defaultInStockAvailability \Shopsys\FrameworkBundle\Model\Product\Availability\Availability */
$hashGenerator = $this->get(HashGenerator::class);
/* @var $hashGenerator \Shopsys\FrameworkBundle\Component\String\HashGenerator */
$defaultUnit = $this->getReference(UnitDataFixture::UNIT_PIECES);
/* @var $defaultUnit \Shopsys\FrameworkBundle\Model\Product\Unit\Unit */
$orderSentText = '
<p>
Order number {number} has been sent, thank you for your purchase.
We will contact you about next order status. <br /><br />
<a href="{order_detail_url}">Track</a> the status of your order. <br />
{transport_instructions} <br />
{payment_instructions} <br />
</p>
';
// @codingStandardsIgnoreStart
$manager->persist(new SettingValue(PricingSetting::INPUT_PRICE_TYPE, PricingSetting::INPUT_PRICE_TYPE_WITHOUT_VAT, SettingValue::DOMAIN_ID_COMMON));
$manager->persist(new SettingValue(PricingSetting::ROUNDING_TYPE, PricingSetting::ROUNDING_TYPE_INTEGER, SettingValue::DOMAIN_ID_COMMON));
$manager->persist(new SettingValue(Vat::SETTING_DEFAULT_VAT, $vat->getId(), SettingValue::DOMAIN_ID_COMMON));
$manager->persist(new SettingValue(Setting::ORDER_SENT_PAGE_CONTENT, $orderSentText, Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(MailSetting::MAIN_ADMIN_MAIL, 'no-reply@netdevelo.cz', Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(MailSetting::MAIN_ADMIN_MAIL_NAME, 'Shopsys', Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::DEFAULT_PRICING_GROUP, $pricingGroup1->getId(), Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(PricingSetting::DEFAULT_CURRENCY, $defaultCurrency->getId(), SettingValue::DOMAIN_ID_COMMON));
$manager->persist(new SettingValue(PricingSetting::DEFAULT_DOMAIN_CURRENCY, $defaultCurrency->getId(), Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::DEFAULT_AVAILABILITY_IN_STOCK, $defaultInStockAvailability->getId(), SettingValue::DOMAIN_ID_COMMON));
$manager->persist(new SettingValue(PricingSetting::FREE_TRANSPORT_AND_PAYMENT_PRICE_LIMIT, null, Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(SeoSettingFacade::SEO_META_DESCRIPTION_MAIN_PAGE, 'ShopSys Framework - the best solution for your eshop.', Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(SeoSettingFacade::SEO_TITLE_MAIN_PAGE, 'ShopSys Framework - Title page', Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(SeoSettingFacade::SEO_TITLE_ADD_ON, '| Demo eshop', Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::TERMS_AND_CONDITIONS_ARTICLE_ID, null, Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::COOKIES_ARTICLE_ID, null, Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::DOMAIN_DATA_CREATED, true, Domain::FIRST_DOMAIN_ID));
$manager->persist(new SettingValue(Setting::FEED_HASH, $hashGenerator->generateHash(10), SettingValue::DOMAIN_ID_COMMON));
$manager->persist(new SettingValue(Setting::DEFAULT_UNIT, $defaultUnit->getId(), SettingValue::DOMAIN_ID_COMMON));
// @codingStandardsIgnoreStop
$manager->flush();
$this->clearSettingCache();
}
private function clearSettingCache()
{
$setting = $this->get(Setting::class);
/* @var $setting \Shopsys\FrameworkBundle\Component\Setting\Setting */
$setting->clearCache();
}
/**
* {@inheritDoc}
*/
public function getDependencies()
{
return [
AvailabilityDataFixture::class,
VatDataFixture::class,
];
}
}
| 1 | 9,433 | There should be a migration for that as well to reflect the change on in-production instances | shopsys-shopsys | php |
@@ -41,6 +41,7 @@ var _ = BeforeSuite(func() {
appName = fmt.Sprintf("e2e-customizedenv-%d", time.Now().Unix())
vpcConfig = client.EnvInitRequestVPCConfig{
CIDR: "10.1.0.0/16",
+ AZs: `""`, // Use default AZ options.
PrivateSubnetCIDRs: "10.1.2.0/24,10.1.3.0/24",
PublicSubnetCIDRs: "10.1.0.0/24,10.1.1.0/24",
} | 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package customized_env_test
import (
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var cli *client.CLI
var aws *client.AWS
var appName string
var vpcStackName string
var vpcStackTemplatePath string
var vpcImport client.EnvInitRequestVPCImport
var vpcConfig client.EnvInitRequestVPCConfig
/**
The Customized Env Suite creates multiple environments with customized resources,
deploys a service to it, and then
tears it down.
*/
func Test_Customized_Env(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Customized Env Svc Suite")
}
var _ = BeforeSuite(func() {
vpcStackName = fmt.Sprintf("e2e-customizedenv-vpc-stack-%d", time.Now().Unix())
vpcStackTemplatePath = "file://vpc.yml"
ecsCli, err := client.NewCLI()
Expect(err).NotTo(HaveOccurred())
cli = ecsCli
aws = client.NewAWS()
appName = fmt.Sprintf("e2e-customizedenv-%d", time.Now().Unix())
vpcConfig = client.EnvInitRequestVPCConfig{
CIDR: "10.1.0.0/16",
PrivateSubnetCIDRs: "10.1.2.0/24,10.1.3.0/24",
PublicSubnetCIDRs: "10.1.0.0/24,10.1.1.0/24",
}
})
var _ = AfterSuite(func() {
_, err := cli.AppDelete()
Expect(err).NotTo(HaveOccurred())
// Delete VPC stack.
err = aws.DeleteStack(vpcStackName)
Expect(err).NotTo(HaveOccurred())
})
func BeforeAll(fn func()) {
first := true
BeforeEach(func() {
if first {
fn()
first = false
}
})
}
| 1 | 20,255 | Why does it have to be `""` instead of an empty string | aws-copilot-cli | go |
@@ -107,7 +107,7 @@ module RSpec
start(reporter)
begin
- unless pending
+ unless pending or RSpec.configuration.dry_run
with_around_each_hooks do
begin
run_before_each | 1 | module RSpec
module Core
# Wrapper for an instance of a subclass of {ExampleGroup}. An instance of
# `Example` is returned by the {ExampleGroup#example example} method
# exposed to examples, {Hooks#before before} and {Hooks#after after} hooks,
# and yielded to {Hooks#around around} hooks.
#
# Useful for configuring logging and/or taking some action based
# on the state of an example's metadata.
#
# @example
#
# RSpec.configure do |config|
# config.before do
# log example.description
# end
#
# config.after do
# log example.description
# end
#
# config.around do |ex|
# log example.description
# ex.run
# end
# end
#
# shared_examples "auditable" do
# it "does something" do
# log "#{example.full_description}: #{auditable.inspect}"
# auditable.should do_something
# end
# end
#
# @see ExampleGroup
class Example
# @private
#
# Used to define methods that delegate to this example's metadata
def self.delegate_to_metadata(*keys)
keys.each { |key| define_method(key) { @metadata[key] } }
end
delegate_to_metadata :full_description, :execution_result, :file_path, :pending, :location
# Returns the string submitted to `example` or its aliases (e.g.
# `specify`, `it`, etc). If no string is submitted (e.g. `it { should
# do_something }`) it returns the message generated by the matcher if
# there is one, otherwise returns a message including the location of the
# example.
def description
description = metadata[:description].to_s.empty? ? "example at #{location}" : metadata[:description]
RSpec.configuration.format_docstrings_block.call(description)
end
# @attr_reader
#
# Returns the first exception raised in the context of running this
# example (nil if no exception is raised)
attr_reader :exception
# @attr_reader
#
# Returns the metadata object associated with this example.
attr_reader :metadata
# @attr_reader
# @private
#
# Returns the example_group_instance that provides the context for
# running this example.
attr_reader :example_group_instance
# Creates a new instance of Example.
# @param example_group_class the subclass of ExampleGroup in which this Example is declared
# @param description the String passed to the `it` method (or alias)
# @param metadata additional args passed to `it` to be used as metadata
# @param example_block the block of code that represents the example
def initialize(example_group_class, description, metadata, example_block=nil)
@example_group_class, @options, @example_block = example_group_class, metadata, example_block
@metadata = @example_group_class.metadata.for_example(description, metadata)
@example_group_instance = @exception = nil
@pending_declared_in_example = false
end
# @deprecated access options via metadata instead
def options
@options
end
# Returns the example group class that provides the context for running
# this example.
def example_group
@example_group_class
end
alias_method :pending?, :pending
# @api private
# instance_evals the block passed to the constructor in the context of
# the instance of {ExampleGroup}.
# @param example_group_instance the instance of an ExampleGroup subclass
def run(example_group_instance, reporter)
@example_group_instance = example_group_instance
RSpec.current_example = self
start(reporter)
begin
unless pending
with_around_each_hooks do
begin
run_before_each
@example_group_instance.instance_exec(self, &@example_block)
rescue Pending::PendingDeclaredInExample => e
@pending_declared_in_example = e.message
rescue Exception => e
set_exception(e)
ensure
run_after_each
end
end
end
rescue Exception => e
set_exception(e)
ensure
@example_group_instance.instance_variables.each do |ivar|
@example_group_instance.instance_variable_set(ivar, nil)
end
@example_group_instance = nil
begin
assign_generated_description
rescue Exception => e
set_exception(e, "while assigning the example description")
end
end
finish(reporter)
ensure
RSpec.current_example = nil
end
# @api private
#
# Wraps the example block in a Proc so it can invoked using `run` or
# `call` in [around](../Hooks#around-instance_method) hooks.
def self.procsy(metadata, &proc)
proc.extend(Procsy).with(metadata)
end
# Used to extend a `Proc` with behavior that makes it look something like
# an {Example} in an {Hooks#around around} hook.
#
# @note Procsy, itself, is not a public API, but we're documenting it
# here to document how to interact with the object yielded to an
# `around` hook.
#
# @example
#
# RSpec.configure do |c|
# c.around do |ex| # ex is a Proc extended with Procsy
# if ex.metadata[:key] == :some_value && some_global_condition
# raise "some message"
# end
# ex.run # run delegates to ex.call
# end
# end
module Procsy
# The `metadata` of the {Example} instance.
attr_reader :metadata
# @api private
# @param [Proc]
# Adds a `run` method to the extended Proc, allowing it to be invoked
# in an [around](../Hooks#around-instance_method) hook using either
# `run` or `call`.
def self.extended(proc)
# @api public
# Foo bar
def proc.run; call; end
end
# @api private
def with(metadata)
@metadata = metadata
self
end
end
# @private
def any_apply?(filters)
metadata.any_apply?(filters)
end
# @private
def all_apply?(filters)
@metadata.all_apply?(filters) || @example_group_class.all_apply?(filters)
end
# @private
def around_each_hooks
@around_each_hooks ||= example_group.around_each_hooks_for(self)
end
# @private
#
# Used internally to set an exception in an after hook, which
# captures the exception but doesn't raise it.
def set_exception(exception, context=nil)
if @exception && context != :dont_print
# An error has already been set; we don't want to override it,
# but we also don't want silence the error, so let's print it.
msg = <<-EOS
An error occurred #{context}
#{exception.class}: #{exception.message}
occurred at #{exception.backtrace.first}
EOS
RSpec.configuration.reporter.message(msg)
end
@exception ||= exception
end
# @private
#
# Used internally to set an exception and fail without actually executing
# the example when an exception is raised in before(:all).
def fail_with_exception(reporter, exception)
start(reporter)
set_exception(exception)
finish(reporter)
end
# @private
def instance_exec_with_rescue(context = nil, &block)
@example_group_instance.instance_exec_with_rescue(self, context, &block)
end
# @private
def instance_exec(*args, &block)
@example_group_instance.instance_exec(*args, &block)
end
private
def with_around_each_hooks(&block)
if around_each_hooks.empty?
yield
else
@example_group_class.run_around_each_hooks(self, Example.procsy(metadata, &block))
end
rescue Exception => e
set_exception(e, "in an around(:each) hook")
end
def start(reporter)
reporter.example_started(self)
record :started_at => RSpec::Core::Time.now
end
# @private
module NotPendingExampleFixed
def pending_fixed?; false; end
end
def finish(reporter)
if @exception
@exception.extend(NotPendingExampleFixed) unless @exception.respond_to?(:pending_fixed?)
record_finished 'failed', :exception => @exception
reporter.example_failed self
false
elsif @pending_declared_in_example
record_finished 'pending', :pending_message => @pending_declared_in_example
reporter.example_pending self
true
elsif pending
record_finished 'pending', :pending_message => String === pending ? pending : Pending::NO_REASON_GIVEN
reporter.example_pending self
true
else
record_finished 'passed'
reporter.example_passed self
true
end
end
def record_finished(status, results={})
finished_at = RSpec::Core::Time.now
record results.merge(:status => status, :finished_at => finished_at, :run_time => (finished_at - execution_result[:started_at]).to_f)
end
def run_before_each
@example_group_instance.setup_mocks_for_rspec
@example_group_class.run_before_each_hooks(self)
end
def run_after_each
@example_group_class.run_after_each_hooks(self)
verify_mocks
rescue Exception => e
set_exception(e, "in an after(:each) hook")
ensure
@example_group_instance.teardown_mocks_for_rspec
end
def verify_mocks
@example_group_instance.verify_mocks_for_rspec
rescue Exception => e
set_exception(e, :dont_print)
end
def assign_generated_description
return unless RSpec.configuration.expecting_with_rspec?
if metadata[:description_args].empty? and !pending?
metadata[:description_args] << RSpec::Matchers.generated_description
end
RSpec::Matchers.clear_generated_description
end
def record(results={})
execution_result.update(results)
end
end
end
end
| 1 | 9,847 | This is very strongly opinionated so feel free to disagree with me better, but as conditionals get more complex I like turn them into ifs instead of unlesses. What do you think? | rspec-rspec-core | rb |
@@ -894,7 +894,7 @@ module RSpec
# @private
RANDOM_ORDERING = lambda do |list|
Kernel.srand RSpec.configuration.seed
- ordering = list.sort_by { Kernel.rand(list.size) }
+ ordering = list.shuffle
Kernel.srand # reset random generation
ordering
end | 1 | require 'fileutils'
require 'rspec/core/backtrace_cleaner'
require 'rspec/core/ruby_project'
require 'rspec/core/formatters/deprecation_formatter.rb'
module RSpec
module Core
# Stores runtime configuration information.
#
# Configuration options are loaded from `~/.rspec`, `.rspec`,
# `.rspec-local`, command line switches, and the `SPEC_OPTS` environment
# variable (listed in lowest to highest precedence; for example, an option
# in `~/.rspec` can be overridden by an option in `.rspec-local`).
#
# @example Standard settings
# RSpec.configure do |c|
# c.drb = true
# c.drb_port = 1234
# c.default_path = 'behavior'
# end
#
# @example Hooks
# RSpec.configure do |c|
# c.before(:suite) { establish_connection }
# c.before(:each) { log_in_as :authorized }
# c.around(:each) { |ex| Database.transaction(&ex) }
# end
#
# @see RSpec.configure
# @see Hooks
class Configuration
include RSpec::Core::Hooks
class MustBeConfiguredBeforeExampleGroupsError < StandardError; end
# @private
def self.define_reader(name)
define_method(name) do
variable = instance_variable_defined?("@#{name}") ? instance_variable_get("@#{name}") : nil
value_for(name, variable)
end
end
# @private
def self.deprecate_alias_key
RSpec.deprecate("add_setting with :alias option", :replacement => ":alias_with")
end
# @private
def self.define_aliases(name, alias_name)
alias_method alias_name, name
alias_method "#{alias_name}=", "#{name}="
define_predicate_for alias_name
end
# @private
def self.define_predicate_for(*names)
names.each {|name| alias_method "#{name}?", name}
end
# @private
#
# Invoked by the `add_setting` instance method. Use that method on a
# `Configuration` instance rather than this class method.
def self.add_setting(name, opts={})
raise "Use the instance add_setting method if you want to set a default" if opts.has_key?(:default)
if opts[:alias]
deprecate_alias_key
define_aliases(opts[:alias], name)
else
attr_writer name
define_reader name
define_predicate_for name
end
Array(opts[:alias_with]).each do |alias_name|
define_aliases(name, alias_name)
end
end
# @macro [attach] add_setting
# @attribute $1
# Path to use if no path is provided to the `rspec` command (default:
# `"spec"`). Allows you to just type `rspec` instead of `rspec spec` to
# run all the examples in the `spec` directory.
add_setting :default_path
# Run examples over DRb (default: `false`). RSpec doesn't supply the DRb
# server, but you can use tools like spork.
add_setting :drb
# The drb_port (default: nil).
add_setting :drb_port
# Default: `$stderr`.
add_setting :error_stream
# Default: `$stderr`.
add_setting :deprecation_stream
# Clean up and exit after the first failure (default: `false`).
add_setting :fail_fast
# Prints the formatter output of your suite without running any
# examples or hooks.
add_setting :dry_run
# The exit code to return if there are any failures (default: 1).
add_setting :failure_exit_code
# Determines the order in which examples are run (default: OS standard
# load order for files, declaration order for groups and examples).
define_reader :order
# Indicates files configured to be required
define_reader :requires
# Returns dirs that have been prepended to the load path by #lib=
define_reader :libs
# Default: `$stdout`.
# Also known as `output` and `out`
add_setting :output_stream, :alias_with => [:output, :out]
# Load files matching this pattern (default: `'**/*_spec.rb'`)
add_setting :pattern, :alias_with => :filename_pattern
def pattern= value
if @spec_files_loaded
Kernel.warn "WARNING: Configuring `pattern` to #{value} has no effect since RSpec has already loaded the spec files. Called from #{CallerFilter.first_non_rspec_line}"
end
@pattern = value
end
alias :filename_pattern= :pattern=
# Report the times for the slowest examples (default: `false`).
# Use this to specify the number of examples to include in the profile.
add_setting :profile_examples
# Run all examples if none match the configured filters (default: `false`).
add_setting :run_all_when_everything_filtered
# Allow user to configure their own success/pending/failure colors
# @param [Symbol] should be one of the following: [:black, :white, :red, :green, :yellow, :blue, :magenta, :cyan]
add_setting :success_color
add_setting :pending_color
add_setting :failure_color
add_setting :default_color
add_setting :fixed_color
add_setting :detail_color
# Seed for random ordering (default: generated randomly each run).
#
# When you run specs with `--order random`, RSpec generates a random seed
# for the randomization and prints it to the `output_stream` (assuming
# you're using RSpec's built-in formatters). If you discover an ordering
# dependency (i.e. examples fail intermittently depending on order), set
# this (on Configuration or on the command line with `--seed`) to run
# using the same seed while you debug the issue.
#
# We recommend, actually, that you use the command line approach so you
# don't accidentally leave the seed encoded.
define_reader :seed
# When a block passed to pending fails (as expected), display the failure
# without reporting it as a failure (default: false).
add_setting :show_failures_in_pending_blocks
# Deprecated. This config option was added in RSpec 2 to pave the way
# for this being the default behavior in RSpec 3. Now this option is
# a no-op.
def treat_symbols_as_metadata_keys_with_true_values=(value)
RSpec.deprecate("RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=")
end
# @private
add_setting :tty
# @private
add_setting :include_or_extend_modules
# @private
add_setting :files_to_run
# @private
add_setting :expecting_with_rspec
# @private
attr_accessor :filter_manager
attr_reader :backtrace_cleaner
def initialize
@expectation_frameworks = []
@include_or_extend_modules = []
@mock_framework = nil
@files_to_run = []
@formatters = []
@color = false
@pattern = '**/*_spec.rb'
@failure_exit_code = 1
@spec_files_loaded = false
@backtrace_cleaner = BacktraceCleaner.new
@default_path = 'spec'
@deprecation_stream = $stderr
@filter_manager = FilterManager.new
@preferred_options = {}
@seed = srand % 0xFFFF
@failure_color = :red
@success_color = :green
@pending_color = :yellow
@default_color = :white
@fixed_color = :blue
@detail_color = :cyan
@profile_examples = false
@requires = []
@libs = []
end
# @private
#
# Used to set higher priority option values from the command line.
def force(hash)
if hash.has_key?(:seed)
hash[:order], hash[:seed] = order_and_seed_from_seed(hash[:seed])
elsif hash.has_key?(:order)
set_order_and_seed(hash)
end
@preferred_options.merge!(hash)
self.warnings = value_for :warnings, nil
end
# @private
def reset
@spec_files_loaded = false
@reporter = nil
@formatters.clear
end
# @overload add_setting(name)
# @overload add_setting(name, opts)
# @option opts [Symbol] :default
#
# set a default value for the generated getter and predicate methods:
#
# add_setting(:foo, :default => "default value")
#
# @option opts [Symbol] :alias_with
#
# Use `:alias_with` to alias the setter, getter, and predicate to another
# name, or names:
#
# add_setting(:foo, :alias_with => :bar)
# add_setting(:foo, :alias_with => [:bar, :baz])
#
# Adds a custom setting to the RSpec.configuration object.
#
# RSpec.configuration.add_setting :foo
#
# Used internally and by extension frameworks like rspec-rails, so they
# can add config settings that are domain specific. For example:
#
# RSpec.configure do |c|
# c.add_setting :use_transactional_fixtures,
# :default => true,
# :alias_with => :use_transactional_examples
# end
#
# `add_setting` creates three methods on the configuration object, a
# setter, a getter, and a predicate:
#
# RSpec.configuration.foo=(value)
# RSpec.configuration.foo
# RSpec.configuration.foo? # returns true if foo returns anything but nil or false
def add_setting(name, opts={})
default = opts.delete(:default)
(class << self; self; end).class_eval do
add_setting(name, opts)
end
send("#{name}=", default) if default
end
# Returns the configured mock framework adapter module
def mock_framework
mock_with :rspec unless @mock_framework
@mock_framework
end
# Delegates to mock_framework=(framework)
def mock_framework=(framework)
mock_with framework
end
# The patterns to always include to backtraces.
#
# Defaults to [Regexp.new Dir.getwd] if the current working directory
# matches any of the exclusion patterns. Otherwise it defaults to empty.
#
# One can replace the list by using the setter or modify it through the
# getter
def backtrace_inclusion_patterns
@backtrace_cleaner.inclusion_patterns
end
def backtrace_inclusion_patterns=(patterns)
@backtrace_cleaner.inclusion_patterns = patterns
end
# The patterns to discard from backtraces.
#
# Defaults to RSpec::Core::BacktraceCleaner::DEFAULT_EXCLUSION_PATTERNS
#
# One can replace the list by using the setter or modify it through the
# getter
#
# To override this behaviour and display a full backtrace, use
# `--backtrace`on the command line, in a `.rspec` file, or in the
# `rspec_options` attribute of RSpec's rake task.
def backtrace_exclusion_patterns
@backtrace_cleaner.exclusion_patterns
end
def backtrace_exclusion_patterns=(patterns)
@backtrace_cleaner.exclusion_patterns = patterns
end
# Sets the mock framework adapter module.
#
# `framework` can be a Symbol or a Module.
#
# Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the
# named framework.
#
# Given `:nothing`, configures no framework. Use this if you don't use
# any mocking framework to save a little bit of overhead.
#
# Given a Module, includes that module in every example group. The module
# should adhere to RSpec's mock framework adapter API:
#
# setup_mocks_for_rspec
# - called before each example
#
# verify_mocks_for_rspec
# - called after each example. Framework should raise an exception
# when expectations fail
#
# teardown_mocks_for_rspec
# - called after verify_mocks_for_rspec (even if there are errors)
#
# If the module responds to `configuration` and `mock_with` receives a block,
# it will yield the configuration object to the block e.g.
#
# config.mock_with OtherMockFrameworkAdapter do |mod_config|
# mod_config.custom_setting = true
# end
def mock_with(framework)
framework_module = case framework
when Module
framework
when String, Symbol
require case framework.to_s
when /rspec/i
'rspec/core/mocking/with_rspec'
when /mocha/i
'rspec/core/mocking/with_mocha'
when /rr/i
'rspec/core/mocking/with_rr'
when /flexmock/i
'rspec/core/mocking/with_flexmock'
else
'rspec/core/mocking/with_absolutely_nothing'
end
RSpec::Core::MockFrameworkAdapter
end
new_name, old_name = [framework_module, @mock_framework].map do |mod|
mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed
end
unless new_name == old_name
assert_no_example_groups_defined(:mock_framework)
end
if block_given?
raise "#{framework_module} must respond to `configuration` so that mock_with can yield it." unless framework_module.respond_to?(:configuration)
yield framework_module.configuration
end
@mock_framework = framework_module
end
# Returns the configured expectation framework adapter module(s)
def expectation_frameworks
expect_with :rspec if @expectation_frameworks.empty?
@expectation_frameworks
end
# Delegates to expect_with(framework)
def expectation_framework=(framework)
expect_with(framework)
end
# Sets the expectation framework module(s) to be included in each example
# group.
#
# `frameworks` can be `:rspec`, `:stdlib`, a custom module, or any
# combination thereof:
#
# config.expect_with :rspec
# config.expect_with :stdlib
# config.expect_with :rspec, :stdlib
# config.expect_with OtherExpectationFramework
#
# RSpec will translate `:rspec` and `:stdlib` into the appropriate
# modules.
#
# ## Configuration
#
# If the module responds to `configuration`, `expect_with` will
# yield the `configuration` object if given a block:
#
# config.expect_with OtherExpectationFramework do |custom_config|
# custom_config.custom_setting = true
# end
def expect_with(*frameworks)
modules = frameworks.map do |framework|
case framework
when Module
framework
when :rspec
require 'rspec/expectations'
self.expecting_with_rspec = true
::RSpec::Matchers
when :stdlib
require 'test/unit/assertions'
::Test::Unit::Assertions
else
raise ArgumentError, "#{framework.inspect} is not supported"
end
end
if (modules - @expectation_frameworks).any?
assert_no_example_groups_defined(:expect_with)
end
if block_given?
raise "expect_with only accepts a block with a single argument. Call expect_with #{modules.length} times, once with each argument, instead." if modules.length > 1
raise "#{modules.first} must respond to `configuration` so that expect_with can yield it." unless modules.first.respond_to?(:configuration)
yield modules.first.configuration
end
@expectation_frameworks.push(*modules)
end
def full_backtrace?
@backtrace_cleaner.full_backtrace?
end
def full_backtrace=(true_or_false)
@backtrace_cleaner.full_backtrace = true_or_false
end
def color(output=output_stream)
# rspec's built-in formatters all call this with the output argument,
# but defaulting to output_stream for backward compatibility with
# formatters in extension libs
return false unless output_to_tty?(output)
value_for(:color, @color)
end
def color=(bool)
if bool
if RSpec.windows_os? and not ENV['ANSICON']
warn "You must use ANSICON 1.31 or later (http://adoxa.3eeweb.com/ansicon/) to use colour on Windows"
@color = false
else
@color = true
end
end
end
# TODO - deprecate color_enabled - probably not until the last 2.x
# release before 3.0
alias_method :color_enabled, :color
alias_method :color_enabled=, :color=
define_predicate_for :color_enabled, :color
def libs=(libs)
libs.map do |lib|
@libs.unshift lib
$LOAD_PATH.unshift lib
end
end
def requires=(paths)
RSpec.deprecate("RSpec::Core::Configuration#requires=(paths)",
:replacement => "paths.each {|path| require path}")
paths.map {|path| require path}
@requires += paths
end
# Run examples defined on `line_numbers` in all files to run.
def line_numbers=(line_numbers)
filter_run :line_numbers => line_numbers.map{|l| l.to_i}
end
def line_numbers
filter.fetch(:line_numbers,[])
end
def full_description=(description)
filter_run :full_description => Regexp.union(*Array(description).map {|d| Regexp.new(d) })
end
def full_description
filter.fetch :full_description, nil
end
# @overload add_formatter(formatter)
#
# Adds a formatter to the formatters collection. `formatter` can be a
# string representing any of the built-in formatters (see
# `built_in_formatter`), or a custom formatter class.
#
# ### Note
#
# For internal purposes, `add_formatter` also accepts the name of a class
# and paths to use for output streams, but you should consider that a
# private api that may change at any time without notice.
def add_formatter(formatter_to_use, *paths)
formatter_class =
built_in_formatter(formatter_to_use) ||
custom_formatter(formatter_to_use) ||
(raise ArgumentError, "Formatter '#{formatter_to_use}' unknown - maybe you meant 'documentation' or 'progress'?.")
paths << output if paths.empty?
formatters << formatter_class.new(*paths.map {|p| String === p ? file_at(p) : p})
end
alias_method :formatter=, :add_formatter
def formatters
@formatters ||= []
end
def reporter
@reporter ||= begin
add_formatter('progress') if formatters.empty?
add_formatter(RSpec::Core::Formatters::DeprecationFormatter, deprecation_stream, output_stream)
Reporter.new(*formatters)
end
end
# @api private
#
# Defaults `profile_examples` to 10 examples when `@profile_examples` is `true`.
#
def profile_examples
profile = value_for(:profile_examples, @profile_examples)
if profile && !profile.is_a?(Integer)
10
else
profile
end
end
# @private
def files_or_directories_to_run=(*files)
files = files.flatten
files << default_path if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty?
self.files_to_run = get_files_to_run(files)
end
# Creates a method that delegates to `example` including the submitted
# `args`. Used internally to add variants of `example` like `pending`:
#
# @example
# alias_example_to :pending, :pending => true
#
# # This lets you do this:
#
# describe Thing do
# pending "does something" do
# thing = Thing.new
# end
# end
#
# # ... which is the equivalent of
#
# describe Thing do
# it "does something", :pending => true do
# thing = Thing.new
# end
# end
def alias_example_to(new_name, *args)
extra_options = Metadata.build_hash_from(args)
RSpec::Core::ExampleGroup.alias_example_to(new_name, extra_options)
end
# Define an alias for it_should_behave_like that allows different
# language (like "it_has_behavior" or "it_behaves_like") to be
# employed when including shared examples.
#
# Example:
#
# alias_it_behaves_like_to(:it_has_behavior, 'has behavior:')
#
# allows the user to include a shared example group like:
#
# describe Entity do
# it_has_behavior 'sortability' do
# let(:sortable) { Entity.new }
# end
# end
#
# which is reported in the output as:
#
# Entity
# has behavior: sortability
# # sortability examples here
def alias_it_behaves_like_to(new_name, report_label = '')
RSpec::Core::ExampleGroup.alias_it_behaves_like_to(new_name, report_label)
end
alias_method :alias_it_should_behave_like_to, :alias_it_behaves_like_to
# Adds key/value pairs to the `inclusion_filter`. If `args`
# includes any symbols that are not part of the hash, each symbol
# is treated as a key in the hash with the value `true`.
#
# ### Note
#
# Filters set using this method can be overridden from the command line
# or config files (e.g. `.rspec`).
#
# @example
# # given this declaration
# describe "something", :foo => 'bar' do
# # ...
# end
#
# # any of the following will include that group
# config.filter_run_including :foo => 'bar'
# config.filter_run_including :foo => /^ba/
# config.filter_run_including :foo => lambda {|v| v == 'bar'}
# config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
#
# # given a proc with an arity of 1, the lambda is passed the value related to the key, e.g.
# config.filter_run_including :foo => lambda {|v| v == 'bar'}
#
# # given a proc with an arity of 2, the lambda is passed the value related to the key,
# # and the metadata itself e.g.
# config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'}
#
# filter_run_including :foo # same as filter_run_including :foo => true
def filter_run_including(*args)
filter_manager.include_with_low_priority Metadata.build_hash_from(args)
end
alias_method :filter_run, :filter_run_including
# Clears and reassigns the `inclusion_filter`. Set to `nil` if you don't
# want any inclusion filter at all.
#
# ### Warning
#
# This overrides any inclusion filters/tags set on the command line or in
# configuration files.
def inclusion_filter=(filter)
filter_manager.include! Metadata.build_hash_from([filter])
end
alias_method :filter=, :inclusion_filter=
# Returns the `inclusion_filter`. If none has been set, returns an empty
# hash.
def inclusion_filter
filter_manager.inclusions
end
alias_method :filter, :inclusion_filter
# Adds key/value pairs to the `exclusion_filter`. If `args`
# includes any symbols that are not part of the hash, each symbol
# is treated as a key in the hash with the value `true`.
#
# ### Note
#
# Filters set using this method can be overridden from the command line
# or config files (e.g. `.rspec`).
#
# @example
# # given this declaration
# describe "something", :foo => 'bar' do
# # ...
# end
#
# # any of the following will exclude that group
# config.filter_run_excluding :foo => 'bar'
# config.filter_run_excluding :foo => /^ba/
# config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
# config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
#
# # given a proc with an arity of 1, the lambda is passed the value related to the key, e.g.
# config.filter_run_excluding :foo => lambda {|v| v == 'bar'}
#
# # given a proc with an arity of 2, the lambda is passed the value related to the key,
# # and the metadata itself e.g.
# config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'}
#
# filter_run_excluding :foo # same as filter_run_excluding :foo => true
def filter_run_excluding(*args)
filter_manager.exclude_with_low_priority Metadata.build_hash_from(args)
end
# Clears and reassigns the `exclusion_filter`. Set to `nil` if you don't
# want any exclusion filter at all.
#
# ### Warning
#
# This overrides any exclusion filters/tags set on the command line or in
# configuration files.
def exclusion_filter=(filter)
filter_manager.exclude! Metadata.build_hash_from([filter])
end
# Returns the `exclusion_filter`. If none has been set, returns an empty
# hash.
def exclusion_filter
filter_manager.exclusions
end
# Tells RSpec to include `mod` in example groups. Methods defined in
# `mod` are exposed to examples (not example groups). Use `filters` to
# constrain the groups in which to include the module.
#
# @example
#
# module AuthenticationHelpers
# def login_as(user)
# # ...
# end
# end
#
# module UserHelpers
# def users(username)
# # ...
# end
# end
#
# RSpec.configure do |config|
# config.include(UserHelpers) # included in all modules
# config.include(AuthenticationHelpers, :type => :request)
# end
#
# describe "edit profile", :type => :request do
# it "can be viewed by owning user" do
# login_as users(:jdoe)
# get "/profiles/jdoe"
# assert_select ".username", :text => 'jdoe'
# end
# end
#
# @see #extend
def include(mod, *filters)
include_or_extend_modules << [:include, mod, Metadata.build_hash_from(filters)]
end
# Tells RSpec to extend example groups with `mod`. Methods defined in
# `mod` are exposed to example groups (not examples). Use `filters` to
# constrain the groups to extend.
#
# Similar to `include`, but behavior is added to example groups, which
# are classes, rather than the examples, which are instances of those
# classes.
#
# @example
#
# module UiHelpers
# def run_in_browser
# # ...
# end
# end
#
# RSpec.configure do |config|
# config.extend(UiHelpers, :type => :request)
# end
#
# describe "edit profile", :type => :request do
# run_in_browser
#
# it "does stuff in the client" do
# # ...
# end
# end
#
# @see #include
def extend(mod, *filters)
include_or_extend_modules << [:extend, mod, Metadata.build_hash_from(filters)]
end
# @private
#
# Used internally to extend a group with modules using `include` and/or
# `extend`.
def configure_group(group)
include_or_extend_modules.each do |include_or_extend, mod, filters|
next unless filters.empty? || group.any_apply?(filters)
send("safe_#{include_or_extend}", mod, group)
end
end
# @private
def safe_include(mod, host)
host.send(:include,mod) unless host < mod
end
# @private
def setup_load_path_and_require(paths)
directories = ['lib', default_path].select { |p| File.directory? p }
RSpec::Core::RubyProject.add_to_load_path(*directories)
paths.each {|path| require path}
@requires += paths
end
# @private
if RUBY_VERSION.to_f >= 1.9
def safe_extend(mod, host)
host.extend(mod) unless (class << host; self; end) < mod
end
else
def safe_extend(mod, host)
host.extend(mod) unless (class << host; self; end).included_modules.include?(mod)
end
end
# @private
def configure_mock_framework
RSpec::Core::ExampleGroup.send(:include, mock_framework)
end
# @private
def configure_expectation_framework
expectation_frameworks.each do |framework|
RSpec::Core::ExampleGroup.send(:include, framework)
end
end
# @private
def load_spec_files
files_to_run.uniq.each {|f| load File.expand_path(f) }
@spec_files_loaded = true
raise_if_rspec_1_is_loaded
end
# @private
DEFAULT_FORMATTER = lambda { |string| string }
# Formats the docstring output using the block provided.
#
# @example
# # This will strip the descriptions of both examples and example groups.
# RSpec.configure do |config|
# config.format_docstrings { |s| s.strip }
# end
def format_docstrings(&block)
@format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER
end
# @private
def format_docstrings_block
@format_docstrings_block ||= DEFAULT_FORMATTER
end
# @api
#
# Sets the seed value and sets `order='rand'`
def seed=(seed)
order_and_seed_from_seed(seed)
end
# @api
#
# Sets the order and, if order is `'rand:<seed>'`, also sets the seed.
def order=(type)
order_and_seed_from_order(type)
end
def randomize?
order.to_s.match(/rand/)
end
# @private
DEFAULT_ORDERING = lambda { |list| list }
# @private
RANDOM_ORDERING = lambda do |list|
Kernel.srand RSpec.configuration.seed
ordering = list.sort_by { Kernel.rand(list.size) }
Kernel.srand # reset random generation
ordering
end
# Sets a strategy by which to order examples.
#
# @example
# RSpec.configure do |config|
# config.order_examples do |examples|
# examples.reverse
# end
# end
#
# @see #order_groups
# @see #order_groups_and_examples
# @see #order=
# @see #seed=
def order_examples(&block)
@example_ordering_block = block
@order = "custom" unless built_in_orderer?(block)
end
# @private
def example_ordering_block
@example_ordering_block ||= DEFAULT_ORDERING
end
# Sets a strategy by which to order groups.
#
# @example
# RSpec.configure do |config|
# config.order_groups do |groups|
# groups.reverse
# end
# end
#
# @see #order_examples
# @see #order_groups_and_examples
# @see #order=
# @see #seed=
def order_groups(&block)
@group_ordering_block = block
@order = "custom" unless built_in_orderer?(block)
end
# @private
def group_ordering_block
@group_ordering_block ||= DEFAULT_ORDERING
end
# Sets a strategy by which to order groups and examples.
#
# @example
# RSpec.configure do |config|
# config.order_groups_and_examples do |groups_or_examples|
# groups_or_examples.reverse
# end
# end
#
# @see #order_groups
# @see #order_examples
# @see #order=
# @see #seed=
def order_groups_and_examples(&block)
order_groups(&block)
order_examples(&block)
end
# Set Ruby warnings on or off
def warnings= value
$VERBOSE = !!value
end
def warnings
$VERBOSE
end
private
def get_files_to_run(paths)
FlatMap.flat_map(paths) do |path|
path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
File.directory?(path) ? gather_directories(path) : extract_location(path)
end.sort
end
def gather_directories(path)
stripped = "{#{pattern.gsub(/\s*,\s*/, ',')}}"
files = pattern =~ /^#{Regexp.escape path}/ ? Dir[stripped] : Dir["#{path}/#{stripped}"]
files.sort
end
def extract_location(path)
if path =~ /^(.*?)((?:\:\d+)+)$/
path, lines = $1, $2[1..-1].split(":").map{|n| n.to_i}
filter_manager.add_location path, lines
end
path
end
def command
$0.split(File::SEPARATOR).last
end
def value_for(key, default=nil)
@preferred_options.has_key?(key) ? @preferred_options[key] : default
end
def assert_no_example_groups_defined(config_option)
if RSpec.world.example_groups.any?
raise MustBeConfiguredBeforeExampleGroupsError.new(
"RSpec's #{config_option} configuration option must be configured before " +
"any example groups are defined, but you have already defined a group."
)
end
end
def raise_if_rspec_1_is_loaded
if defined?(Spec) && defined?(Spec::VERSION::MAJOR) && Spec::VERSION::MAJOR == 1
raise <<-MESSAGE
#{'*'*80}
You are running rspec-2, but it seems as though rspec-1 has been loaded as
well. This is likely due to a statement like this somewhere in the specs:
require 'spec'
Please locate that statement, remove it, and try again.
#{'*'*80}
MESSAGE
end
end
def output_to_tty?(output=output_stream)
tty? || (output.respond_to?(:tty?) && output.tty?)
end
def built_in_formatter(key)
case key.to_s
when 'd', 'doc', 'documentation', 's', 'n', 'spec', 'nested'
require 'rspec/core/formatters/documentation_formatter'
RSpec::Core::Formatters::DocumentationFormatter
when 'h', 'html'
require 'rspec/core/formatters/html_formatter'
RSpec::Core::Formatters::HtmlFormatter
when 'p', 'progress'
require 'rspec/core/formatters/progress_formatter'
RSpec::Core::Formatters::ProgressFormatter
when 'j', 'json'
require 'rspec/core/formatters/json_formatter'
RSpec::Core::Formatters::JsonFormatter
end
end
def custom_formatter(formatter_ref)
if Class === formatter_ref
formatter_ref
elsif string_const?(formatter_ref)
begin
eval(formatter_ref)
rescue NameError
require path_for(formatter_ref)
eval(formatter_ref)
end
end
end
def string_const?(str)
str.is_a?(String) && /\A[A-Z][a-zA-Z0-9_:]*\z/ =~ str
end
def path_for(const_ref)
underscore_with_fix_for_non_standard_rspec_naming(const_ref)
end
def underscore_with_fix_for_non_standard_rspec_naming(string)
underscore(string).sub(%r{(^|/)r_spec($|/)}, '\\1rspec\\2')
end
# activesupport/lib/active_support/inflector/methods.rb, line 48
def underscore(camel_cased_word)
word = camel_cased_word.to_s.dup
word.gsub!(/::/, '/')
word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
def file_at(path)
FileUtils.mkdir_p(File.dirname(path))
File.new(path, 'w')
end
def order_and_seed_from_seed(value)
order_groups_and_examples(&RANDOM_ORDERING)
@order, @seed = 'rand', value.to_i
[@order, @seed]
end
def set_order_and_seed(hash)
hash[:order], seed = order_and_seed_from_order(hash[:order])
hash[:seed] = seed if seed
end
def order_and_seed_from_order(type)
order, seed = type.to_s.split(':')
@order = order
@seed = seed = seed.to_i if seed
if randomize?
order_groups_and_examples(&RANDOM_ORDERING)
elsif order == 'default'
@order, @seed = nil, nil
order_groups_and_examples(&DEFAULT_ORDERING)
end
return order, seed
end
def built_in_orderer?(block)
[DEFAULT_ORDERING, RANDOM_ORDERING].include?(block)
end
end
end
end
| 1 | 10,345 | Will this obey the seed set on Kernel? | rspec-rspec-core | rb |
@@ -23,16 +23,9 @@ Puppet::Functions.create_function(:add_facts) do
.from_issue_and_stack(Bolt::PAL::Issues::PLAN_OPERATION_NOT_SUPPORTED_WHEN_COMPILING, action: 'add_facts')
end
- inventory = Puppet.lookup(:bolt_inventory) { nil }
-
- unless inventory
- raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
- Puppet::Pops::Issues::TASK_MISSING_BOLT, action: _('add facts')
- )
- end
-
- executor = Puppet.lookup(:bolt_executor) { nil }
- executor&.report_function_call('add_facts')
+ inventory = Puppet.lookup(:bolt_inventory)
+ executor = Puppet.lookup(:bolt_executor)
+ executor.report_function_call('add_facts')
inventory.add_facts(target, facts)
end | 1 | # frozen_string_literal: true
require 'bolt/error'
# Deep merges a hash of facts with the existing facts on a target.
#
# **NOTE:** Not available in apply block
Puppet::Functions.create_function(:add_facts) do
# @param target A target.
# @param facts A hash of fact names to values that may include structured facts.
# @return The target's new facts.
# @example Adding facts to a target
# add_facts($target, { 'os' => { 'family' => 'windows', 'name' => 'windows' } })
dispatch :add_facts do
param 'Target', :target
param 'Hash', :facts
return_type 'Hash[String, Data]'
end
def add_facts(target, facts)
unless Puppet[:tasks]
raise Puppet::ParseErrorWithIssue
.from_issue_and_stack(Bolt::PAL::Issues::PLAN_OPERATION_NOT_SUPPORTED_WHEN_COMPILING, action: 'add_facts')
end
inventory = Puppet.lookup(:bolt_inventory) { nil }
unless inventory
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::TASK_MISSING_BOLT, action: _('add facts')
)
end
executor = Puppet.lookup(:bolt_executor) { nil }
executor&.report_function_call('add_facts')
inventory.add_facts(target, facts)
end
end
| 1 | 11,267 | We shouldn't use the `&.` syntax here, since we expect that `executor` will never be `nil`. For the functions that _can_ be called from apply / without an executor, `&.` is still appropriate. | puppetlabs-bolt | rb |
@@ -68,11 +68,12 @@ public class SurfaceNamer extends NameFormatterDelegator {
public String getNotImplementedString(String feature) {
return "$ NOT IMPLEMENTED: " + feature + " $";
+ //throw new RuntimeException(feature);
}
/** The full path to the source file */
public String getSourceFilePath(String path, String className) {
- return getNotImplementedString("SurfaceNamer.getSourceFilePath");
+ return getNotImplementedString("SurfaceNamer:getSourceFilePath");
}
/** The name of the class that implements a particular proto interface. */ | 1 | /* Copyright 2016 Google Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.codegen.transformer;
import com.google.api.codegen.CollectionConfig;
import com.google.api.codegen.MethodConfig;
import com.google.api.codegen.metacode.InitValueConfig;
import com.google.api.codegen.util.CommonRenderingUtil;
import com.google.api.codegen.util.Name;
import com.google.api.codegen.util.NameFormatter;
import com.google.api.codegen.util.NameFormatterDelegator;
import com.google.api.codegen.util.NamePath;
import com.google.api.codegen.util.SymbolTable;
import com.google.api.codegen.util.TypeNameConverter;
import com.google.api.tools.framework.aspects.documentation.model.DocumentationUtil;
import com.google.api.tools.framework.model.Field;
import com.google.api.tools.framework.model.Interface;
import com.google.api.tools.framework.model.Method;
import com.google.api.tools.framework.model.ProtoElement;
import com.google.api.tools.framework.model.TypeRef;
import java.util.ArrayList;
import java.util.List;
/**
* A SurfaceNamer provides language-specific names for specific components of a view for a surface.
*
* Naming is composed of two steps:
*
* 1. Composing a Name instance with the name pieces
* 2. Formatting the Name for the particular type of identifier needed.
*
* This class delegates step 2 to the provided name formatter, which generally
* would be a language-specific namer.
*/
public class SurfaceNamer extends NameFormatterDelegator {
private ModelTypeFormatter modelTypeFormatter;
private TypeNameConverter typeNameConverter;
public SurfaceNamer(
NameFormatter languageNamer,
ModelTypeFormatter modelTypeFormatter,
TypeNameConverter typeNameConverter) {
super(languageNamer);
this.modelTypeFormatter = modelTypeFormatter;
this.typeNameConverter = typeNameConverter;
}
public ModelTypeFormatter getModelTypeFormatter() {
return modelTypeFormatter;
}
public TypeNameConverter getTypeNameConverter() {
return typeNameConverter;
}
public String getNotImplementedString(String feature) {
return "$ NOT IMPLEMENTED: " + feature + " $";
}
/** The full path to the source file */
public String getSourceFilePath(String path, String className) {
return getNotImplementedString("SurfaceNamer.getSourceFilePath");
}
/** The name of the class that implements a particular proto interface. */
public String getApiWrapperClassName(Interface interfaze) {
return className(Name.upperCamel(interfaze.getSimpleName(), "Api"));
}
/**
* The name of a variable that holds an instance of the class that implements
* a particular proto interface.
*/
public String getApiWrapperVariableName(Interface interfaze) {
return varName(Name.upperCamel(interfaze.getSimpleName(), "Api"));
}
/**
* The name of a variable that holds an instance of the module that contains
* the implementation of a particular proto interface. So far it is used by
* just NodeJS.
*/
public String getApiWrapperModuleName(Interface interfaze) {
return getNotImplementedString("SurfaceNamer.getApiWrapperModuleName");
}
/**
* The name of the settings class for a particular proto interface;
* not used in most languages.
*/
public String getApiSettingsClassName(Interface interfaze) {
return className(Name.upperCamel(interfaze.getSimpleName(), "Settings"));
}
/**
* The name of a variable that holds the settings class for a particular
* proto interface; not used in most languages.
*/
public String getApiSettingsVariableName(Interface interfaze) {
return varName(Name.upperCamel(interfaze.getSimpleName(), "Settings"));
}
/**
* The name of the builder class for the settings class for a particular
* proto interface; not used in most languages.
*/
public String getApiSettingsBuilderVarName(Interface interfaze) {
return varName(Name.upperCamel(interfaze.getSimpleName(), "SettingsBuilder"));
}
/**
* The variable name for the given identifier. If it has formatting config
* (specified by initValueConfig), then its name reflects that.
*/
public String getVariableName(Name identifier, InitValueConfig initValueConfig) {
if (initValueConfig == null || !initValueConfig.hasFormattingConfig()) {
return varName(identifier);
} else {
return varName(Name.from("formatted").join(identifier));
}
}
/** The function name to set the given proto field. */
public String getFieldSetFunctionName(Field field) {
return getFieldSetFunctionName(field.getType(), Name.from(field.getSimpleName()));
}
/** The function name to set a field having the given type and name. */
public String getFieldSetFunctionName(TypeRef type, Name identifier) {
if (type.isMap()) {
return methodName(Name.from("put", "all").join(identifier));
} else if (type.isRepeated()) {
return methodName(Name.from("add", "all").join(identifier));
} else {
return methodName(Name.from("set").join(identifier));
}
}
/** The function name to get the given proto field. */
public String getFieldGetFunctionName(Field field) {
return getFieldGetFunctionName(field.getType(), Name.from(field.getSimpleName()));
}
/** The function name to get a field having the given type and name. */
public String getFieldGetFunctionName(TypeRef type, Name identifier) {
if (type.isRepeated() && !type.isMap()) {
return methodName(Name.from("get").join(identifier).join("list"));
} else {
return methodName(Name.from("get").join(identifier));
}
}
/**
* The function name to get the count of elements in the given field.
*
* @throws IllegalArgumentException if the field is not a repeated field.
*/
public String getFieldCountGetFunctionName(Field field) {
if (field.isRepeated()) {
return methodName(Name.from("get", field.getSimpleName(), "count"));
} else {
throw new IllegalArgumentException(
"Non-repeated field " + field.getSimpleName() + " has no count function.");
}
}
/**
* The function name to get an element by index from the given field.
*
* @throws IllegalArgumentException if the field is not a repeated field.
*/
public String getByIndexGetFunctionName(Field field) {
if (field.isRepeated()) {
return methodName(Name.from("get", field.getSimpleName()));
} else {
throw new IllegalArgumentException(
"Non-repeated field " + field.getSimpleName() + " has no get-by-index function.");
}
}
/**
* The name of a path template constant for the given collection,
* to be held in an API wrapper class.
*/
public String getPathTemplateName(CollectionConfig collectionConfig) {
return inittedConstantName(Name.from(collectionConfig.getEntityName(), "path", "template"));
}
/** The name of a getter function to get a particular path template for the given collection. */
public String getPathTemplateNameGetter(CollectionConfig collectionConfig) {
return methodName(Name.from("get", collectionConfig.getEntityName(), "name", "template"));
}
/** The function name to format the entity for the given collection. */
public String getFormatFunctionName(CollectionConfig collectionConfig) {
return staticFunctionName(Name.from("format", collectionConfig.getEntityName(), "name"));
}
/**
* The function name to parse a variable from the string representing the entity for
* the given collection.
*/
public String getParseFunctionName(String var, CollectionConfig collectionConfig) {
return staticFunctionName(
Name.from("parse", var, "from", collectionConfig.getEntityName(), "name"));
}
/** The entity name for the given collection. */
public String getEntityName(CollectionConfig collectionConfig) {
return varName(Name.from(collectionConfig.getEntityName()));
}
/** The parameter name for the entity for the given collection config. */
public String getEntityNameParamName(CollectionConfig collectionConfig) {
return varName(Name.from(collectionConfig.getEntityName(), "name"));
}
/** The parameter name for the given lower-case field name. */
public String getParamName(String var) {
return varName(Name.from(var));
}
/** The page streaming descriptor name for the given method. */
public String getPageStreamingDescriptorName(Method method) {
return varName(Name.upperCamel(method.getSimpleName(), "PageStreamingDescriptor"));
}
/** The name of the constant to hold the page streaming descriptor for the given method. */
public String getPageStreamingDescriptorConstName(Method method) {
return inittedConstantName(Name.upperCamel(method.getSimpleName()).join("page_str_desc"));
}
/** The name of the constant to hold the bundling descriptor for the given method. */
public String getBundlingDescriptorConstName(Method method) {
return inittedConstantName(Name.upperCamel(method.getSimpleName()).join("bundling_desc"));
}
/** Adds the imports used in the implementation of page streaming descriptors. */
public void addPageStreamingDescriptorImports(ModelTypeTable typeTable) {
// do nothing
}
/** Adds the imports used in the implementation of bundling descriptors. */
public void addBundlingDescriptorImports(ModelTypeTable typeTable) {
// do nothing
}
/** Adds the imports used for page streaming call settings. */
public void addPageStreamingCallSettingsImports(ModelTypeTable typeTable) {
// do nothing
}
/** Adds the imports used for bundling call settings. */
public void addBundlingCallSettingsImports(ModelTypeTable typeTable) {
// do nothing
}
/** The key to use in a dictionary for the given method. */
public String getMethodKey(Method method) {
return keyName(Name.upperCamel(method.getSimpleName()));
}
/** The path to the client config for the given interface. */
public String getClientConfigPath(Interface service) {
return getNotImplementedString("SurfaceNamer.getClientConfigPath");
}
/**
* The type name of the Grpc client class.
* This needs to match what Grpc generates for the particular language.
*/
public String getGrpcClientTypeName(Interface service) {
NamePath namePath = typeNameConverter.getNamePath(modelTypeFormatter.getFullNameFor(service));
String className = className(Name.upperCamel(namePath.getHead(), "Client"));
return qualifiedName(namePath.withHead(className));
}
/**
* The type name of the Grpc container class.
* This needs to match what Grpc generates for the particular language.
*/
public String getGrpcContainerTypeName(Interface service) {
NamePath namePath = typeNameConverter.getNamePath(modelTypeFormatter.getFullNameFor(service));
String className = className(Name.upperCamel(namePath.getHead(), "Grpc"));
return qualifiedName(namePath.withHead(className));
}
/**
* The type name of the Grpc service class
* This needs to match what Grpc generates for the particular language.
*/
public String getGrpcServiceClassName(Interface service) {
NamePath namePath = typeNameConverter.getNamePath(modelTypeFormatter.getFullNameFor(service));
String grpcContainerName = className(Name.upperCamel(namePath.getHead(), "Grpc"));
String serviceClassName = className(Name.upperCamel(service.getSimpleName()));
return qualifiedName(namePath.withHead(grpcContainerName).append(serviceClassName));
}
/**
* The type name of the method constant in the Grpc container class.
* This needs to match what Grpc generates for the particular language.
*/
public String getGrpcMethodConstant(Method method) {
return inittedConstantName(Name.from("method").join(Name.upperCamel(method.getSimpleName())));
}
/** The name of the surface method which can call the given API method. */
public String getApiMethodName(Method method) {
return methodName(Name.upperCamel(method.getSimpleName()));
}
/**
* The name of a variable to hold a value for the given proto message field
* (such as a flattened parameter).
*/
public String getVariableName(Field field) {
return varName(Name.from(field.getSimpleName()));
}
/**
* Returns true if the request object param type for the given field should be imported.
*/
public boolean shouldImportRequestObjectParamType(Field field) {
return true;
}
/**
* Returns true if the request object param element type for the given field should be imported.
*/
public boolean shouldImportRequestObjectParamElementType(Field field) {
return true;
}
/** Converts the given text to doc lines in the format of the current language. */
public List<String> getDocLines(String text) {
return CommonRenderingUtil.getDocLines(text);
}
/** Provides the doc lines for the given proto element in the current language. */
public List<String> getDocLines(ProtoElement element) {
return getDocLines(DocumentationUtil.getDescription(element));
}
/** The doc lines that declare what exception(s) are thrown for an API method. */
public List<String> getThrowsDocLines() {
return new ArrayList<>();
}
/** The public access modifier for the current language. */
public String getPublicAccessModifier() {
return "public";
}
/** The private access modifier for the current language. */
public String getPrivateAccessModifier() {
return "private";
}
/**
* The name used in Grpc for the given API method.
* This needs to match what Grpc generates.
*/
public String getGrpcMethodName(Method method) {
// This might seem silly, but it makes clear what we're dealing with (upper camel).
// This is language-independent because of gRPC conventions.
return Name.upperCamel(method.getSimpleName()).toUpperCamel();
}
/** The type name for retry settings. */
public String getRetrySettingsTypeName() {
return getNotImplementedString("SurfaceNamer.getRetrySettingsClassName");
}
/** The type name for an optional array argument; not used in most languages. */
public String getOptionalArrayTypeName() {
return getNotImplementedString("SurfaceNamer.getOptionalArrayTypeName");
}
/** The return type name in a dynamic language for the given method. */
public String getDynamicLangReturnTypeName(Method method, MethodConfig methodConfig) {
return getNotImplementedString("SurfaceNamer.getDynamicReturnTypeName");
}
/** The return type name in a static language for the given method. */
public String getStaticLangReturnTypeName(Method method, MethodConfig methodConfig) {
return getNotImplementedString("SurfaceNamer.getStaticReturnTypeName");
}
/** The name of the paged callable variant of the given method. */
public String getPagedCallableMethodName(Method method) {
return methodName(Name.upperCamel(method.getSimpleName(), "PagedCallable"));
}
/** The name of the callable for the paged callable variant of the given method. */
public String getPagedCallableName(Method method) {
return varName(Name.upperCamel(method.getSimpleName(), "PagedCallable"));
}
/** The name of the plain callable variant of the given method. */
public String getCallableMethodName(Method method) {
return methodName(Name.upperCamel(method.getSimpleName(), "Callable"));
}
/** The name of the plain callable for the given method. */
public String getCallableName(Method method) {
return varName(Name.upperCamel(method.getSimpleName(), "Callable"));
}
/** The name of the settings member name for the given method. */
public String getSettingsMemberName(Method method) {
return methodName(Name.upperCamel(method.getSimpleName(), "Settings"));
}
/** The getter function name for the settings for the given method. */
public String getSettingsFunctionName(Method method) {
return getSettingsMemberName(method);
}
/**
* The generic-aware response type name for the given type.
* For example, in Java, this will be the type used for ListenableFuture<...>.
*/
public String getGenericAwareResponseTypeName(TypeRef outputType) {
return getNotImplementedString("SurfaceNamer.getGenericAwareResponseType");
}
/**
* The function name to get the given proto field as a list.
*
* @throws IllegalArgumentException if the field is not a repeated field.
*/
public String getGetResourceListCallName(Field resourcesField) {
if (resourcesField.isRepeated()) {
return methodName(Name.from("get", resourcesField.getSimpleName(), "list"));
} else {
throw new IllegalArgumentException(
"Non-repeated field "
+ resourcesField.getSimpleName()
+ " cannot be accessed as a list.");
}
}
/**
* Computes the nickname of the response type name for the given resource type, saves it in the
* given type table, and returns it.
*/
public String getAndSavePagedResponseTypeName(
ModelTypeTable typeTable, TypeRef... parameterizedTypes) {
return getNotImplementedString("SurfaceNamer.getAndSavePagedResponseTypeName");
}
/**
* The test case name for the given method.
*/
public String getTestCaseName(SymbolTable symbolTable, Method method) {
Name testCaseName = symbolTable.getNewSymbol(Name.upperCamel(method.getSimpleName(), "Test"));
return methodName(testCaseName);
}
/** The unit test class name for the given API service. */
public String getUnitTestClassName(Interface service) {
return className(Name.upperCamel(service.getSimpleName(), "Test"));
}
/** The smoke test class name for the given API service. */
public String getSmokeTestClassName(Interface service) {
return className(Name.upperCamel(service.getSimpleName(), "Smoke", "Test"));
}
/** The class name of the mock gRPC service for the given API service. */
public String getMockServiceClassName(Interface service) {
return className(Name.upperCamel("Mock", service.getSimpleName()));
}
/** The class name of a variable to hold the mock gRPC service for the given API service. */
public String getMockServiceVarName(Interface service) {
return varName(Name.upperCamel("Mock", service.getSimpleName()));
}
/** The class name of the mock gRPC service implementation for the given API service. */
public String getMockGrpcServiceImplName(Interface service) {
return className(Name.upperCamel("Mock", service.getSimpleName(), "Impl"));
}
/** The file name for an API service. */
public String getServiceFileName(Interface service, String packageName) {
return getNotImplementedString("SurfaceNamer.getApiName");
}
/**
* The fully qualified class name of a an API service.
* TODO: Support the general pattern of package + class name in NameFormatter.
*/
public String getFullyQualifiedApiWrapperClassName(Interface interfaze, String packageName) {
return getNotImplementedString("SurfaceNamer.getFullyQualifiedApiWrapperClassName");
}
/** The name of the variable that will hold the stub for a service. */
public String getStubName(Interface service) {
return varName(Name.upperCamel(service.getSimpleName(), "Stub"));
}
/** The name of the function that will create a stub. */
public String getCreateStubFunctionName(Interface service) {
return varName(Name.upperCamel("Create", service.getSimpleName(), "Stub", "Function"));
}
/** The name of the array which will hold the methods for a given stub. */
public String getStubMethodsArrayName(Interface service) {
return varName(Name.upperCamel(service.getSimpleName(), "Stub", "Methods"));
}
/** The name of the import for a specific grpcClient */
public String getGrpcClientImportName(Interface service) {
return getNotImplementedString("SurfaceNamer.getGrpcClientImportName");
}
/** The fully qualified type name for the stub of a service. */
public String getFullyQualifiedStubType(Interface service) {
return getNotImplementedString("SurfaceNamer.getFullyQualifiedStubType");
}
/** The name of the variable to hold the grpc client of a service. */
public String getGrpcClientVariableName(Interface service) {
return varName(Name.upperCamel(service.getSimpleName(), "Client"));
}
/** The qualified namespace of a service. */
public String getNamespace(Interface service) {
NamePath namePath = typeNameConverter.getNamePath(modelTypeFormatter.getFullNameFor(service));
return qualifiedName(namePath.withoutHead());
}
public String getProtoFileImportFromService(Interface service) {
return getNotImplementedString("SurfaceNamer.getProtoFileImportFromService");
}
}
| 1 | 17,742 | Why the switch from period to colon? | googleapis-gapic-generator | java |
@@ -314,8 +314,9 @@ func environmentConfig() Config {
imageCleanupDisabled := utils.ParseBool(os.Getenv("ECS_DISABLE_IMAGE_CLEANUP"), false)
minimumImageDeletionAge := parseEnvVariableDuration("ECS_IMAGE_MINIMUM_CLEANUP_AGE")
imageCleanupInterval := parseEnvVariableDuration("ECS_IMAGE_CLEANUP_INTERVAL")
- numImagesToDeletePerCycle, err := strconv.Atoi(os.Getenv("ECS_NUM_IMAGES_DELETE_PER_CYCLE"))
- if err != nil {
+ numImagesToDeletePerCycleEnvVal := os.Getenv("ECS_NUM_IMAGES_DELETE_PER_CYCLE")
+ numImagesToDeletePerCycle, err := strconv.Atoi(numImagesToDeletePerCycleEnvVal)
+ if numImagesToDeletePerCycleEnvVal != "" && err != nil {
seelog.Warnf("Invalid format for \"ECS_NUM_IMAGES_DELETE_PER_CYCLE\", expected an integer. err %v", err)
}
| 1 | // Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package config
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/aws/amazon-ecs-agent/agent/ec2"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/cihub/seelog"
)
const (
// http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker
DockerReservedPort = 2375
DockerReservedSSLPort = 2376
SSHPort = 22
// AgentIntrospectionPort is used to serve the metadata about the agent and to query the tasks being managed by the agent.
AgentIntrospectionPort = 51678
// AgentCredentialsPort is used to serve the credentials for tasks.
AgentCredentialsPort = 51679
// DefaultClusterName is the name of the default cluster.
DefaultClusterName = "default"
// DefaultTaskCleanupWaitDuration specifies the default value for task cleanup duration. It is used to
// clean up task's containers.
DefaultTaskCleanupWaitDuration = 3 * time.Hour
// DefaultDockerStopTimeout specifies the value for container stop timeout duration
DefaultDockerStopTimeout = 30 * time.Second
// DefaultImageCleanupTimeInterval specifies the default value for image cleanup duration. It is used to
// remove the images pulled by agent.
DefaultImageCleanupTimeInterval = 30 * time.Minute
// DefaultNumImagesToDeletePerCycle specifies the default number of images to delete when agent performs
// image cleanup.
DefaultNumImagesToDeletePerCycle = 5
//DefaultImageDeletionAge specifies the default value for minimum amount of elapsed time after an image
// has been pulled before it can be deleted.
DefaultImageDeletionAge = 1 * time.Hour
// minimumTaskCleanupWaitDuration specifies the minimum duration to wait before cleaning up
// a task's container. This is used to enforce sane values for the config.TaskCleanupWaitDuration field.
minimumTaskCleanupWaitDuration = 1 * time.Minute
// minimumDockerStopTimeout specifies the minimum value for docker StopContainer API
minimumDockerStopTimeout = 1 * time.Second
// minimumImageCleanupInterval specifies the minimum time for agent to wait before performing
// image cleanup.
minimumImageCleanupInterval = 10 * time.Minute
// minimumNumImagesToDeletePerCycle specifies the minimum number of images that to be deleted when
// performing image cleanup.
minimumNumImagesToDeletePerCycle = 1
// defaultAuditLogFile specifies the default audit log filename
defaultCredentialsAuditLogFile = "/log/audit.log"
)
// Merge merges two config files, preferring the ones on the left. Any nil or
// zero values present in the left that are not present in the right will be
// overridden
func (lhs *Config) Merge(rhs Config) *Config {
left := reflect.ValueOf(lhs).Elem()
right := reflect.ValueOf(&rhs).Elem()
for i := 0; i < left.NumField(); i++ {
leftField := left.Field(i)
if utils.ZeroOrNil(leftField.Interface()) {
leftField.Set(reflect.ValueOf(right.Field(i).Interface()))
}
}
return lhs //make it chainable
}
// complete returns true if all fields of the config are populated / nonzero
func (cfg *Config) complete() bool {
cfgElem := reflect.ValueOf(cfg).Elem()
for i := 0; i < cfgElem.NumField(); i++ {
if utils.ZeroOrNil(cfgElem.Field(i).Interface()) {
return false
}
}
return true
}
// checkMissingAndDeprecated checks all zero-valued fields for tags of the form
// missing:STRING and acts based on that string. Current options are: fatal,
// warn. Fatal will result in an error being returned, warn will result in a
// warning that the field is missing being logged.
func (cfg *Config) checkMissingAndDepreciated() error {
cfgElem := reflect.ValueOf(cfg).Elem()
cfgStructField := reflect.Indirect(reflect.ValueOf(cfg)).Type()
fatalFields := []string{}
for i := 0; i < cfgElem.NumField(); i++ {
cfgField := cfgElem.Field(i)
if utils.ZeroOrNil(cfgField.Interface()) {
missingTag := cfgStructField.Field(i).Tag.Get("missing")
if len(missingTag) == 0 {
continue
}
switch missingTag {
case "warn":
seelog.Warnf("Configuration key not set, key: %v", cfgStructField.Field(i).Name)
case "fatal":
seelog.Criticalf("Configuration key not set, key: %v", cfgStructField.Field(i).Name)
fatalFields = append(fatalFields, cfgStructField.Field(i).Name)
default:
seelog.Warnf("Unexpected `missing` tag value, tag %v", missingTag)
}
} else {
// present
deprecatedTag := cfgStructField.Field(i).Tag.Get("deprecated")
if len(deprecatedTag) == 0 {
continue
}
seelog.Warnf("Use of deprecated configuration key, key: %v message: %v", cfgStructField.Field(i).Name, deprecatedTag)
}
}
if len(fatalFields) > 0 {
return errors.New("Missing required fields: " + strings.Join(fatalFields, ", "))
}
return nil
}
// trimWhitespace trims whitespace from all string config values with the
// `trim` tag
func (cfg *Config) trimWhitespace() {
cfgElem := reflect.ValueOf(cfg).Elem()
cfgStructField := reflect.Indirect(reflect.ValueOf(cfg)).Type()
for i := 0; i < cfgElem.NumField(); i++ {
cfgField := cfgElem.Field(i)
if !cfgField.CanInterface() {
continue
}
trimTag := cfgStructField.Field(i).Tag.Get("trim")
if len(trimTag) == 0 {
continue
}
if cfgField.Kind() != reflect.String {
seelog.Warnf("Cannot trim non-string field type %v index %v", cfgField.Kind().String(), i)
continue
}
str := cfgField.Interface().(string)
cfgField.SetString(strings.TrimSpace(str))
}
}
func DefaultConfig() Config {
return Config{
DockerEndpoint: "unix:///var/run/docker.sock",
ReservedPorts: []uint16{SSHPort, DockerReservedPort, DockerReservedSSLPort, AgentIntrospectionPort, AgentCredentialsPort},
ReservedPortsUDP: []uint16{},
DataDir: "/data/",
DisableMetrics: false,
ReservedMemory: 0,
AvailableLoggingDrivers: []dockerclient.LoggingDriver{dockerclient.JsonFileDriver},
TaskCleanupWaitDuration: DefaultTaskCleanupWaitDuration,
DockerStopTimeout: DefaultDockerStopTimeout,
CredentialsAuditLogFile: defaultCredentialsAuditLogFile,
CredentialsAuditLogDisabled: false,
ImageCleanupDisabled: false,
MinimumImageDeletionAge: DefaultImageDeletionAge,
ImageCleanupInterval: DefaultImageCleanupTimeInterval,
NumImagesToDeletePerCycle: DefaultNumImagesToDeletePerCycle,
}
}
func fileConfig() Config {
config_file := utils.DefaultIfBlank(os.Getenv("ECS_AGENT_CONFIG_FILE_PATH"), "/etc/ecs_container_agent/config.json")
file, err := os.Open(config_file)
if err != nil {
return Config{}
}
data, err := ioutil.ReadAll(file)
if err != nil {
seelog.Errorf("Unable to read config file, err %v", err)
return Config{}
}
if strings.TrimSpace(string(data)) == "" {
// empty file, not an error
return Config{}
}
config := Config{}
err = json.Unmarshal(data, &config)
if err != nil {
seelog.Errorf("Error reading config json data, err %v", err)
}
// Handle any deprecated keys correctly here
if utils.ZeroOrNil(config.Cluster) && !utils.ZeroOrNil(config.ClusterArn) {
config.Cluster = config.ClusterArn
}
return config
}
// environmentConfig reads the given configs from the environment and attempts
// to convert them to the given type
func environmentConfig() Config {
endpoint := os.Getenv("ECS_BACKEND_HOST")
clusterRef := os.Getenv("ECS_CLUSTER")
awsRegion := os.Getenv("AWS_DEFAULT_REGION")
dockerEndpoint := os.Getenv("DOCKER_HOST")
engineAuthType := os.Getenv("ECS_ENGINE_AUTH_TYPE")
engineAuthData := os.Getenv("ECS_ENGINE_AUTH_DATA")
var checkpoint bool
dataDir := os.Getenv("ECS_DATADIR")
if dataDir != "" {
// if we have a directory to checkpoint to, default it to be on
checkpoint = utils.ParseBool(os.Getenv("ECS_CHECKPOINT"), true)
} else {
// if the directory is not set, default to checkpointing off for
// backwards compatibility
checkpoint = utils.ParseBool(os.Getenv("ECS_CHECKPOINT"), false)
}
// Format: json array, e.g. [1,2,3]
reservedPortEnv := os.Getenv("ECS_RESERVED_PORTS")
portDecoder := json.NewDecoder(strings.NewReader(reservedPortEnv))
var reservedPorts []uint16
err := portDecoder.Decode(&reservedPorts)
// EOF means the string was blank as opposed to UnexepctedEof which means an
// invalid parse
// Blank is not a warning; we have sane defaults
if err != io.EOF && err != nil {
seelog.Warnf("Invalid format for \"ECS_RESERVED_PORTS\" environment variable; expected a JSON array like [1,2,3]. err %v", err)
}
reservedPortUDPEnv := os.Getenv("ECS_RESERVED_PORTS_UDP")
portDecoderUDP := json.NewDecoder(strings.NewReader(reservedPortUDPEnv))
var reservedPortsUDP []uint16
err = portDecoderUDP.Decode(&reservedPortsUDP)
// EOF means the string was blank as opposed to UnexepctedEof which means an
// invalid parse
// Blank is not a warning; we have sane defaults
if err != io.EOF && err != nil {
seelog.Warnf("Invalid format for \"ECS_RESERVED_PORTS_UDP\" environment variable; expected a JSON array like [1,2,3]. err %v", err)
}
updateDownloadDir := os.Getenv("ECS_UPDATE_DOWNLOAD_DIR")
updatesEnabled := utils.ParseBool(os.Getenv("ECS_UPDATES_ENABLED"), false)
disableMetrics := utils.ParseBool(os.Getenv("ECS_DISABLE_METRICS"), false)
reservedMemory := parseEnvVariableUint16("ECS_RESERVED_MEMORY")
var dockerStopTimeout time.Duration
parsedStopTimeout := parseEnvVariableDuration("ECS_CONTAINER_STOP_TIMEOUT")
if parsedStopTimeout >= minimumDockerStopTimeout {
dockerStopTimeout = parsedStopTimeout
} else if parsedStopTimeout != 0 {
seelog.Warnf("Discarded invalid value for docker stop timeout, parsed as: %v", parsedStopTimeout)
}
taskCleanupWaitDuration := parseEnvVariableDuration("ECS_ENGINE_TASK_CLEANUP_WAIT_DURATION")
availableLoggingDriversEnv := os.Getenv("ECS_AVAILABLE_LOGGING_DRIVERS")
loggingDriverDecoder := json.NewDecoder(strings.NewReader(availableLoggingDriversEnv))
var availableLoggingDrivers []dockerclient.LoggingDriver
err = loggingDriverDecoder.Decode(&availableLoggingDrivers)
// EOF means the string was blank as opposed to UnexepctedEof which means an
// invalid parse
// Blank is not a warning; we have sane defaults
if err != io.EOF && err != nil {
seelog.Warnf("Invalid format for \"ECS_AVAILABLE_LOGGING_DRIVERS\" environment variable; expected a JSON array like [\"json-file\",\"syslog\"]. err %v", err)
}
privilegedDisabled := utils.ParseBool(os.Getenv("ECS_DISABLE_PRIVILEGED"), false)
seLinuxCapable := utils.ParseBool(os.Getenv("ECS_SELINUX_CAPABLE"), false)
appArmorCapable := utils.ParseBool(os.Getenv("ECS_APPARMOR_CAPABLE"), false)
taskIAMRoleEnabled := utils.ParseBool(os.Getenv("ECS_ENABLE_TASK_IAM_ROLE"), false)
taskIAMRoleEnabledForNetworkHost := utils.ParseBool(os.Getenv("ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST"), false)
credentialsAuditLogFile := os.Getenv("ECS_AUDIT_LOGFILE")
credentialsAuditLogDisabled := utils.ParseBool(os.Getenv("ECS_AUDIT_LOGFILE_DISABLED"), false)
imageCleanupDisabled := utils.ParseBool(os.Getenv("ECS_DISABLE_IMAGE_CLEANUP"), false)
minimumImageDeletionAge := parseEnvVariableDuration("ECS_IMAGE_MINIMUM_CLEANUP_AGE")
imageCleanupInterval := parseEnvVariableDuration("ECS_IMAGE_CLEANUP_INTERVAL")
numImagesToDeletePerCycle, err := strconv.Atoi(os.Getenv("ECS_NUM_IMAGES_DELETE_PER_CYCLE"))
if err != nil {
seelog.Warnf("Invalid format for \"ECS_NUM_IMAGES_DELETE_PER_CYCLE\", expected an integer. err %v", err)
}
return Config{
Cluster: clusterRef,
APIEndpoint: endpoint,
AWSRegion: awsRegion,
DockerEndpoint: dockerEndpoint,
ReservedPorts: reservedPorts,
ReservedPortsUDP: reservedPortsUDP,
DataDir: dataDir,
Checkpoint: checkpoint,
EngineAuthType: engineAuthType,
EngineAuthData: NewSensitiveRawMessage([]byte(engineAuthData)),
UpdatesEnabled: updatesEnabled,
UpdateDownloadDir: updateDownloadDir,
DisableMetrics: disableMetrics,
ReservedMemory: reservedMemory,
AvailableLoggingDrivers: availableLoggingDrivers,
PrivilegedDisabled: privilegedDisabled,
SELinuxCapable: seLinuxCapable,
AppArmorCapable: appArmorCapable,
TaskCleanupWaitDuration: taskCleanupWaitDuration,
TaskIAMRoleEnabled: taskIAMRoleEnabled,
DockerStopTimeout: dockerStopTimeout,
CredentialsAuditLogFile: credentialsAuditLogFile,
CredentialsAuditLogDisabled: credentialsAuditLogDisabled,
TaskIAMRoleEnabledForNetworkHost: taskIAMRoleEnabledForNetworkHost,
ImageCleanupDisabled: imageCleanupDisabled,
MinimumImageDeletionAge: minimumImageDeletionAge,
ImageCleanupInterval: imageCleanupInterval,
NumImagesToDeletePerCycle: numImagesToDeletePerCycle,
}
}
func parseEnvVariableUint16(envVar string) uint16 {
envVal := os.Getenv(envVar)
var var16 uint16
if envVal != "" {
var64, err := strconv.ParseUint(envVal, 10, 16)
if err != nil {
seelog.Warnf("Invalid format for \""+envVar+"\" environment variable; expected unsigned integer. err %v", err)
} else {
var16 = uint16(var64)
}
}
return var16
}
func parseEnvVariableDuration(envVar string) time.Duration {
var duration time.Duration
envVal := os.Getenv(envVar)
if envVal == "" {
seelog.Debugf("Environment variable empty: %v", envVar)
} else {
var err error
duration, err = time.ParseDuration(envVal)
if err != nil {
seelog.Warnf("Could not parse duration value: %v for Environment Variable %v : %v", envVal, envVar, err)
}
}
return duration
}
func ec2MetadataConfig(ec2client ec2.EC2MetadataClient) Config {
iid, err := ec2client.InstanceIdentityDocument()
if err != nil {
seelog.Criticalf("Unable to communicate with EC2 Metadata service to infer region: %v", err.Error())
return Config{}
}
return Config{AWSRegion: iid.Region}
}
// NewConfig returns a config struct created by merging environment variables,
// a config file, and EC2 Metadata info.
// The 'config' struct it returns can be used, even if an error is returned. An
// error is returned, however, if the config is incomplete in some way that is
// considered fatal.
func NewConfig(ec2client ec2.EC2MetadataClient) (config *Config, err error) {
ctmp := environmentConfig() //Environment overrides all else
config = &ctmp
defer func() {
config.trimWhitespace()
config.Merge(DefaultConfig())
err = config.validateAndOverrideBounds()
}()
if config.complete() {
// No need to do file / network IO
return config, nil
}
config.Merge(fileConfig())
if config.AWSRegion == "" {
// Get it from metadata only if we need to (network io)
config.Merge(ec2MetadataConfig(ec2client))
}
return config, err
}
// validateAndOverrideBounds performs validation over members of the Config struct
// and check the value against the minimum required value.
func (config *Config) validateAndOverrideBounds() error {
err := config.checkMissingAndDepreciated()
if err != nil {
return err
}
if config.DockerStopTimeout < minimumDockerStopTimeout {
return fmt.Errorf("Invalid negative DockerStopTimeout: %v", config.DockerStopTimeout.String())
}
var badDrivers []string
for _, driver := range config.AvailableLoggingDrivers {
_, ok := dockerclient.LoggingDriverMinimumVersion[driver]
if !ok {
badDrivers = append(badDrivers, string(driver))
}
}
if len(badDrivers) > 0 {
return errors.New("Invalid logging drivers: " + strings.Join(badDrivers, ", "))
}
// If a value has been set for taskCleanupWaitDuration and the value is less than the minimum allowed cleanup duration,
// print a warning and override it
if config.TaskCleanupWaitDuration < minimumTaskCleanupWaitDuration {
seelog.Warnf("Invalid value for image cleanup duration, will be overridden with the default value: %s. Parsed value: %v, minimum value: %v.", DefaultTaskCleanupWaitDuration.String(), config.TaskCleanupWaitDuration, minimumTaskCleanupWaitDuration)
config.TaskCleanupWaitDuration = DefaultTaskCleanupWaitDuration
}
if config.ImageCleanupInterval < minimumImageCleanupInterval {
seelog.Warnf("Invalid value for image cleanup duration, will be overridden with the default value: %s. Parsed value: %v, minimum value: %v.", DefaultImageCleanupTimeInterval.String(), config.ImageCleanupInterval, minimumImageCleanupInterval)
config.ImageCleanupInterval = DefaultImageCleanupTimeInterval
}
if config.NumImagesToDeletePerCycle < minimumNumImagesToDeletePerCycle {
seelog.Warnf("Invalid value for number of images to delete for image cleanup, will be overriden with the default value: %d. Parsed value: %d, minimum value: %d.", DefaultImageDeletionAge, config.NumImagesToDeletePerCycle, minimumNumImagesToDeletePerCycle)
config.NumImagesToDeletePerCycle = DefaultNumImagesToDeletePerCycle
}
return nil
}
// String returns a lossy string representation of the config suitable for human readable display.
// Consequently, it *should not* return any sensitive information.
func (config *Config) String() string {
return fmt.Sprintf("Cluster: %v, Region: %v, DataDir: %v, Checkpoint: %v, AuthType: %v, UpdatesEnabled: %v, DisableMetrics: %v, ReservedMem: %v, TaskCleanupWaitDuration: %v, DockerStopTimeout: %v", config.Cluster, config.AWSRegion, config.DataDir, config.Checkpoint, config.EngineAuthType, config.UpdatesEnabled, config.DisableMetrics, config.ReservedMemory, config.TaskCleanupWaitDuration, config.DockerStopTimeout)
}
| 1 | 14,408 | Can you just fix the warning instead? It's actually important for this to have a default of `""` as the subsequent merges with `DefaultConfig()` and `fileConfig()` need to work. If you make this not `""`, you break the assumptions of `Merge()`. | aws-amazon-ecs-agent | go |
@@ -23,5 +23,15 @@ namespace Nethermind.Baseline.Config
{
[ConfigItem(Description = "If 'true' then the Baseline Module is enabled via JSON RPC", DefaultValue = "false")]
bool Enabled { get; }
+
+ bool BaselineTreeDbCacheIndexAndFilterBlocks { get; set; }
+ ulong BaselineTreeDbBlockCacheSize { get; set; }
+ ulong BaselineTreeDbWriteBufferSize { get; set; }
+ uint BaselineTreeDbWriteBufferNumber { get; set; }
+
+ bool BaselineTreeMetadataDbCacheIndexAndFilterBlocks { get; set; }
+ ulong BaselineTreeMetadataDbBlockCacheSize { get; set; }
+ ulong BaselineTreeMetadataDbWriteBufferSize { get; set; }
+ uint BaselineTreeMetadataDbWriteBufferNumber { get; set; }
}
-}
+} | 1 | // Copyright (c) 2018 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind 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 the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using Nethermind.Config;
namespace Nethermind.Baseline.Config
{
[ConfigCategory(Description = "Configuration of the Baseline Protocol integration with Nethermind")]
public interface IBaselineConfig : IConfig
{
[ConfigItem(Description = "If 'true' then the Baseline Module is enabled via JSON RPC", DefaultValue = "false")]
bool Enabled { get; }
}
} | 1 | 24,739 | let us not add this | NethermindEth-nethermind | .cs |
@@ -41,6 +41,13 @@ type Cgroup struct {
// Rootless tells if rootless cgroups should be used.
Rootless bool
+
+ // The host UID that should own the cgroup, or nil to accept
+ // the default ownership. This should only be set when the
+ // cgroupfs is to be mounted read/write.
+ // Not all cgroup manager implementations support changing
+ // the ownership.
+ OwnerUID *int `json:"owner_uid,omitempty"`
}
type Resources struct { | 1 | package configs
import (
systemdDbus "github.com/coreos/go-systemd/v22/dbus"
"github.com/opencontainers/runc/libcontainer/devices"
)
type FreezerState string
const (
Undefined FreezerState = ""
Frozen FreezerState = "FROZEN"
Thawed FreezerState = "THAWED"
)
// Cgroup holds properties of a cgroup on Linux.
type Cgroup struct {
// Name specifies the name of the cgroup
Name string `json:"name,omitempty"`
// Parent specifies the name of parent of cgroup or slice
Parent string `json:"parent,omitempty"`
// Path specifies the path to cgroups that are created and/or joined by the container.
// The path is assumed to be relative to the host system cgroup mountpoint.
Path string `json:"path"`
// ScopePrefix describes prefix for the scope name
ScopePrefix string `json:"scope_prefix"`
// Resources contains various cgroups settings to apply
*Resources
// Systemd tells if systemd should be used to manage cgroups.
Systemd bool
// SystemdProps are any additional properties for systemd,
// derived from org.systemd.property.xxx annotations.
// Ignored unless systemd is used for managing cgroups.
SystemdProps []systemdDbus.Property `json:"-"`
// Rootless tells if rootless cgroups should be used.
Rootless bool
}
type Resources struct {
// Devices is the set of access rules for devices in the container.
Devices []*devices.Rule `json:"devices"`
// Memory limit (in bytes)
Memory int64 `json:"memory"`
// Memory reservation or soft_limit (in bytes)
MemoryReservation int64 `json:"memory_reservation"`
// Total memory usage (memory + swap); set `-1` to enable unlimited swap
MemorySwap int64 `json:"memory_swap"`
// CPU shares (relative weight vs. other containers)
CpuShares uint64 `json:"cpu_shares"`
// CPU hardcap limit (in usecs). Allowed cpu time in a given period.
CpuQuota int64 `json:"cpu_quota"`
// CPU period to be used for hardcapping (in usecs). 0 to use system default.
CpuPeriod uint64 `json:"cpu_period"`
// How many time CPU will use in realtime scheduling (in usecs).
CpuRtRuntime int64 `json:"cpu_rt_quota"`
// CPU period to be used for realtime scheduling (in usecs).
CpuRtPeriod uint64 `json:"cpu_rt_period"`
// CPU to use
CpusetCpus string `json:"cpuset_cpus"`
// MEM to use
CpusetMems string `json:"cpuset_mems"`
// Process limit; set <= `0' to disable limit.
PidsLimit int64 `json:"pids_limit"`
// Specifies per cgroup weight, range is from 10 to 1000.
BlkioWeight uint16 `json:"blkio_weight"`
// Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, range is from 10 to 1000, cfq scheduler only
BlkioLeafWeight uint16 `json:"blkio_leaf_weight"`
// Weight per cgroup per device, can override BlkioWeight.
BlkioWeightDevice []*WeightDevice `json:"blkio_weight_device"`
// IO read rate limit per cgroup per device, bytes per second.
BlkioThrottleReadBpsDevice []*ThrottleDevice `json:"blkio_throttle_read_bps_device"`
// IO write rate limit per cgroup per device, bytes per second.
BlkioThrottleWriteBpsDevice []*ThrottleDevice `json:"blkio_throttle_write_bps_device"`
// IO read rate limit per cgroup per device, IO per second.
BlkioThrottleReadIOPSDevice []*ThrottleDevice `json:"blkio_throttle_read_iops_device"`
// IO write rate limit per cgroup per device, IO per second.
BlkioThrottleWriteIOPSDevice []*ThrottleDevice `json:"blkio_throttle_write_iops_device"`
// set the freeze value for the process
Freezer FreezerState `json:"freezer"`
// Hugetlb limit (in bytes)
HugetlbLimit []*HugepageLimit `json:"hugetlb_limit"`
// Whether to disable OOM Killer
OomKillDisable bool `json:"oom_kill_disable"`
// Tuning swappiness behaviour per cgroup
MemorySwappiness *uint64 `json:"memory_swappiness"`
// Set priority of network traffic for container
NetPrioIfpriomap []*IfPrioMap `json:"net_prio_ifpriomap"`
// Set class identifier for container's network packets
NetClsClassid uint32 `json:"net_cls_classid_u"`
// Rdma resource restriction configuration
Rdma map[string]LinuxRdma `json:"rdma"`
// Used on cgroups v2:
// CpuWeight sets a proportional bandwidth limit.
CpuWeight uint64 `json:"cpu_weight"`
// Unified is cgroupv2-only key-value map.
Unified map[string]string `json:"unified"`
// SkipDevices allows to skip configuring device permissions.
// Used by e.g. kubelet while creating a parent cgroup (kubepods)
// common for many containers, and by runc update.
//
// NOTE it is impossible to start a container which has this flag set.
SkipDevices bool `json:"-"`
// SkipFreezeOnSet is a flag for cgroup manager to skip the cgroup
// freeze when setting resources. Only applicable to systemd legacy
// (i.e. cgroup v1) manager (which uses freeze by default to avoid
// spurious permission errors caused by systemd inability to update
// device rules in a non-disruptive manner).
//
// If not set, a few methods (such as looking into cgroup's
// devices.list and querying the systemd unit properties) are used
// during Set() to figure out whether the freeze is required. Those
// methods may be relatively slow, thus this flag.
SkipFreezeOnSet bool `json:"-"`
}
| 1 | 24,048 | Is there a need for group as well? crun sets both. | opencontainers-runc | go |
@@ -62,9 +62,12 @@ namespace OpenTelemetry.Instrumentation.Dependencies.Tests
[Fact]
public async Task HttpDependenciesInstrumentationInjectsHeadersAsync()
{
- var spanProcessor = new Mock<SpanProcessor>();
- var tracer = TracerFactory.Create(b => b.AddProcessorPipeline(p => p.AddProcessor(_ => spanProcessor.Object)))
- .GetTracer(null);
+ var activityProcessor = new Mock<ActivityProcessor>();
+ using var shutdownSignal = OpenTelemetrySdk.EnableOpenTelemetry(b =>
+ {
+ b.SetProcessorPipeline(c => c.AddProcessor(ap => activityProcessor.Object));
+ b.AddHttpWebRequestDependencyInstrumentation();
+ });
var request = (HttpWebRequest)WebRequest.Create(this.url);
| 1 | // <copyright file="HttpWebRequestTests.Basic.net461.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry 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.
// </copyright>
#if NET461
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Moq;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Internal.Test;
using OpenTelemetry.Trace;
using OpenTelemetry.Trace.Configuration;
using OpenTelemetry.Trace.Export;
using OpenTelemetry.Instrumentation.Dependencies.Implementation;
using Xunit;
namespace OpenTelemetry.Instrumentation.Dependencies.Tests
{
public partial class HttpWebRequestTests : IDisposable
{
private readonly IDisposable serverLifeTime;
private readonly string url;
public HttpWebRequestTests()
{
Assert.Null(Activity.Current);
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = false;
this.serverLifeTime = TestHttpServer.RunServer(
(ctx) =>
{
ctx.Response.StatusCode = 200;
ctx.Response.OutputStream.Close();
},
out var host,
out var port);
this.url = $"http://{host}:{port}/";
}
public void Dispose()
{
this.serverLifeTime?.Dispose();
}
[Fact]
public async Task HttpDependenciesInstrumentationInjectsHeadersAsync()
{
var spanProcessor = new Mock<SpanProcessor>();
var tracer = TracerFactory.Create(b => b.AddProcessorPipeline(p => p.AddProcessor(_ => spanProcessor.Object)))
.GetTracer(null);
var request = (HttpWebRequest)WebRequest.Create(this.url);
request.Method = "GET";
var parent = new Activity("parent")
.SetIdFormat(ActivityIdFormat.W3C)
.Start();
parent.TraceStateString = "k1=v1,k2=v2";
parent.ActivityTraceFlags = ActivityTraceFlags.Recorded;
using (new HttpWebRequestInstrumentation(tracer, new HttpClientInstrumentationOptions()))
{
using var response = await request.GetResponseAsync();
}
Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called
var span = (SpanData)spanProcessor.Invocations[1].Arguments[0];
Assert.Equal(parent.TraceId, span.Context.TraceId);
Assert.Equal(parent.SpanId, span.ParentSpanId);
Assert.NotEqual(parent.SpanId, span.Context.SpanId);
Assert.NotEqual(default, span.Context.SpanId);
string traceparent = request.Headers.Get("traceparent");
string tracestate = request.Headers.Get("tracestate");
Assert.Equal($"00-{span.Context.TraceId}-{span.Context.SpanId}-01", traceparent);
Assert.Equal("k1=v1,k2=v2", tracestate);
parent.Stop();
}
[Fact]
public async Task HttpDependenciesInstrumentationInjectsHeadersAsync_CustomFormat()
{
var textFormat = new Mock<ITextFormat>();
textFormat.Setup(m => m.Inject<HttpWebRequest>(It.IsAny<SpanContext>(), It.IsAny<HttpWebRequest>(), It.IsAny<Action<HttpWebRequest, string, string>>()))
.Callback<SpanContext, HttpWebRequest, Action<HttpWebRequest, string, string>>((context, message, action) =>
{
action(message, "custom_traceparent", $"00/{context.TraceId}/{context.SpanId}/01");
action(message, "custom_tracestate", Activity.Current.TraceStateString);
});
var spanProcessor = new Mock<SpanProcessor>();
var tracer = TracerFactory.Create(b => b
.AddProcessorPipeline(p => p.AddProcessor(_ => spanProcessor.Object)))
.GetTracer(null);
var request = (HttpWebRequest)WebRequest.Create(this.url);
request.Method = "GET";
var parent = new Activity("parent")
.SetIdFormat(ActivityIdFormat.W3C)
.Start();
parent.TraceStateString = "k1=v1,k2=v2";
parent.ActivityTraceFlags = ActivityTraceFlags.Recorded;
using (new HttpWebRequestInstrumentation(tracer, new HttpClientInstrumentationOptions { TextFormat = textFormat.Object }))
{
using var response = await request.GetResponseAsync();
}
Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called
var span = (SpanData)spanProcessor.Invocations[1].Arguments[0];
Assert.Equal(parent.TraceId, span.Context.TraceId);
Assert.Equal(parent.SpanId, span.ParentSpanId);
Assert.NotEqual(parent.SpanId, span.Context.SpanId);
Assert.NotEqual(default, span.Context.SpanId);
string traceparent = request.Headers.Get("custom_traceparent");
string tracestate = request.Headers.Get("custom_tracestate");
Assert.Equal($"00/{span.Context.TraceId}/{span.Context.SpanId}/01", traceparent);
Assert.Equal("k1=v1,k2=v2", tracestate);
parent.Stop();
}
[Fact]
public async Task HttpDependenciesInstrumentation_AddViaFactory_HttpInstrumentation_CollectsSpans()
{
var spanProcessor = new Mock<SpanProcessor>();
using (TracerFactory.Create(b => b
.AddProcessorPipeline(p => p.AddProcessor(_ => spanProcessor.Object))
.AddInstrumentation(t => new HttpWebRequestInstrumentation(t))))
{
using var c = new HttpClient();
await c.GetAsync(this.url);
}
Assert.Single(spanProcessor.Invocations.Where(i => i.Method.Name == "OnStart"));
Assert.Single(spanProcessor.Invocations.Where(i => i.Method.Name == "OnEnd"));
Assert.IsType<SpanData>(spanProcessor.Invocations[1].Arguments[0]);
}
[Fact]
public async Task HttpDependenciesInstrumentation_AddViaFactory_DependencyInstrumentation_CollectsSpans()
{
var spanProcessor = new Mock<SpanProcessor>();
using (TracerFactory.Create(b => b
.AddProcessorPipeline(p => p.AddProcessor(_ => spanProcessor.Object))
.AddDependencyInstrumentation()))
{
using var c = new HttpClient();
await c.GetAsync(this.url);
}
Assert.Single(spanProcessor.Invocations.Where(i => i.Method.Name == "OnStart"));
Assert.Single(spanProcessor.Invocations.Where(i => i.Method.Name == "OnEnd"));
Assert.IsType<SpanData>(spanProcessor.Invocations[1].Arguments[0]);
}
[Fact]
public async Task HttpDependenciesInstrumentationBacksOffIfAlreadyInstrumented()
{
var spanProcessor = new Mock<SpanProcessor>();
var tracer = TracerFactory.Create(b => b
.AddProcessorPipeline(p => p.AddProcessor(_ => spanProcessor.Object)))
.GetTracer(null);
var request = new HttpRequestMessage
{
RequestUri = new Uri(this.url),
Method = new HttpMethod("GET"),
};
request.Headers.Add("traceparent", "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01");
using (new HttpWebRequestInstrumentation(tracer, new HttpClientInstrumentationOptions()))
{
using var c = new HttpClient();
await c.SendAsync(request);
}
Assert.Equal(0, spanProcessor.Invocations.Count);
}
[Fact]
public async Task HttpDependenciesInstrumentationFiltersOutRequests()
{
var spanProcessor = new Mock<SpanProcessor>();
var tracer = TracerFactory.Create(b => b
.AddProcessorPipeline(p => p.AddProcessor(_ => spanProcessor.Object)))
.GetTracer(null);
var options = new HttpClientInstrumentationOptions((activityName, arg1, _)
=> !(activityName == HttpWebRequestDiagnosticSource.ActivityName &&
arg1 is HttpWebRequest request &&
request.RequestUri.OriginalString.Contains(this.url)));
using (new HttpWebRequestInstrumentation(tracer, options))
{
using var c = new HttpClient();
await c.GetAsync(this.url);
}
Assert.Equal(0, spanProcessor.Invocations.Count);
}
}
}
#endif
| 1 | 14,065 | @cijothomas This build-up pattern was really confusing. It looks like internally ActivityProcessor is intended to be chained but there is nothing in the abstract class that enforces it. We never set a "Next" or make sure that the chain is called. Probably need to do some more work in this area? | open-telemetry-opentelemetry-dotnet | .cs |
@@ -1206,6 +1206,11 @@ Schema.prototype.queue = function(name, args) {
* console.log(this.getFilter());
* });
*
+ * // Equivalent to calling `pre()` on `save`, `findOneAndUpdate`.
+ * toySchema.pre(['save', 'findOneAndUpdate'], function(next) {
+ * console.log(this.getFilter());
+ * });
+ *
* @param {String|RegExp} The method name or regular expression to match method name
* @param {Object} [options]
* @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. | 1 | 'use strict';
/*!
* Module dependencies.
*/
const EventEmitter = require('events').EventEmitter;
const Kareem = require('kareem');
const SchemaType = require('./schematype');
const VirtualType = require('./virtualtype');
const applyTimestampsToChildren = require('./helpers/update/applyTimestampsToChildren');
const applyTimestampsToUpdate = require('./helpers/update/applyTimestampsToUpdate');
const get = require('./helpers/get');
const getIndexes = require('./helpers/schema/getIndexes');
const handleTimestampOption = require('./helpers/schema/handleTimestampOption');
const merge = require('./helpers/schema/merge');
const mpath = require('mpath');
const readPref = require('./driver').get().ReadPreference;
const symbols = require('./schema/symbols');
const util = require('util');
const utils = require('./utils');
const validateRef = require('./helpers/populate/validateRef');
let MongooseTypes;
const queryHooks = require('./helpers/query/applyQueryMiddleware').
middlewareFunctions;
const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
const hookNames = queryHooks.concat(documentHooks).
reduce((s, hook) => s.add(hook), new Set());
let id = 0;
/**
* Schema constructor.
*
* ####Example:
*
* var child = new Schema({ name: String });
* var schema = new Schema({ name: String, age: Number, children: [child] });
* var Tree = mongoose.model('Tree', schema);
*
* // setting schema options
* new Schema({ name: String }, { _id: false, autoIndex: false })
*
* ####Options:
*
* - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
* - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
* - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
* - [capped](/docs/guide.html#capped): bool - defaults to false
* - [collection](/docs/guide.html#collection): string - no default
* - [id](/docs/guide.html#id): bool - defaults to true
* - [_id](/docs/guide.html#_id): bool - defaults to true
* - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
* - [read](/docs/guide.html#read): string
* - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/)
* - [shardKey](/docs/guide.html#shardKey): object - defaults to `null`
* - [strict](/docs/guide.html#strict): bool - defaults to true
* - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false
* - [toJSON](/docs/guide.html#toJSON) - object - no default
* - [toObject](/docs/guide.html#toObject) - object - no default
* - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type'
* - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false
* - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
* - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v"
* - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation)
* - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
* - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning
* - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
* - [storeSubdocValidationError](/docs/guide.html#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path.
*
* ####Note:
*
* _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
*
* @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
* @param {Object} [options]
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `init`: Emitted after the schema is compiled into a `Model`.
* @api public
*/
function Schema(obj, options) {
if (!(this instanceof Schema)) {
return new Schema(obj, options);
}
this.obj = obj;
this.paths = {};
this.aliases = {};
this.subpaths = {};
this.virtuals = {};
this.singleNestedPaths = {};
this.nested = {};
this.inherits = {};
this.callQueue = [];
this._indexes = [];
this.methods = {};
this.methodOptions = {};
this.statics = {};
this.tree = {};
this.query = {};
this.childSchemas = [];
this.plugins = [];
// For internal debugging. Do not use this to try to save a schema in MDB.
this.$id = ++id;
this.s = {
hooks: new Kareem()
};
this.options = this.defaultOptions(options);
// build paths
if (Array.isArray(obj)) {
for (const definition of obj) {
this.add(definition);
}
} else if (obj) {
this.add(obj);
}
// check if _id's value is a subdocument (gh-2276)
const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
// ensure the documents get an auto _id unless disabled
const auto_id = !this.paths['_id'] &&
(!this.options.noId && this.options._id) && !_idSubDoc;
if (auto_id) {
const _obj = {_id: {auto: true}};
_obj._id[this.options.typeKey] = Schema.ObjectId;
this.add(_obj);
}
this.setupTimestamp(this.options.timestamps);
}
/*!
* Create virtual properties with alias field
*/
function aliasFields(schema, paths) {
paths = paths || Object.keys(schema.paths);
for (const path of paths) {
const options = get(schema.paths[path], 'options');
if (options == null) {
continue;
}
const prop = schema.paths[path].path;
const alias = options.alias;
if (!alias) {
continue;
}
if (typeof alias !== 'string') {
throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias);
}
schema.aliases[alias] = prop;
schema.
virtual(alias).
get((function(p) {
return function() {
if (typeof this.get === 'function') {
return this.get(p);
}
return this[p];
};
})(prop)).
set((function(p) {
return function(v) {
return this.set(p, v);
};
})(prop));
}
}
/*!
* Inherit from EventEmitter.
*/
Schema.prototype = Object.create(EventEmitter.prototype);
Schema.prototype.constructor = Schema;
Schema.prototype.instanceOfSchema = true;
/*!
* ignore
*/
Object.defineProperty(Schema.prototype, '$schemaType', {
configurable: false,
enumerable: false,
writable: true
});
/**
* Array of child schemas (from document arrays and single nested subdocs)
* and their corresponding compiled models. Each element of the array is
* an object with 2 properties: `schema` and `model`.
*
* This property is typically only useful for plugin authors and advanced users.
* You do not need to interact with this property at all to use mongoose.
*
* @api public
* @property childSchemas
* @memberOf Schema
* @instance
*/
Object.defineProperty(Schema.prototype, 'childSchemas', {
configurable: false,
enumerable: true,
writable: true
});
/**
* The original object passed to the schema constructor
*
* ####Example:
*
* var schema = new Schema({ a: String }).add({ b: String });
* schema.obj; // { a: String }
*
* @api public
* @property obj
* @memberOf Schema
* @instance
*/
Schema.prototype.obj;
/**
* Schema as flat paths
*
* ####Example:
* {
* '_id' : SchemaType,
* , 'nested.key' : SchemaType,
* }
*
* @api private
* @property paths
* @memberOf Schema
* @instance
*/
Schema.prototype.paths;
/**
* Schema as a tree
*
* ####Example:
* {
* '_id' : ObjectId
* , 'nested' : {
* 'key' : String
* }
* }
*
* @api private
* @property tree
* @memberOf Schema
* @instance
*/
Schema.prototype.tree;
/**
* Returns a deep copy of the schema
*
* ####Example:
*
* const schema = new Schema({ name: String });
* const clone = schema.clone();
* clone === schema; // false
* clone.path('name'); // SchemaString { ... }
*
* @return {Schema} the cloned schema
* @api public
* @memberOf Schema
* @instance
*/
Schema.prototype.clone = function() {
const s = new Schema({}, this._userProvidedOptions);
s.base = this.base;
s.obj = this.obj;
s.options = utils.clone(this.options);
s.callQueue = this.callQueue.map(function(f) { return f; });
s.methods = utils.clone(this.methods);
s.methodOptions = utils.clone(this.methodOptions);
s.statics = utils.clone(this.statics);
s.query = utils.clone(this.query);
s.plugins = Array.prototype.slice.call(this.plugins);
s._indexes = utils.clone(this._indexes);
s.s.hooks = this.s.hooks.clone();
s._originalSchema = this._originalSchema == null ?
this._originalSchema :
this._originalSchema.clone();
s.tree = utils.clone(this.tree);
s.paths = utils.clone(this.paths);
s.nested = utils.clone(this.nested);
s.subpaths = utils.clone(this.subpaths);
s.singleNestedPaths = utils.clone(this.singleNestedPaths);
s.childSchemas = gatherChildSchemas(s);
s.virtuals = utils.clone(this.virtuals);
s.$globalPluginsApplied = this.$globalPluginsApplied;
s.$isRootDiscriminator = this.$isRootDiscriminator;
s.$implicitlyCreated = this.$implicitlyCreated;
if (this.discriminatorMapping != null) {
s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
}
if (this.discriminators != null) {
s.discriminators = Object.assign({}, this.discriminators);
}
s.aliases = Object.assign({}, this.aliases);
// Bubble up `init` for backwards compat
s.on('init', v => this.emit('init', v));
return s;
};
/**
* Returns default options for this schema, merged with `options`.
*
* @param {Object} options
* @return {Object}
* @api private
*/
Schema.prototype.defaultOptions = function(options) {
if (options && options.safe === false) {
options.safe = {w: 0};
}
if (options && options.safe && options.safe.w === 0) {
// if you turn off safe writes, then versioning goes off as well
options.versionKey = false;
}
this._userProvidedOptions = options == null ? {} : utils.clone(options);
const baseOptions = get(this, 'base.options', {});
options = utils.options({
strict: 'strict' in baseOptions ? baseOptions.strict : true,
bufferCommands: true,
capped: false, // { size, max, autoIndexId }
versionKey: '__v',
discriminatorKey: '__t',
minimize: true,
autoIndex: null,
shardKey: null,
read: null,
validateBeforeSave: true,
// the following are only applied at construction time
noId: false, // deprecated, use { _id: false }
_id: true,
noVirtualId: false, // deprecated, use { id: false }
id: true,
typeKey: 'type'
}, utils.clone(options));
if (options.read) {
options.read = readPref(options.read);
}
return options;
};
/**
* Adds key path / schema type pairs to this schema.
*
* ####Example:
*
* const ToySchema = new Schema();
* ToySchema.add({ name: 'string', color: 'string', price: 'number' });
*
* const TurboManSchema = new Schema();
* // You can also `add()` another schema and copy over all paths, virtuals,
* // getters, setters, indexes, methods, and statics.
* TurboManSchema.add(ToySchema).add({ year: Number });
*
* @param {Object|Schema} obj plain object with paths to add, or another schema
* @param {String} [prefix] path to prefix the newly added paths with
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.add = function add(obj, prefix) {
if (obj instanceof Schema) {
merge(this, obj);
return this;
}
// Special case: setting top-level `_id` to false should convert to disabling
// the `_id` option. This behavior never worked before 5.4.11 but numerous
// codebases use it (see gh-7516, gh-7512).
if (obj._id === false && prefix == null) {
delete obj._id;
this.options._id = false;
}
prefix = prefix || '';
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const fullPath = prefix + key;
if (obj[key] == null) {
throw new TypeError('Invalid value for schema path `' + fullPath +
'`, got value "' + obj[key] + '"');
}
if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) {
throw new TypeError('Invalid value for schema Array path `' + fullPath +
'`, got value "' + obj[key][0] + '"');
}
if (utils.isPOJO(obj[key]) &&
(!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) {
if (Object.keys(obj[key]).length) {
// nested object { last: { name: String }}
this.nested[fullPath] = true;
this.add(obj[key], fullPath + '.');
} else {
if (prefix) {
this.nested[prefix.substr(0, prefix.length - 1)] = true;
}
this.path(fullPath, obj[key]); // mixed type
}
} else {
if (prefix) {
this.nested[prefix.substr(0, prefix.length - 1)] = true;
}
this.path(prefix + key, obj[key]);
}
}
const addedKeys = Object.keys(obj).
map(key => prefix ? prefix + key : key);
aliasFields(this, addedKeys);
return this;
};
/**
* Reserved document keys.
*
* Keys in this object are names that are rejected in schema declarations
* because they conflict with Mongoose functionality. If you create a schema
* using `new Schema()` with one of these property names, Mongoose will throw
* an error.
*
* - prototype
* - emit
* - on
* - once
* - listeners
* - removeListener
* - collection
* - db
* - errors
* - init
* - isModified
* - isNew
* - get
* - modelName
* - save
* - schema
* - toObject
* - validate
* - remove
* - populated
* - _pres
* - _posts
*
* _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.
*
* var schema = new Schema(..);
* schema.methods.init = function () {} // potentially breaking
*/
Schema.reserved = Object.create(null);
Schema.prototype.reserved = Schema.reserved;
const reserved = Schema.reserved;
// Core object
reserved['prototype'] =
// EventEmitter
reserved.emit =
reserved.on =
reserved.once =
reserved.listeners =
reserved.removeListener =
// document properties and functions
reserved.collection =
reserved.db =
reserved.errors =
reserved.init =
reserved.isModified =
reserved.isNew =
reserved.get =
reserved.modelName =
reserved.save =
reserved.schema =
reserved.toObject =
reserved.validate =
reserved.remove =
reserved.populated =
// hooks.js
reserved._pres = reserved._posts = 1;
/*!
* Document keys to print warnings for
*/
const warnings = {};
warnings.increment = '`increment` should not be used as a schema path name ' +
'unless you have disabled versioning.';
/**
* Gets/sets schema paths.
*
* Sets a path (if arity 2)
* Gets a path (if arity 1)
*
* ####Example
*
* schema.path('name') // returns a SchemaType
* schema.path('name', Number) // changes the schemaType of `name` to Number
*
* @param {String} path
* @param {Object} constructor
* @api public
*/
Schema.prototype.path = function(path, obj) {
if (obj === undefined) {
if (this.paths.hasOwnProperty(path)) {
return this.paths[path];
}
if (this.subpaths.hasOwnProperty(path)) {
return this.subpaths[path];
}
if (this.singleNestedPaths.hasOwnProperty(path)) {
return this.singleNestedPaths[path];
}
// Look for maps
const mapPath = getMapPath(this, path);
if (mapPath != null) {
return mapPath;
}
// subpaths?
return /\.\d+\.?.*$/.test(path)
? getPositionalPath(this, path)
: undefined;
}
// some path names conflict with document methods
if (reserved[path]) {
throw new Error('`' + path + '` may not be used as a schema pathname');
}
if (warnings[path]) {
console.log('WARN: ' + warnings[path]);
}
if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
validateRef(obj.ref, path);
}
// update the tree
const subpaths = path.split(/\./);
const last = subpaths.pop();
let branch = this.tree;
subpaths.forEach(function(sub, i) {
if (!branch[sub]) {
branch[sub] = {};
}
if (typeof branch[sub] !== 'object') {
const msg = 'Cannot set nested path `' + path + '`. '
+ 'Parent path `'
+ subpaths.slice(0, i).concat([sub]).join('.')
+ '` already set to type ' + branch[sub].name
+ '.';
throw new Error(msg);
}
branch = branch[sub];
});
branch[last] = utils.clone(obj);
this.paths[path] = this.interpretAsType(path, obj, this.options);
const schemaType = this.paths[path];
if (schemaType.$isSchemaMap) {
// Maps can have arbitrary keys, so `$*` is internal shorthand for "any key"
// The '$' is to imply this path should never be stored in MongoDB so we
// can easily build a regexp out of this path, and '*' to imply "any key."
const mapPath = path + '.$*';
let _mapType = { type: {} };
if (utils.hasUserDefinedProperty(obj, 'of')) {
const isInlineSchema = utils.isPOJO(obj.of) &&
Object.keys(obj.of).length > 0 &&
!utils.hasUserDefinedProperty(obj.of, this.options.typeKey);
_mapType = isInlineSchema ? new Schema(obj.of) : obj.of;
}
this.paths[mapPath] = this.interpretAsType(mapPath,
_mapType, this.options);
schemaType.$__schemaType = this.paths[mapPath];
}
if (schemaType.$isSingleNested) {
for (const key in schemaType.schema.paths) {
this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
}
for (const key in schemaType.schema.singleNestedPaths) {
this.singleNestedPaths[path + '.' + key] =
schemaType.schema.singleNestedPaths[key];
}
Object.defineProperty(schemaType.schema, 'base', {
configurable: true,
enumerable: false,
writable: false,
value: this.base
});
schemaType.caster.base = this.base;
this.childSchemas.push({
schema: schemaType.schema,
model: schemaType.caster
});
} else if (schemaType.$isMongooseDocumentArray) {
Object.defineProperty(schemaType.schema, 'base', {
configurable: true,
enumerable: false,
writable: false,
value: this.base
});
schemaType.casterConstructor.base = this.base;
this.childSchemas.push({
schema: schemaType.schema,
model: schemaType.casterConstructor
});
}
return this;
};
/*!
* ignore
*/
function gatherChildSchemas(schema) {
const childSchemas = [];
for (const path of Object.keys(schema.paths)) {
const schematype = schema.paths[path];
if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) {
childSchemas.push({ schema: schematype.schema, model: schematype.caster });
}
}
return childSchemas;
}
/*!
* ignore
*/
function getMapPath(schema, path) {
for (const _path of Object.keys(schema.paths)) {
if (!_path.includes('.$*')) {
continue;
}
const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
if (re.test(path)) {
return schema.paths[_path];
}
}
return null;
}
/**
* The Mongoose instance this schema is associated with
*
* @property base
* @api private
*/
Object.defineProperty(Schema.prototype, 'base', {
configurable: true,
enumerable: false,
writable: true,
value: null
});
/**
* Converts type arguments into Mongoose Types.
*
* @param {String} path
* @param {Object} obj constructor
* @api private
*/
Schema.prototype.interpretAsType = function(path, obj, options) {
if (obj instanceof SchemaType) {
return obj;
}
// If this schema has an associated Mongoose object, use the Mongoose object's
// copy of SchemaTypes re: gh-7158 gh-6933
const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
if (obj.constructor) {
const constructorName = utils.getFunctionName(obj.constructor);
if (constructorName !== 'Object') {
const oldObj = obj;
obj = {};
obj[options.typeKey] = oldObj;
}
}
// Get the type making sure to allow keys named "type"
// and default to mixed if not specified.
// { type: { type: String, default: 'freshcut' } }
let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type)
? obj[options.typeKey]
: {};
let name;
if (utils.isPOJO(type) || type === 'mixed') {
return new MongooseTypes.Mixed(path, obj);
}
if (Array.isArray(type) || Array === type || type === 'array') {
// if it was specified through { type } look for `cast`
let cast = (Array === type || type === 'array')
? obj.cast
: type[0];
if (cast && cast.instanceOfSchema) {
return new MongooseTypes.DocumentArray(path, cast, obj);
}
if (cast &&
cast[options.typeKey] &&
cast[options.typeKey].instanceOfSchema) {
return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
}
if (Array.isArray(cast)) {
return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
}
if (typeof cast === 'string') {
cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
} else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type))
&& utils.isPOJO(cast)) {
if (Object.keys(cast).length) {
// The `minimize` and `typeKey` options propagate to child schemas
// declared inline, like `{ arr: [{ val: { $type: String } }] }`.
// See gh-3560
const childSchemaOptions = {minimize: options.minimize};
if (options.typeKey) {
childSchemaOptions.typeKey = options.typeKey;
}
//propagate 'strict' option to child schema
if (options.hasOwnProperty('strict')) {
childSchemaOptions.strict = options.strict;
}
const childSchema = new Schema(cast, childSchemaOptions);
childSchema.$implicitlyCreated = true;
return new MongooseTypes.DocumentArray(path, childSchema, obj);
} else {
// Special case: empty object becomes mixed
return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
}
}
if (cast) {
type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
? cast[options.typeKey]
: cast;
name = typeof type === 'string'
? type
: type.schemaName || utils.getFunctionName(type);
if (!(name in MongooseTypes)) {
throw new TypeError('Invalid schema configuration: ' +
`\`${name}\` is not a valid type within the array \`${path}\`.` +
'See http://bit.ly/mongoose-schematypes for a list of valid schema types.');
}
}
return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
}
if (type && type.instanceOfSchema) {
return new MongooseTypes.Embedded(type, path, obj);
}
if (Buffer.isBuffer(type)) {
name = 'Buffer';
} else if (typeof type === 'function' || typeof type === 'object') {
name = type.schemaName || utils.getFunctionName(type);
} else {
name = type == null ? '' + type : type.toString();
}
if (name) {
name = name.charAt(0).toUpperCase() + name.substring(1);
}
// Special case re: gh-7049 because the bson `ObjectID` class' capitalization
// doesn't line up with Mongoose's.
if (name === 'ObjectID') {
name = 'ObjectId';
}
if (MongooseTypes[name] == null) {
throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
`a valid type at path \`${path}\`. See ` +
'http://bit.ly/mongoose-schematypes for a list of valid schema types.');
}
return new MongooseTypes[name](path, obj);
};
/**
* Iterates the schemas paths similar to Array#forEach.
*
* The callback is passed the pathname and the schemaType instance.
*
* ####Example:
*
* const userSchema = new Schema({ name: String, registeredAt: Date });
* userSchema.eachPath((pathname, schematype) => {
* // Prints twice:
* // name SchemaString { ... }
* // registeredAt SchemaDate { ... }
* console.log(pathname, schematype);
* });
*
* @param {Function} fn callback function
* @return {Schema} this
* @api public
*/
Schema.prototype.eachPath = function(fn) {
const keys = Object.keys(this.paths);
const len = keys.length;
for (let i = 0; i < len; ++i) {
fn(keys[i], this.paths[keys[i]]);
}
return this;
};
/**
* Returns an Array of path strings that are required by this schema.
*
* ####Example:
* const s = new Schema({
* name: { type: String, required: true },
* age: { type: String, required: true },
* notes: String
* });
* s.requiredPaths(); // [ 'age', 'name' ]
*
* @api public
* @param {Boolean} invalidate refresh the cache
* @return {Array}
*/
Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
if (this._requiredpaths && !invalidate) {
return this._requiredpaths;
}
const paths = Object.keys(this.paths);
let i = paths.length;
const ret = [];
while (i--) {
const path = paths[i];
if (this.paths[path].isRequired) {
ret.push(path);
}
}
this._requiredpaths = ret;
return this._requiredpaths;
};
/**
* Returns indexes from fields and schema-level indexes (cached).
*
* @api private
* @return {Array}
*/
Schema.prototype.indexedPaths = function indexedPaths() {
if (this._indexedpaths) {
return this._indexedpaths;
}
this._indexedpaths = this.indexes();
return this._indexedpaths;
};
/**
* Returns the pathType of `path` for this schema.
*
* Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
*
* ####Example:
* const s = new Schema({ name: String, nested: { foo: String } });
* s.virtual('foo').get(() => 42);
* s.pathType('name'); // "real"
* s.pathType('nested'); // "nested"
* s.pathType('foo'); // "virtual"
* s.pathType('fail'); // "adhocOrUndefined"
*
* @param {String} path
* @return {String}
* @api public
*/
Schema.prototype.pathType = function(path) {
if (this.paths.hasOwnProperty(path)) {
return 'real';
}
if (this.virtuals.hasOwnProperty(path)) {
return 'virtual';
}
if (this.nested.hasOwnProperty(path)) {
return 'nested';
}
if (this.subpaths.hasOwnProperty(path)) {
return 'real';
}
if (this.singleNestedPaths.hasOwnProperty(path)) {
return 'real';
}
// Look for maps
const mapPath = getMapPath(this, path);
if (mapPath != null) {
return 'real';
}
if (/\.\d+\.|\.\d+$/.test(path)) {
return getPositionalPathType(this, path);
}
return 'adhocOrUndefined';
};
/**
* Returns true iff this path is a child of a mixed schema.
*
* @param {String} path
* @return {Boolean}
* @api private
*/
Schema.prototype.hasMixedParent = function(path) {
const subpaths = path.split(/\./g);
path = '';
for (let i = 0; i < subpaths.length; ++i) {
path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
if (path in this.paths &&
this.paths[path] instanceof MongooseTypes.Mixed) {
return true;
}
}
return false;
};
/**
* Setup updatedAt and createdAt timestamps to documents if enabled
*
* @param {Boolean|Object} timestamps timestamps options
* @api private
*/
Schema.prototype.setupTimestamp = function(timestamps) {
const childHasTimestamp = this.childSchemas.find(withTimestamp);
function withTimestamp(s) {
const ts = s.schema.options.timestamps;
return !!ts;
}
if (!timestamps && !childHasTimestamp) {
return;
}
const createdAt = handleTimestampOption(timestamps, 'createdAt');
const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
const schemaAdditions = {};
this.$timestamps = { createdAt: createdAt, updatedAt: updatedAt };
if (updatedAt && !this.paths[updatedAt]) {
schemaAdditions[updatedAt] = Date;
}
if (createdAt && !this.paths[createdAt]) {
schemaAdditions[createdAt] = Date;
}
this.add(schemaAdditions);
this.pre('save', function(next) {
if (get(this, '$__.saveOptions.timestamps') === false) {
return next();
}
const defaultTimestamp = (this.ownerDocument ? this.ownerDocument() : this).
constructor.base.now();
const auto_id = this._id && this._id.auto;
if (createdAt && !this.get(createdAt) && this.isSelected(createdAt)) {
this.set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp);
}
if (updatedAt && (this.isNew || this.isModified())) {
let ts = defaultTimestamp;
if (this.isNew) {
if (createdAt != null) {
ts = this.$__getValue(createdAt);
} else if (auto_id) {
ts = this._id.getTimestamp();
}
}
this.set(updatedAt, ts);
}
next();
});
this.methods.initializeTimestamps = function() {
if (createdAt && !this.get(createdAt)) {
this.set(createdAt, new Date());
}
if (updatedAt && !this.get(updatedAt)) {
this.set(updatedAt, new Date());
}
return this;
};
_setTimestampsOnUpdate[symbols.builtInMiddleware] = true;
const opts = { query: true, model: false };
this.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate);
this.pre('replaceOne', opts, _setTimestampsOnUpdate);
this.pre('update', opts, _setTimestampsOnUpdate);
this.pre('updateOne', opts, _setTimestampsOnUpdate);
this.pre('updateMany', opts, _setTimestampsOnUpdate);
function _setTimestampsOnUpdate(next) {
const now = this.model.base.now();
applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(),
this.options, this.schema);
applyTimestampsToChildren(now, this.getUpdate(), this.model.schema);
next();
}
};
/*!
* ignore
*/
function getPositionalPathType(self, path) {
const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
if (subpaths.length < 2) {
return self.paths.hasOwnProperty(subpaths[0]) ?
self.paths[subpaths[0]] :
'adhocOrUndefined';
}
let val = self.path(subpaths[0]);
let isNested = false;
if (!val) {
return 'adhocOrUndefined';
}
const last = subpaths.length - 1;
for (let i = 1; i < subpaths.length; ++i) {
isNested = false;
const subpath = subpaths[i];
if (i === last && val && !/\D/.test(subpath)) {
if (val.$isMongooseDocumentArray) {
const oldVal = val;
val = new SchemaType(subpath, {
required: get(val, 'schemaOptions.required', false)
});
val.cast = function(value, doc, init) {
return oldVal.cast(value, doc, init)[0];
};
val.$isMongooseDocumentArrayElement = true;
val.caster = oldVal.caster;
val.schema = oldVal.schema;
} else if (val instanceof MongooseTypes.Array) {
// StringSchema, NumberSchema, etc
val = val.caster;
} else {
val = undefined;
}
break;
}
// ignore if its just a position segment: path.0.subpath
if (!/\D/.test(subpath)) {
// Nested array
if (val instanceof MongooseTypes.Array && i !== last) {
val = val.caster;
}
continue;
}
if (!(val && val.schema)) {
val = undefined;
break;
}
const type = val.schema.pathType(subpath);
isNested = (type === 'nested');
val = val.schema.path(subpath);
}
self.subpaths[path] = val;
if (val) {
return 'real';
}
if (isNested) {
return 'nested';
}
return 'adhocOrUndefined';
}
/*!
* ignore
*/
function getPositionalPath(self, path) {
getPositionalPathType(self, path);
return self.subpaths[path];
}
/**
* Adds a method call to the queue.
*
* ####Example:
*
* schema.methods.print = function() { console.log(this); };
* schema.queue('print', []); // Print the doc every one is instantiated
*
* const Model = mongoose.model('Test', schema);
* new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
*
* @param {String} name name of the document method to call later
* @param {Array} args arguments to pass to the method
* @api public
*/
Schema.prototype.queue = function(name, args) {
this.callQueue.push([name, args]);
return this;
};
/**
* Defines a pre hook for the document.
*
* ####Example
*
* var toySchema = new Schema({ name: String, created: Date });
*
* toySchema.pre('save', function(next) {
* if (!this.created) this.created = new Date;
* next();
* });
*
* toySchema.pre('validate', function(next) {
* if (this.name !== 'Woody') this.name = 'Woody';
* next();
* });
*
* // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
* toySchema.pre(/^find/, function(next) {
* console.log(this.getFilter());
* });
*
* @param {String|RegExp} The method name or regular expression to match method name
* @param {Object} [options]
* @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
* @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
* @param {Function} callback
* @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3
* @api public
*/
Schema.prototype.pre = function(name) {
if (name instanceof RegExp) {
const remainingArgs = Array.prototype.slice.call(arguments, 1);
for (const fn of hookNames) {
if (name.test(fn)) {
this.pre.apply(this, [fn].concat(remainingArgs));
}
}
return this;
}
if (Array.isArray(name)) {
const remainingArgs = Array.prototype.slice.call(arguments, 1);
for (const el of name) {
this.pre.apply(this, [el].concat(remainingArgs));
}
return this;
}
this.s.hooks.pre.apply(this.s.hooks, arguments);
return this;
};
/**
* Defines a post hook for the document
*
* var schema = new Schema(..);
* schema.post('save', function (doc) {
* console.log('this fired after a document was saved');
* });
*
* schema.post('find', function(docs) {
* console.log('this fired after you ran a find query');
* });
*
* schema.post(/Many$/, function(res) {
* console.log('this fired after you ran `updateMany()` or `deleteMany()`);
* });
*
* var Model = mongoose.model('Model', schema);
*
* var m = new Model(..);
* m.save(function(err) {
* console.log('this fires after the `post` hook');
* });
*
* m.find(function(err, docs) {
* console.log('this fires after the post find hook');
* });
*
* @param {String|RegExp} The method name or regular expression to match method name
* @param {Object} [options]
* @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
* @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
* @param {Function} fn callback
* @see middleware http://mongoosejs.com/docs/middleware.html
* @see kareem http://npmjs.org/package/kareem
* @api public
*/
Schema.prototype.post = function(name) {
if (name instanceof RegExp) {
const remainingArgs = Array.prototype.slice.call(arguments, 1);
for (const fn of hookNames) {
if (name.test(fn)) {
this.post.apply(this, [fn].concat(remainingArgs));
}
}
return this;
}
if (Array.isArray(name)) {
const remainingArgs = Array.prototype.slice.call(arguments, 1);
for (const el of name) {
this.post.apply(this, [el].concat(remainingArgs));
}
return this;
}
this.s.hooks.post.apply(this.s.hooks, arguments);
return this;
};
/**
* Registers a plugin for this schema.
*
* ####Example:
*
* const s = new Schema({ name: String });
* s.plugin(schema => console.log(schema.path('name').path));
* mongoose.model('Test', schema); // Prints 'name'
*
* @param {Function} plugin callback
* @param {Object} [opts]
* @see plugins
* @api public
*/
Schema.prototype.plugin = function(fn, opts) {
if (typeof fn !== 'function') {
throw new Error('First param to `schema.plugin()` must be a function, ' +
'got "' + (typeof fn) + '"');
}
if (opts &&
opts.deduplicate) {
for (let i = 0; i < this.plugins.length; ++i) {
if (this.plugins[i].fn === fn) {
return this;
}
}
}
this.plugins.push({ fn: fn, opts: opts });
fn(this, opts);
return this;
};
/**
* Adds an instance method to documents constructed from Models compiled from this schema.
*
* ####Example
*
* var schema = kittySchema = new Schema(..);
*
* schema.method('meow', function () {
* console.log('meeeeeoooooooooooow');
* })
*
* var Kitty = mongoose.model('Kitty', schema);
*
* var fizz = new Kitty;
* fizz.meow(); // meeeeeooooooooooooow
*
* If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
*
* schema.method({
* purr: function () {}
* , scratch: function () {}
* });
*
* // later
* fizz.purr();
* fizz.scratch();
*
* NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](./guide.html#methods)
*
* @param {String|Object} method name
* @param {Function} [fn]
* @api public
*/
Schema.prototype.method = function(name, fn, options) {
if (typeof name !== 'string') {
for (const i in name) {
this.methods[i] = name[i];
this.methodOptions[i] = utils.clone(options);
}
} else {
this.methods[name] = fn;
this.methodOptions[name] = utils.clone(options);
}
return this;
};
/**
* Adds static "class" methods to Models compiled from this schema.
*
* ####Example
*
* const schema = new Schema(..);
* // Equivalent to `schema.statics.findByName = function(name) {}`;
* schema.static('findByName', function(name) {
* return this.find({ name: name });
* });
*
* const Drink = mongoose.model('Drink', schema);
* await Drink.findByName('LaCroix');
*
* If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
*
* @param {String|Object} name
* @param {Function} [fn]
* @api public
* @see Statics /docs/guide.html#statics
*/
Schema.prototype.static = function(name, fn) {
if (typeof name !== 'string') {
for (const i in name) {
this.statics[i] = name[i];
}
} else {
this.statics[name] = fn;
}
return this;
};
/**
* Defines an index (most likely compound) for this schema.
*
* ####Example
*
* schema.index({ first: 1, last: -1 })
*
* @param {Object} fields
* @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex)
* @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
* @api public
*/
Schema.prototype.index = function(fields, options) {
fields || (fields = {});
options || (options = {});
if (options.expires) {
utils.expires(options);
}
this._indexes.push([fields, options]);
return this;
};
/**
* Sets/gets a schema option.
*
* ####Example
*
* schema.set('strict'); // 'true' by default
* schema.set('strict', false); // Sets 'strict' to false
* schema.set('strict'); // 'false'
*
* @param {String} key option name
* @param {Object} [value] if not passed, the current option value is returned
* @see Schema ./
* @api public
*/
Schema.prototype.set = function(key, value, _tags) {
if (arguments.length === 1) {
return this.options[key];
}
switch (key) {
case 'read':
this.options[key] = readPref(value, _tags);
this._userProvidedOptions[key] = this.options[key];
break;
case 'safe':
setSafe(this.options, value);
this._userProvidedOptions[key] = this.options[key];
break;
case 'timestamps':
this.setupTimestamp(value);
this.options[key] = value;
this._userProvidedOptions[key] = this.options[key];
break;
default:
this.options[key] = value;
this._userProvidedOptions[key] = this.options[key];
break;
}
return this;
};
/*!
* ignore
*/
const safeDeprecationWarning = 'Mongoose: The `safe` option for schemas is ' +
'deprecated. Use the `writeConcern` option instead: ' +
'http://bit.ly/mongoose-write-concern';
const setSafe = util.deprecate(function setSafe(options, value) {
options.safe = value === false ?
{w: 0} :
value;
}, safeDeprecationWarning);
/**
* Gets a schema option.
*
* ####Example:
*
* schema.get('strict'); // true
* schema.set('strict', false);
* schema.get('strict'); // false
*
* @param {String} key option name
* @api public
* @return {Any} the option's value
*/
Schema.prototype.get = function(key) {
return this.options[key];
};
/**
* The allowed index types
*
* @receiver Schema
* @static indexTypes
* @api public
*/
const indexTypes = '2d 2dsphere hashed text'.split(' ');
Object.defineProperty(Schema, 'indexTypes', {
get: function() {
return indexTypes;
},
set: function() {
throw new Error('Cannot overwrite Schema.indexTypes');
}
});
/**
* Returns a list of indexes that this schema declares, via `schema.index()`
* or by `index: true` in a path's options.
*
* ####Example:
*
* const userSchema = new Schema({
* email: { type: String, required: true, unique: true },
* registeredAt: { type: Date, index: true }
* });
*
* // [ [ { email: 1 }, { unique: true, background: true } ],
* // [ { registeredAt: 1 }, { background: true } ] ]
* userSchema.indexes();
*
* @api public
* @return {Array} list of indexes defined in the schema
*/
Schema.prototype.indexes = function() {
return getIndexes(this);
};
/**
* Creates a virtual type with the given name.
*
* @param {String} name
* @param {Object} [options]
* @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](populate.html#populate-virtuals).
* @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information.
* @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information.
* @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If truthy, will be a single doc or `null`. Otherwise, the populate virtual will be an array.
* @param {Boolean} [options.count=false] Only works with populate virtuals. If truthy, this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
* @return {VirtualType}
*/
Schema.prototype.virtual = function(name, options) {
if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
if (!options.localField) {
throw new Error('Reference virtuals require `localField` option');
}
if (!options.foreignField) {
throw new Error('Reference virtuals require `foreignField` option');
}
this.pre('init', function(obj) {
if (mpath.has(name, obj)) {
const _v = mpath.get(name, obj);
if (!this.$$populatedVirtuals) {
this.$$populatedVirtuals = {};
}
if (options.justOne || options.count) {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v[0] :
_v;
} else {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v :
_v == null ? [] : [_v];
}
mpath.unset(name, obj);
}
});
const virtual = this.virtual(name);
virtual.options = options;
return virtual.
get(function() {
if (!this.$$populatedVirtuals) {
this.$$populatedVirtuals = {};
}
if (this.$$populatedVirtuals.hasOwnProperty(name)) {
return this.$$populatedVirtuals[name];
}
return void 0;
}).
set(function(_v) {
if (!this.$$populatedVirtuals) {
this.$$populatedVirtuals = {};
}
if (options.justOne || options.count) {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v[0] :
_v;
if (typeof this.$$populatedVirtuals[name] !== 'object') {
this.$$populatedVirtuals[name] = options.count ? _v : null;
}
} else {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v :
_v == null ? [] : [_v];
this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
return doc && typeof doc === 'object';
});
}
});
}
const virtuals = this.virtuals;
const parts = name.split('.');
if (this.pathType(name) === 'real') {
throw new Error('Virtual path "' + name + '"' +
' conflicts with a real path in the schema');
}
virtuals[name] = parts.reduce(function(mem, part, i) {
mem[part] || (mem[part] = (i === parts.length - 1)
? new VirtualType(options, name)
: {});
return mem[part];
}, this.tree);
return virtuals[name];
};
/**
* Returns the virtual type with the given `name`.
*
* @param {String} name
* @return {VirtualType}
*/
Schema.prototype.virtualpath = function(name) {
return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null;
};
/**
* Removes the given `path` (or [`paths`]).
*
* ####Example:
*
* const schema = new Schema({ name: String, age: Number });
* schema.remove('name');
* schema.path('name'); // Undefined
* schema.path('age'); // SchemaNumber { ... }
*
* @param {String|Array} path
* @return {Schema} the Schema instance
* @api public
*/
Schema.prototype.remove = function(path) {
if (typeof path === 'string') {
path = [path];
}
if (Array.isArray(path)) {
path.forEach(function(name) {
if (this.path(name) == null && !this.nested[name]) {
return;
}
if (this.nested[name]) {
const allKeys = Object.keys(this.paths).
concat(Object.keys(this.nested));
for (const path of allKeys) {
if (path.startsWith(name + '.')) {
delete this.paths[path];
delete this.nested[path];
_deletePath(this, path);
}
}
delete this.nested[name];
_deletePath(this, name);
return;
}
delete this.paths[name];
_deletePath(this, name);
}, this);
}
return this;
};
/*!
* ignore
*/
function _deletePath(schema, name) {
const pieces = name.split('.');
const last = pieces.pop();
let branch = schema.tree;
for (let i = 0; i < pieces.length; ++i) {
branch = branch[pieces[i]];
}
delete branch[last];
}
/**
* Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
* and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
* to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
* [statics](http://mongoosejs.com/docs/guide.html#statics), and
* [methods](http://mongoosejs.com/docs/guide.html#methods).
*
* ####Example:
*
* ```javascript
* const md5 = require('md5');
* const userSchema = new Schema({ email: String });
* class UserClass {
* // `gravatarImage` becomes a virtual
* get gravatarImage() {
* const hash = md5(this.email.toLowerCase());
* return `https://www.gravatar.com/avatar/${hash}`;
* }
*
* // `getProfileUrl()` becomes a document method
* getProfileUrl() {
* return `https://mysite.com/${this.email}`;
* }
*
* // `findByEmail()` becomes a static
* static findByEmail(email) {
* return this.findOne({ email });
* }
* }
*
* // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
* // and a `findByEmail()` static
* userSchema.loadClass(UserClass);
* ```
*
* @param {Function} model
* @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics
*/
Schema.prototype.loadClass = function(model, virtualsOnly) {
if (model === Object.prototype ||
model === Function.prototype ||
model.prototype.hasOwnProperty('$isMongooseModelPrototype')) {
return this;
}
this.loadClass(Object.getPrototypeOf(model));
// Add static methods
if (!virtualsOnly) {
Object.getOwnPropertyNames(model).forEach(function(name) {
if (name.match(/^(length|name|prototype)$/)) {
return;
}
const method = Object.getOwnPropertyDescriptor(model, name);
if (typeof method.value === 'function') {
this.static(name, method.value);
}
}, this);
}
// Add methods and virtuals
Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
if (name.match(/^(constructor)$/)) {
return;
}
const method = Object.getOwnPropertyDescriptor(model.prototype, name);
if (!virtualsOnly) {
if (typeof method.value === 'function') {
this.method(name, method.value);
}
}
if (typeof method.get === 'function') {
this.virtual(name).get(method.get);
}
if (typeof method.set === 'function') {
this.virtual(name).set(method.set);
}
}, this);
return this;
};
/*!
* ignore
*/
Schema.prototype._getSchema = function(path) {
const _this = this;
const pathschema = _this.path(path);
const resultPath = [];
if (pathschema) {
pathschema.$fullPath = path;
return pathschema;
}
function search(parts, schema) {
let p = parts.length + 1;
let foundschema;
let trypath;
while (p--) {
trypath = parts.slice(0, p).join('.');
foundschema = schema.path(trypath);
if (foundschema) {
resultPath.push(trypath);
if (foundschema.caster) {
// array of Mixed?
if (foundschema.caster instanceof MongooseTypes.Mixed) {
foundschema.caster.$fullPath = resultPath.join('.');
return foundschema.caster;
}
// Now that we found the array, we need to check if there
// are remaining document paths to look up for casting.
// Also we need to handle array.$.path since schema.path
// doesn't work for that.
// If there is no foundschema.schema we are dealing with
// a path like array.$
if (p !== parts.length && foundschema.schema) {
let ret;
if (parts[p] === '$' || isArrayFilter(parts[p])) {
if (p + 1 === parts.length) {
// comments.$
return foundschema;
}
// comments.$.comments.$.title
ret = search(parts.slice(p + 1), foundschema.schema);
if (ret) {
ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
!foundschema.schema.$isSingleNested;
}
return ret;
}
// this is the last path of the selector
ret = search(parts.slice(p), foundschema.schema);
if (ret) {
ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
!foundschema.schema.$isSingleNested;
}
return ret;
}
}
foundschema.$fullPath = resultPath.join('.');
return foundschema;
}
}
}
// look for arrays
const parts = path.split('.');
for (let i = 0; i < parts.length; ++i) {
if (parts[i] === '$' || isArrayFilter(parts[i])) {
// Re: gh-5628, because `schema.path()` doesn't take $ into account.
parts[i] = '0';
}
}
return search(parts, _this);
};
/*!
* ignore
*/
Schema.prototype._getPathType = function(path) {
const _this = this;
const pathschema = _this.path(path);
if (pathschema) {
return 'real';
}
function search(parts, schema) {
let p = parts.length + 1,
foundschema,
trypath;
while (p--) {
trypath = parts.slice(0, p).join('.');
foundschema = schema.path(trypath);
if (foundschema) {
if (foundschema.caster) {
// array of Mixed?
if (foundschema.caster instanceof MongooseTypes.Mixed) {
return { schema: foundschema, pathType: 'mixed' };
}
// Now that we found the array, we need to check if there
// are remaining document paths to look up for casting.
// Also we need to handle array.$.path since schema.path
// doesn't work for that.
// If there is no foundschema.schema we are dealing with
// a path like array.$
if (p !== parts.length && foundschema.schema) {
if (parts[p] === '$' || isArrayFilter(parts[p])) {
if (p === parts.length - 1) {
return { schema: foundschema, pathType: 'nested' };
}
// comments.$.comments.$.title
return search(parts.slice(p + 1), foundschema.schema);
}
// this is the last path of the selector
return search(parts.slice(p), foundschema.schema);
}
return {
schema: foundschema,
pathType: foundschema.$isSingleNested ? 'nested' : 'array'
};
}
return { schema: foundschema, pathType: 'real' };
} else if (p === parts.length && schema.nested[trypath]) {
return { schema: schema, pathType: 'nested' };
}
}
return { schema: foundschema || schema, pathType: 'undefined' };
}
// look for arrays
return search(path.split('.'), _this);
};
/*!
* ignore
*/
function isArrayFilter(piece) {
return piece.startsWith('$[') && piece.endsWith(']');
}
/*!
* Module exports.
*/
module.exports = exports = Schema;
// require down here because of reference issues
/**
* The various built-in Mongoose Schema Types.
*
* ####Example:
*
* var mongoose = require('mongoose');
* var ObjectId = mongoose.Schema.Types.ObjectId;
*
* ####Types:
*
* - [String](#schema-string-js)
* - [Number](#schema-number-js)
* - [Boolean](#schema-boolean-js) | Bool
* - [Array](#schema-array-js)
* - [Buffer](#schema-buffer-js)
* - [Date](#schema-date-js)
* - [ObjectId](#schema-objectid-js) | Oid
* - [Mixed](#schema-mixed-js)
*
* Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
*
* var Mixed = mongoose.Schema.Types.Mixed;
* new mongoose.Schema({ _user: Mixed })
*
* @api public
*/
Schema.Types = MongooseTypes = require('./schema/index');
/*!
* ignore
*/
exports.ObjectId = MongooseTypes.ObjectId;
| 1 | 14,049 | `this.getFilter()` won't work on `pre('save')`. Perhaps make this `toySchema.pre(['updateOne', 'findOneAndUpdate'])`? | Automattic-mongoose | js |
@@ -58,9 +58,12 @@ public class TracerTest {
public void shouldBeAbleToCreateATracer() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
+ long timeStamp = 1593493828L;
try (Span span = tracer.getCurrentContext().createSpan("parent")) {
span.setAttribute("cheese", "gouda");
+ span.addEvent("Grating cheese");
+ span.addEvent("Melting cheese", timeStamp);
span.setStatus(Status.NOT_FOUND);
}
| 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
package org.openqa.selenium.remote.tracing.opentelemetry;
import io.opentelemetry.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.TracerSdkProvider;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SimpleSpansProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import org.junit.Test;
import org.openqa.selenium.grid.web.CombinedHandler;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.http.Routable;
import org.openqa.selenium.remote.http.Route;
import org.openqa.selenium.remote.tracing.HttpTracing;
import org.openqa.selenium.remote.tracing.Span;
import org.openqa.selenium.remote.tracing.Status;
import org.openqa.selenium.remote.tracing.Tracer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.openqa.selenium.remote.http.HttpMethod.GET;
import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;
public class TracerTest {
@Test
public void shouldBeAbleToCreateATracer() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span span = tracer.getCurrentContext().createSpan("parent")) {
span.setAttribute("cheese", "gouda");
span.setStatus(Status.NOT_FOUND);
}
Set<SpanData> values = allSpans.stream()
.filter(data -> data.getAttributes().containsKey("cheese"))
.collect(Collectors.toSet());
assertThat(values).hasSize(1);
assertThat(values).element(0)
.extracting(SpanData::getStatus).isEqualTo(io.opentelemetry.trace.Status.NOT_FOUND);
assertThat(values).element(0)
.extracting(el -> el.getAttributes().get("cheese").getStringValue()).isEqualTo("gouda");
}
@Test
public void nestingSpansInTheSameThreadShouldWork() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
try (Span child = parent.createSpan("child")) {
child.setAttribute("cheese", "camembert");
}
}
SpanData parent = allSpans.stream().filter(data -> data.getName().equals("parent"))
.findFirst().orElseThrow(NoSuchElementException::new);
SpanData child = allSpans.stream().filter(data -> data.getName().equals("child"))
.findFirst().orElseThrow(NoSuchElementException::new);
assertThat(child.getParentSpanId()).isEqualTo(parent.getSpanId());
}
@Test
public void nestingSpansFromDifferentThreadsIsFineToo() throws ExecutionException, InterruptedException {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
Future<?> future = Executors.newSingleThreadExecutor().submit(() -> {
try (Span child = parent.createSpan("child")) {
child.setAttribute("cheese", "gruyere");
}
});
future.get();
}
SpanData parent = allSpans.stream().filter(data -> data.getName().equals("parent"))
.findFirst().orElseThrow(NoSuchElementException::new);
SpanData child = allSpans.stream().filter(data -> data.getName().equals("child"))
.findFirst().orElseThrow(NoSuchElementException::new);
assertThat(child.getParentSpanId()).isEqualTo(parent.getSpanId());
}
@Test
public void currentSpanIsKeptOnTracerCorrectlyWithinSameThread() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
try (Span child = parent.createSpan("child")) {
assertThat(child.getId()).isEqualTo(tracer.getCurrentContext().getId());
}
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
}
}
@Test
public void currentSpanIsKeptOnTracerCorrectlyBetweenThreads() throws ExecutionException, InterruptedException {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
Future<?> future = Executors.newSingleThreadExecutor().submit(() -> {
Span child = null;
try {
child = parent.createSpan("child");
assertThat(child.getId()).isEqualTo(tracer.getCurrentContext().getId());
} finally {
assert child != null;
child.close();
}
// At this point, the parent span is undefind, but shouldn't be null
assertThat(parent.getId()).isNotEqualTo(tracer.getCurrentContext().getId());
assertThat(child.getId()).isNotEqualTo(tracer.getCurrentContext().getId());
assertThat(tracer.getCurrentContext().getId()).isNotNull();
});
future.get();
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
}
}
@Test
public void cleverShenanigansRepresentingWhatWeSeeInTheRouter() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
CombinedHandler handler = new CombinedHandler();
ExecutorService executors = Executors.newCachedThreadPool();
handler.addHandler(Route.get("/status").to(() -> req -> {
try (Span span = HttpTracing.newSpanAsChildOf(tracer, req, "status")) {
executors.submit(span.wrap(() -> new HashSet<>(Arrays.asList("cheese", "peas")))).get();
CompletableFuture<String> toReturn = new CompletableFuture<>();
executors.submit(() -> {
try {
HttpRequest cheeseReq = new HttpRequest(GET, "/cheeses");
HttpTracing.inject(tracer, span, cheeseReq);
handler.execute(cheeseReq);
toReturn.complete("nom, nom, nom");
} catch (RuntimeException e) {
toReturn.completeExceptionally(e);
}
});
toReturn.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
return new HttpResponse();
}));
handler.addHandler(Route.get("/cheeses").to(() -> req -> new HttpResponse()));
Routable routable = handler.with(delegate -> req -> {
try (Span span = newSpanAsChildOf(tracer, req, "httpclient.execute")) {
return delegate.execute(req);
}
});
routable.execute(new HttpRequest(GET, "/"));
}
private Tracer createTracer(List<SpanData> exportTo) {
TracerSdkProvider provider = OpenTelemetrySdk.getTracerProvider();
provider.addSpanProcessor(SimpleSpansProcessor.create(new SpanExporter() {
@Override
public ResultCode export(Collection<SpanData> spans) {
exportTo.addAll(spans);
return ResultCode.SUCCESS;
}
@Override public ResultCode flush() {
return ResultCode.SUCCESS;
}
@Override
public void shutdown() {
}
}));
io.opentelemetry.trace.Tracer otTracer = provider.get("get");
return new OpenTelemetryTracer(
otTracer,
OpenTelemetry.getPropagators().getHttpTextFormat());
}
}
| 1 | 17,762 | Break out tests for events into their own tests rather than placing them in other ones. That makes it easier for us to figure out where problems lie and to do a TDD-driven implementation over new APIs. | SeleniumHQ-selenium | java |
@@ -67,18 +67,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal
if (result.IsCancelled)
{
- // Send a FIN
- _log.ConnectionWriteFin(_connectionId);
-
- using (var shutdownReq = new UvShutdownReq(_log))
- {
- shutdownReq.Init(_thread);
- var shutdownResult = await shutdownReq.ShutdownAsync(_socket);
-
- _log.ConnectionWroteFin(_connectionId, shutdownResult.Status);
- }
-
- // Ensure no data is written after uv_shutdown
break;
}
| 1 | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking;
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal
{
public class LibuvOutputConsumer
{
private readonly LibuvThread _thread;
private readonly UvStreamHandle _socket;
private readonly string _connectionId;
private readonly ILibuvTrace _log;
private readonly IPipeReader _pipe;
public LibuvOutputConsumer(
IPipeReader pipe,
LibuvThread thread,
UvStreamHandle socket,
string connectionId,
ILibuvTrace log)
{
_pipe = pipe;
_thread = thread;
_socket = socket;
_connectionId = connectionId;
_log = log;
}
public async Task WriteOutputAsync()
{
var pool = _thread.WriteReqPool;
while (true)
{
var result = await _pipe.ReadAsync();
var buffer = result.Buffer;
var consumed = buffer.End;
try
{
if (!buffer.IsEmpty)
{
var writeReq = pool.Allocate();
try
{
var writeResult = await writeReq.WriteAsync(_socket, buffer);
LogWriteInfo(writeResult.Status, writeResult.Error);
if (writeResult.Error != null)
{
consumed = buffer.Start;
throw writeResult.Error;
}
}
finally
{
// Make sure we return the writeReq to the pool
pool.Return(writeReq);
}
}
if (result.IsCancelled)
{
// Send a FIN
_log.ConnectionWriteFin(_connectionId);
using (var shutdownReq = new UvShutdownReq(_log))
{
shutdownReq.Init(_thread);
var shutdownResult = await shutdownReq.ShutdownAsync(_socket);
_log.ConnectionWroteFin(_connectionId, shutdownResult.Status);
}
// Ensure no data is written after uv_shutdown
break;
}
if (buffer.IsEmpty && result.IsCompleted)
{
break;
}
}
finally
{
_pipe.Advance(consumed);
}
}
}
private void LogWriteInfo(int status, Exception error)
{
if (error == null)
{
_log.ConnectionWriteCallback(_connectionId, status);
}
else
{
// Log connection resets at a lower (Debug) level.
if (status == LibuvConstants.ECONNRESET)
{
_log.ConnectionReset(_connectionId);
}
else
{
_log.ConnectionError(_connectionId, error);
}
}
}
}
}
| 1 | 13,141 | I think this is the only place where we use `UvShutdownReq`. Can we remove the type altogether? Or do you prefer to keep it around? | aspnet-KestrelHttpServer | .cs |
@@ -248,7 +248,7 @@ func (a *Agent) Attest() error {
// Configure TLS
// TODO: Pick better options here
tlsConfig := &tls.Config{
- RootCAs: a.Config.TrustBundle,
+ InsecureSkipVerify:true,
}
dialCreds := grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))
conn, err := grpc.Dial(a.Config.ServerAddress.String(), dialCreds) | 1 | package agent
import (
"context"
"crypto/ecdsa"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path"
"github.com/go-kit/kit/log"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-plugin"
"github.com/spiffe/go-spiffe/spiffe"
"github.com/spiffe/go-spiffe/uri"
"github.com/spiffe/sri/helpers"
"github.com/spiffe/sri/pkg/agent/endpoints/server"
"github.com/spiffe/sri/pkg/agent/keymanager"
"github.com/spiffe/sri/pkg/agent/nodeattestor"
"github.com/spiffe/sri/pkg/agent/workloadattestor"
"github.com/spiffe/sri/pkg/api/node"
"github.com/spiffe/sri/pkg/common/plugin"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
var (
PluginTypeMap = map[string]plugin.Plugin{
"KeyManager": &keymanager.KeyManagerPlugin{},
"NodeAttestor": &nodeattestor.NodeAttestorPlugin{},
"WorkloadAttestor": &workloadattestor.WorkloadAttestorPlugin{},
}
MaxPlugins = map[string]int{
"KeyManager": 1,
"NodeAttestor": 1,
"WorkloadAttestor": 1,
}
)
type Config struct {
// Address to bind the workload api to
BindAddress net.Addr
// Distinguished Name to use for all CSRs
CertDN *pkix.Name
// Directory to store runtime data
DataDir string
// Directory for plugin configs
PluginDir string
Logger log.Logger
// Address of SPIRE server
ServerAddress net.Addr
// A channel for receiving errors from agent goroutines
ErrorCh chan error
// A channel to trigger agent shutdown
ShutdownCh chan struct{}
// Trust domain and associated CA bundle
TrustDomain string
TrustBundle *x509.CertPool
}
type Agent struct {
BaseSVID []byte
key *ecdsa.PrivateKey
BaseSVIDTTL int32
Catalog *helpers.PluginCatalog
Config *Config
grpcServer *grpc.Server
}
// Run the agent
// This method initializes the agent, including its plugins,
// and then blocks on the main event loop.
func (a *Agent) Run() error {
err := a.initPlugins()
if err != nil {
return err
}
err = a.bootstrap()
if err != nil {
return err
}
err = a.initEndpoints()
if err != nil {
return err
}
// Main event loop
a.Config.Logger.Log("msg", "SPIRE Agent is now running")
for {
select {
case err = <-a.Config.ErrorCh:
return err
case <-a.Config.ShutdownCh:
a.grpcServer.GracefulStop()
return <-a.Config.ErrorCh
}
}
}
func (a *Agent) initPlugins() error {
a.Config.Logger.Log("msg", "Starting plugins")
// TODO: Feed log level through/fix logging...
pluginLogger := hclog.New(&hclog.LoggerOptions{
Name: "pluginLogger",
Level: hclog.LevelFromString("DEBUG"),
})
a.Catalog = &helpers.PluginCatalog{
PluginConfDirectory: a.Config.PluginDir,
Logger: pluginLogger,
}
a.Catalog.SetMaxPluginTypeMap(MaxPlugins)
a.Catalog.SetPluginTypeMap(PluginTypeMap)
err := a.Catalog.Run()
if err != nil {
return err
}
return nil
}
func (a *Agent) initEndpoints() error {
a.Config.Logger.Log("msg", "Starting the workload API")
svc := server.NewService(a.Catalog, a.Config.ErrorCh)
endpoints := server.Endpoints{
PluginInfoEndpoint: server.MakePluginInfoEndpoint(svc),
StopEndpoint: server.MakeStopEndpoint(svc),
}
a.grpcServer = grpc.NewServer()
handler := server.MakeGRPCServer(endpoints)
sriplugin.RegisterServerServer(a.grpcServer, handler)
listener, err := net.Listen(a.Config.BindAddress.Network(), a.Config.BindAddress.String())
if err != nil {
return fmt.Errorf("Error creating GRPC listener: %s", err)
}
go func() {
a.Config.ErrorCh <- a.grpcServer.Serve(listener)
}()
return nil
}
func (a *Agent) bootstrap() error {
a.Config.Logger.Log("msg", "Bootstrapping SPIRE agent")
// Look up the key manager plugin
pluginClients := a.Catalog.GetPluginsByType("KeyManager")
if len(pluginClients) != 1 {
return fmt.Errorf("Expected only one key manager plugin, found %i", len(pluginClients))
}
keyManager := pluginClients[0].(keymanager.KeyManager)
// Fetch or generate private key
res, err := keyManager.FetchPrivateKey(&keymanager.FetchPrivateKeyRequest{})
if err != nil {
return err
}
if len(res.PrivateKey) > 0 {
key, err := x509.ParseECPrivateKey(res.PrivateKey)
if err != nil {
return err
}
err = a.LoadBaseSVID()
if err != nil {
return err
}
a.key = key
} else {
if a.BaseSVID != nil {
a.Config.Logger.Log("msg", "Certificate configured but no private key found!")
}
a.Config.Logger.Log("msg", "Generating private key for new base SVID")
res, err := keyManager.GenerateKeyPair(&keymanager.GenerateKeyPairRequest{})
if err != nil {
return fmt.Errorf("Failed to generate private key: %s", err)
}
key, err := x509.ParseECPrivateKey(res.PrivateKey)
if err != nil {
return err
}
a.key = key
// If we're here, we need to Attest/Re-Attest
return a.Attest()
}
a.Config.Logger.Log("msg", "Bootstrapping done")
return nil
}
// Attest the agent, obtain a new Base SVID
func (a *Agent) Attest() error {
a.Config.Logger.Log("msg", "Preparing to attest against %s", a.Config.ServerAddress.String())
// Look up the node attestor plugin
pluginClients := a.Catalog.GetPluginsByType("NodeAttestor")
if len(pluginClients) != 1 {
return fmt.Errorf("Expected only one node attestor plugin, found %i", len(pluginClients))
}
attestor := pluginClients[0].(nodeattestor.NodeAttestor)
pluginResponse, err := attestor.FetchAttestationData(&nodeattestor.FetchAttestationDataRequest{})
if err != nil {
return fmt.Errorf("Failed to get attestation data from plugin: %s", err)
}
// Parse the SPIFFE ID, form a CSR with it
id, err := url.Parse(pluginResponse.SpiffeId)
if err != nil {
return fmt.Errorf("Failed to form SPIFFE ID: %s", err)
}
csr, err := a.GenerateCSR(id)
if err != nil {
return fmt.Errorf("Failed to generate CSR for attestation: %s", err)
}
// Configure TLS
// TODO: Pick better options here
tlsConfig := &tls.Config{
RootCAs: a.Config.TrustBundle,
}
dialCreds := grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))
conn, err := grpc.Dial(a.Config.ServerAddress.String(), dialCreds)
if err != nil {
return fmt.Errorf("Could not connect to: %v", err)
}
defer conn.Close()
c := node.NewNodeClient(conn)
// Perform attestation
req := &node.FetchBaseSVIDRequest{
AttestedData: pluginResponse.AttestedData,
Csr: csr,
}
serverResponse, err := c.FetchBaseSVID(context.Background(), req)
if err != nil {
return fmt.Errorf("Failed attestation against spire server: %s", err)
}
// Pull base SVID out of the response
svids := serverResponse.SvidUpdate.Svids
if len(svids) > 1 {
a.Config.Logger.Log("msg", "More than one SVID received during attestation!")
}
svid, ok := svids[id.String()]
if !ok {
return fmt.Errorf("Base SVID not found in attestation response")
}
a.BaseSVID = svid.SvidCert
a.BaseSVIDTTL = svid.Ttl
a.StoreBaseSVID()
a.Config.Logger.Log("msg", "Attestation complete")
return nil
}
// Generate a CSR for the given SPIFFE ID
func (a *Agent) GenerateCSR(spiffeID *url.URL) ([]byte, error) {
a.Config.Logger.Log("msg", "Generating a CSR for %s", spiffeID.String())
uriSANs, err := uri.MarshalUriSANs([]string{spiffeID.String()})
if err != nil {
return []byte{}, err
}
uriSANExtension := []pkix.Extension{{
Id: spiffe.OidExtensionSubjectAltName,
Value: uriSANs,
Critical: true,
}}
csrData := &x509.CertificateRequest{
Subject: *a.Config.CertDN,
SignatureAlgorithm: x509.ECDSAWithSHA256,
ExtraExtensions: uriSANExtension,
}
csr, err := x509.CreateCertificateRequest(rand.Reader, csrData, a.key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csr}), nil
}
// Read base SVID from data dir and load it
func (a *Agent) LoadBaseSVID() error {
a.Config.Logger.Log("msg", "Loading base SVID from disk")
certPath := path.Join(a.Config.DataDir, "base_svid.crt")
if _, err := os.Stat(certPath); os.IsNotExist(err) {
a.Config.Logger.Log("msg", "A base SVID could not be found. A new one will be generated")
return nil
}
data, err := ioutil.ReadFile(certPath)
if err != nil {
return fmt.Errorf("Could not read Base SVID at path %s: %s", certPath, err)
}
// Sanity check
_, err = x509.ParseCertificate(data)
if err != nil {
return fmt.Errorf("Certificate at %s could not be understood: %s", certPath, err)
}
a.BaseSVID = data
return nil
}
// Write base SVID to storage dir
func (a *Agent) StoreBaseSVID() {
certPath := path.Join(a.Config.DataDir, "base_svid.crt")
f, err := os.Create(certPath)
defer f.Close()
if err != nil {
a.Config.Logger.Log("msg", "Unable to store Base SVID at path %s!", certPath)
return
}
err = pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: a.BaseSVID})
if err != nil {
a.Config.Logger.Log("msg", "Unable to store Base SVID at path %s!", certPath)
}
return
}
| 1 | 8,388 | I think we can get this to work by passing in the root ca cert fixture that upstream ca is using | spiffe-spire | go |
@@ -219,6 +219,18 @@ static batch_job_id_t batch_job_condor_wait (struct batch_queue * q, struct batc
}
}
+ time_t current;
+ struct tm tm;
+
+ /* Obtain current year, in case HTCondor log lines do not provide a year.
+ Note that this fallback may give the incorrect year for jobs that run
+ when the year turns. However, we just need some value to give to a
+ mktime below, and the current year is preferable than some fixed value.
+ */
+ time(¤t);
+ tm = *localtime(¤t);
+ int current_year = tm.tm_year + 1900;
+
while(1) {
/*
Note: clearerr is necessary to clear any cached end-of-file condition, | 1 | /*
Copyright (C) 2017- The University of Notre Dame
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/
#include "batch_job.h"
#include "batch_job_internal.h"
#include "debug.h"
#include "itable.h"
#include "path.h"
#include "process.h"
#include "stringtools.h"
#include "xxmalloc.h"
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
static int setup_condor_wrapper(const char *wrapperfile)
{
FILE *file;
if(access(wrapperfile, R_OK | X_OK) == 0)
return 0;
file = fopen(wrapperfile, "w");
if(!file)
return -1;
fprintf(file, "#!/bin/sh\n");
fprintf(file, "eval \"$@\"\n");
fprintf(file, "exit $?\n");
fclose(file);
chmod(wrapperfile, 0755);
return 0;
}
static char *blacklisted_expression(struct batch_queue *q) {
const char *blacklisted = hash_table_lookup(q->options, "workers-blacklisted");
static char *last_blacklist = NULL;
if(!blacklisted)
return NULL;
/* print blacklist only when it changes. */
if(!last_blacklist || strcmp(last_blacklist, blacklisted) != 0) {
debug(D_BATCH, "Blacklisted hostnames: %s\n", blacklisted);
}
buffer_t b;
buffer_init(&b);
char *blist = xxstrdup(blacklisted);
/* strsep updates blist, so we keep the original pointer in binit so we can free it later */
char *binit = blist;
char *sep = "";
char *hostname;
while((hostname = strsep(&blist, " "))) {
buffer_printf(&b, "%s(machine != \"%s\")", sep, hostname);
sep = " && ";
}
char *result = xxstrdup(buffer_tostring(&b));
free(binit);
buffer_free(&b);
if(last_blacklist) {
free(last_blacklist);
}
last_blacklist = xxstrdup(blacklisted);
return result;
}
static batch_job_id_t batch_job_condor_submit (struct batch_queue *q, const char *cmd, const char *extra_input_files, const char *extra_output_files, struct jx *envlist, const struct rmsummary *resources )
{
FILE *file;
int njobs;
int jobid;
const char *options = hash_table_lookup(q->options, "batch-options");
if(setup_condor_wrapper("condor.sh") < 0) {
debug(D_BATCH, "could not create condor.sh: %s", strerror(errno));
return -1;
}
file = fopen("condor.submit", "w");
if(!file) {
debug(D_BATCH, "could not create condor.submit: %s", strerror(errno));
return -1;
}
fprintf(file, "universe = vanilla\n");
fprintf(file, "executable = condor.sh\n");
char *escaped = string_escape_condor(cmd);
fprintf(file, "arguments = %s\n", escaped);
free(escaped);
if(extra_input_files)
fprintf(file, "transfer_input_files = %s\n", extra_input_files);
// Note that we do not use transfer_output_files, because that causes the job
// to get stuck in a system hold if the files are not created.
fprintf(file, "should_transfer_files = yes\n");
fprintf(file, "when_to_transfer_output = on_exit\n");
fprintf(file, "notification = never\n");
fprintf(file, "copy_to_spool = true\n");
fprintf(file, "transfer_executable = true\n");
fprintf(file, "keep_claim_idle = 30\n");
fprintf(file, "log = %s\n", q->logfile);
fprintf(file, "+JobMaxSuspendTime = 0\n");
const char *c_req = batch_queue_get_option(q, "condor-requirements");
char *bexp = blacklisted_expression(q);
if(c_req && bexp) {
fprintf(file, "requirements = (%s) && (%s)\n", c_req, bexp);
} else if(c_req) {
fprintf(file, "requirements = (%s)\n", c_req);
} else if(bexp) {
fprintf(file, "requirements = (%s)\n", bexp);
}
if(bexp)
free(bexp);
/*
Getting environment variables formatted for a condor submit
file is very hairy, due to some strange quoting rules.
To avoid problems, we simply export vars to the environment,
and then tell condor getenv=true, which pulls in the environment.
*/
fprintf(file, "getenv = true\n");
if(envlist) {
jx_export(envlist);
}
/* set same deafults as condor_submit_workers */
int64_t cores = 1;
int64_t memory = 1024;
int64_t disk = 1024;
if(resources) {
cores = resources->cores > -1 ? resources->cores : cores;
memory = resources->memory > -1 ? resources->memory : memory;
disk = resources->disk > -1 ? resources->disk : disk;
}
/* convert disk to KB */
disk *= 1024;
if(batch_queue_get_option(q, "autosize")) {
fprintf(file, "request_cpus = ifThenElse(%" PRId64 " > TotalSlotCpus, %" PRId64 ", TotalSlotCpus)\n", cores, cores);
fprintf(file, "request_memory = ifThenElse(%" PRId64 " > TotalSlotMemory, %" PRId64 ", TotalSlotMemory)\n", memory, memory);
fprintf(file, "request_disk = ifThenElse((%" PRId64 ") > TotalSlotDisk, (%" PRId64 "), TotalSlotDisk)\n", disk, disk);
}
else {
fprintf(file, "request_cpus = %" PRId64 "\n", cores);
fprintf(file, "request_memory = %" PRId64 "\n", memory);
fprintf(file, "request_disk = %" PRId64 "\n", disk);
}
if(options) {
char *opt_expanded = malloc(2 * strlen(options) + 1);
string_replace_backslash_codes(options, opt_expanded);
fprintf(file, "%s\n", opt_expanded);
free(opt_expanded);
}
fprintf(file, "queue\n");
fclose(file);
file = popen("condor_submit condor.submit", "r");
if(!file)
return -1;
char line[BATCH_JOB_LINE_MAX];
while(fgets(line, sizeof(line), file)) {
if(sscanf(line, "%d job(s) submitted to cluster %d", &njobs, &jobid) == 2) {
pclose(file);
debug(D_BATCH, "job %d submitted to condor", jobid);
struct batch_job_info *info;
info = malloc(sizeof(*info));
memset(info, 0, sizeof(*info));
info->submitted = time(0);
itable_insert(q->job_table, jobid, info);
return jobid;
}
}
pclose(file);
debug(D_BATCH, "failed to submit job to condor!");
return -1;
}
static batch_job_id_t batch_job_condor_wait (struct batch_queue * q, struct batch_job_info * info_out, time_t stoptime)
{
static FILE *logfile = 0;
if(!logfile) {
logfile = fopen(q->logfile, "r");
if(!logfile) {
debug(D_NOTICE, "couldn't open logfile %s: %s\n", q->logfile, strerror(errno));
return -1;
}
}
while(1) {
/*
Note: clearerr is necessary to clear any cached end-of-file condition,
otherwise some implementations of fgets (i.e. darwin) will read to end
of file once and then never look for any more data.
*/
clearerr(logfile);
char line[BATCH_JOB_LINE_MAX];
while(fgets(line, sizeof(line), logfile)) {
int type, proc, subproc;
batch_job_id_t jobid;
time_t current;
struct tm tm;
struct batch_job_info *info;
int logcode, exitcode;
/*
HTCondor job log lines come in one of two flavors:
005 (312.000.000) 2020-03-28 23:01:04
or
005 (312.000.000) 03/28 23:01:02
*/
tm.tm_year = 2020;
if((sscanf(line, "%d (%" SCNbjid ".%d.%d) %d/%d %d:%d:%d",
&type, &jobid, &proc, &subproc, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 9) ||
(sscanf(line, "%d (%" SCNbjid ".%d.%d) %d-%d-%d %d:%d:%d",
&type, &jobid, &proc, &subproc, &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 10)) {
tm.tm_year = tm.tm_year - 1900;
tm.tm_isdst = 0;
current = mktime(&tm);
info = itable_lookup(q->job_table, jobid);
if(!info) {
info = malloc(sizeof(*info));
memset(info, 0, sizeof(*info));
itable_insert(q->job_table, jobid, info);
}
debug(D_BATCH, "line: %s", line);
if(type == 0) {
info->submitted = current;
} else if(type == 1) {
info->started = current;
debug(D_BATCH, "job %" PRIbjid " running now", jobid);
} else if(type == 9) {
itable_remove(q->job_table, jobid);
info->finished = current;
info->exited_normally = 0;
info->exit_signal = SIGKILL;
debug(D_BATCH, "job %" PRIbjid " was removed", jobid);
memcpy(info_out, info, sizeof(*info));
free(info);
return jobid;
} else if(type == 5) {
itable_remove(q->job_table, jobid);
info->finished = current;
fgets(line, sizeof(line), logfile);
if(sscanf(line, " (%d) Normal termination (return value %d)", &logcode, &exitcode) == 2) {
debug(D_BATCH, "job %" PRIbjid " completed normally with status %d.", jobid, exitcode);
info->exited_normally = 1;
info->exit_code = exitcode;
} else if(sscanf(line, " (%d) Abnormal termination (signal %d)", &logcode, &exitcode) == 2) {
debug(D_BATCH, "job %" PRIbjid " completed abnormally with signal %d.", jobid, exitcode);
info->exited_normally = 0;
info->exit_signal = exitcode;
} else {
debug(D_BATCH, "job %" PRIbjid " completed with unknown status.", jobid);
info->exited_normally = 0;
info->exit_signal = 0;
}
memcpy(info_out, info, sizeof(*info));
free(info);
return jobid;
}
}
}
if(itable_size(q->job_table) <= 0)
return 0;
if(stoptime != 0 && time(0) >= stoptime)
return -1;
if(process_pending())
return -1;
sleep(1);
}
return -1;
}
static int batch_job_condor_remove (struct batch_queue *q, batch_job_id_t jobid)
{
char *command = string_format("condor_rm %" PRIbjid, jobid);
debug(D_BATCH, "%s", command);
FILE *file = popen(command, "r");
free(command);
if(!file) {
debug(D_BATCH, "condor_rm failed");
return 0;
} else {
char buffer[1024];
while (fread(buffer, sizeof(char), sizeof(buffer)/sizeof(char), file) > 0)
;
pclose(file);
return 1;
}
}
static int batch_queue_condor_create (struct batch_queue *q)
{
strncpy(q->logfile, "condor.logfile", sizeof(q->logfile));
batch_queue_set_feature(q, "output_directories", NULL);
batch_queue_set_feature(q, "batch_log_name", "%s.condorlog");
batch_queue_set_feature(q, "autosize", "yes");
return 0;
}
batch_queue_stub_free(condor);
batch_queue_stub_port(condor);
batch_queue_stub_option_update(condor);
batch_fs_stub_chdir(condor);
batch_fs_stub_getcwd(condor);
batch_fs_stub_mkdir(condor);
batch_fs_stub_putfile(condor);
batch_fs_stub_rename(condor);
batch_fs_stub_stat(condor);
batch_fs_stub_unlink(condor);
const struct batch_queue_module batch_queue_condor = {
BATCH_QUEUE_TYPE_CONDOR,
"condor",
batch_queue_condor_create,
batch_queue_condor_free,
batch_queue_condor_port,
batch_queue_condor_option_update,
{
batch_job_condor_submit,
batch_job_condor_wait,
batch_job_condor_remove,
},
{
batch_fs_condor_chdir,
batch_fs_condor_getcwd,
batch_fs_condor_mkdir,
batch_fs_condor_putfile,
batch_fs_condor_rename,
batch_fs_condor_stat,
batch_fs_condor_unlink,
},
};
/* vim: set noexpandtab tabstop=4: */
| 1 | 14,834 | Just occurred to me to ask: is the condor log date in localtime or UTC? | cooperative-computing-lab-cctools | c |
@@ -686,7 +686,18 @@ public enum Varbits
/**
* 1 is true, 0 is false.
*/
- GAUNTLET_ENTERED(9178);
+ GAUNTLET_ENTERED(9178),
+
+ /**
+ * 1 if full of Mushrooms, 0 is empty.
+ */
+ MUSHY_PIT(5809),
+
+ /**
+ * Current location of Sulliuscep tree.
+ */
+ SULLIUSCEP_LOCATION(5808);
+
/**
* The raw varbit ID. | 1 | /*
* Copyright (c) 2017, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.api;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* An enumeration of local client variables.
*/
@AllArgsConstructor
@Getter
public enum Varbits
{
/*
* If chatbox is transparent or not
*/
TRANSPARENT_CHATBOX(4608),
/*
* If the player has an active stamina potion effect or not
*/
RUN_SLOWED_DEPLETION_ACTIVE(25),
/**
* If scrollbar in resizable mode chat is on the left
*/
CHAT_SCROLLBAR_ON_LEFT(6374),
/**
* Grand Exchange
*/
GRAND_EXCHANGE_PRICE_PER_ITEM(4398),
/**
* Runepouch
*/
RUNE_POUCH_RUNE1(29),
RUNE_POUCH_RUNE2(1622),
RUNE_POUCH_RUNE3(1623),
RUNE_POUCH_AMOUNT1(1624),
RUNE_POUCH_AMOUNT2(1625),
RUNE_POUCH_AMOUNT3(1626),
/**
* Prayers
*/
QUICK_PRAYER(4103),
PRAYER_THICK_SKIN(4104),
PRAYER_BURST_OF_STRENGTH(4105),
PRAYER_CLARITY_OF_THOUGHT(4106),
PRAYER_SHARP_EYE(4122),
PRAYER_MYSTIC_WILL(4123),
PRAYER_ROCK_SKIN(4107),
PRAYER_SUPERHUMAN_STRENGTH(4108),
PRAYER_IMPROVED_REFLEXES(4109),
PRAYER_RAPID_RESTORE(4110),
PRAYER_RAPID_HEAL(4111),
PRAYER_PROTECT_ITEM(4112),
PRAYER_HAWK_EYE(4124),
PRAYER_MYSTIC_LORE(4125),
PRAYER_STEEL_SKIN(4113),
PRAYER_ULTIMATE_STRENGTH(4114),
PRAYER_INCREDIBLE_REFLEXES(4115),
PRAYER_PROTECT_FROM_MAGIC(4116),
PRAYER_PROTECT_FROM_MISSILES(4117),
PRAYER_PROTECT_FROM_MELEE(4118),
PRAYER_EAGLE_EYE(4126),
PRAYER_MYSTIC_MIGHT(4127),
PRAYER_RETRIBUTION(4119),
PRAYER_REDEMPTION(4120),
PRAYER_SMITE(4121),
PRAYER_CHIVALRY(4128),
PRAYER_PIETY(4129),
PRAYER_PRESERVE(5466),
PRAYER_RIGOUR(5464),
PRAYER_AUGURY(5465),
/**
* Diary Entries
*/
DIARY_ARDOUGNE_EASY(4458),
DIARY_ARDOUGNE_MEDIUM(4459),
DIARY_ARDOUGNE_HARD(4460),
DIARY_ARDOUGNE_ELITE(4461),
DIARY_DESERT_EASY(4483),
DIARY_DESERT_MEDIUM(4484),
DIARY_DESERT_HARD(4485),
DIARY_DESERT_ELITE(4486),
DIARY_FALADOR_EASY(4462),
DIARY_FALADOR_MEDIUM(4463),
DIARY_FALADOR_HARD(4464),
DIARY_FALADOR_ELITE(4465),
DIARY_FREMENNIK_EASY(4491),
DIARY_FREMENNIK_MEDIUM(4492),
DIARY_FREMENNIK_HARD(4493),
DIARY_FREMENNIK_ELITE(4494),
DIARY_KANDARIN_EASY(4475),
DIARY_KANDARIN_MEDIUM(4476),
DIARY_KANDARIN_HARD(4477),
DIARY_KANDARIN_ELITE(4478),
DIARY_KARAMJA_EASY(3578),
DIARY_KARAMJA_MEDIUM(3599),
DIARY_KARAMJA_HARD(3611),
DIARY_KARAMJA_ELITE(4566),
DIARY_KOUREND_EASY(7925),
DIARY_KOUREND_MEDIUM(7926),
DIARY_KOUREND_HARD(7927),
DIARY_KOUREND_ELITE(7928),
DIARY_LUMBRIDGE_EASY(4495),
DIARY_LUMBRIDGE_MEDIUM(4496),
DIARY_LUMBRIDGE_HARD(4497),
DIARY_LUMBRIDGE_ELITE(4498),
DIARY_MORYTANIA_EASY(4487),
DIARY_MORYTANIA_MEDIUM(4488),
DIARY_MORYTANIA_HARD(4489),
DIARY_MORYTANIA_ELITE(4490),
DIARY_VARROCK_EASY(4479),
DIARY_VARROCK_MEDIUM(4480),
DIARY_VARROCK_HARD(4481),
DIARY_VARROCK_ELITE(4482),
DIARY_WESTERN_EASY(4471),
DIARY_WESTERN_MEDIUM(4472),
DIARY_WESTERN_HARD(4473),
DIARY_WESTERN_ELITE(4474),
DIARY_WILDERNESS_EASY(4466),
DIARY_WILDERNESS_MEDIUM(4467),
DIARY_WILDERNESS_HARD(4468),
DIARY_WILDERNESS_ELITE(4469),
/**
* Kourend house favours
*/
KOUREND_FAVOR_ARCEUUS(4896),
KOUREND_FAVOR_HOSIDIUS(4895),
KOUREND_FAVOR_LOVAKENGJ(4898),
KOUREND_FAVOR_PISCARILIUS(4899),
KOUREND_FAVOR_SHAYZIEN(4894),
/**
* Equipped weapon type
*/
EQUIPPED_WEAPON_TYPE(357),
/**
* Defensive casting mode
*/
DEFENSIVE_CASTING_MODE(2668),
/**
* Options
*/
SIDE_PANELS(4607),
/**
* Herbiboar Trails
*/
HB_TRAIL_31303(5737),
HB_TRAIL_31306(5738),
HB_TRAIL_31309(5739),
HB_TRAIL_31312(5740),
HB_TRAIL_31315(5741),
HB_TRAIL_31318(5742),
HB_TRAIL_31321(5743),
HB_TRAIL_31324(5744),
HB_TRAIL_31327(5745),
HB_TRAIL_31330(5746),
HB_TRAIL_31333(5768),
HB_TRAIL_31336(5769),
HB_TRAIL_31339(5770),
HB_TRAIL_31342(5771),
HB_TRAIL_31345(5772),
HB_TRAIL_31348(5773),
HB_TRAIL_31351(5774),
HB_TRAIL_31354(5775),
HB_TRAIL_31357(5776),
HB_TRAIL_31360(5777),
HB_TRAIL_31363(5747),
HB_TRAIL_31366(5748),
HB_TRAIL_31369(5749),
HB_TRAIL_31372(5750),
HB_FINISH(5766),
HB_STARTED(5767), //not working
/**
* Barbarian Assault
*/
IN_GAME_BA(3923),
BA_GC(4768),
/**
* 0 = Outside wilderness
* 1 = In wilderness
*/
IN_WILDERNESS(5963),
/**
* Fishing Trawler
* FISHING_TRAWLER_ACTIVITY Expected values: 0-255
*/
FISHING_TRAWLER_ACTIVITY(3377),
/**
* Blast Furnace Bar Dispenser
* <p>
* These are the expected values:
* 0 = No bars being processed
* 1 = Ores are being processed on the conveyor belt, bar dispenser cannot be checked
* 2 = Bars are cooling down
* 3 = Bars can be collected
*/
BAR_DISPENSER(936),
/**
* Motherlode mine sack
*/
SACK_NUMBER(5558),
SACK_UPGRADED(5556),
/**
* Experience tracker
* <p>
* EXPERIENCE_TRACKER_POSITION expected values:
* 0 = Right
* 1 = Middle
* 2 = Left
*/
EXPERIENCE_TRACKER_POSITION(4692),
EXPERIENCE_TRACKER_COUNTER(4697),
EXPERIENCE_TRACKER_PROGRESS_BAR(4698),
/**
* Experience drop color
*/
EXPERIENCE_DROP_COLOR(4695),
/**
* Tithe Farm
*/
TITHE_FARM_SACK_AMOUNT(4900),
TITHE_FARM_SACK_ICON(5370),
TITHE_FARM_POINTS(4893),
/**
* Blast Mine
*/
BLAST_MINE_COAL(4924),
BLAST_MINE_GOLD(4925),
BLAST_MINE_MITHRIL(4926),
BLAST_MINE_ADAMANTITE(4921),
BLAST_MINE_RUNITE(4922),
/**
* Raids
*/
IN_RAID(5432),
TOTAL_POINTS(5431),
PERSONAL_POINTS(5422),
RAID_PARTY_SIZE(5424),
/**
* Theatre of Blood 1=In Party, 2=Inside/Spectator, 3=Dead Spectating
*/
THEATRE_OF_BLOOD(6440),
BLOAT_DOOR(6447),
/**
* Theatre of Blood orb varbits each number stands for the player's health on a scale of 1-27 (I think), 0 hides the orb
*/
THEATRE_OF_BLOOD_ORB_1(6442),
THEATRE_OF_BLOOD_ORB_2(6443),
THEATRE_OF_BLOOD_ORB_3(6444),
THEATRE_OF_BLOOD_ORB_4(6445),
THEATRE_OF_BLOOD_ORB_5(6446),
/**
* Nightmare Zone
*/
NMZ_ABSORPTION(3956),
NMZ_POINTS(3949),
NMZ_OVERLOAD(3955),
/**
* Blast Furnace
*/
BLAST_FURNACE_COPPER_ORE(959),
BLAST_FURNACE_TIN_ORE(950),
BLAST_FURNACE_IRON_ORE(951),
BLAST_FURNACE_COAL(949),
BLAST_FURNACE_MITHRIL_ORE(952),
BLAST_FURNACE_ADAMANTITE_ORE(953),
BLAST_FURNACE_RUNITE_ORE(954),
BLAST_FURNACE_SILVER_ORE(956),
BLAST_FURNACE_GOLD_ORE(955),
BLAST_FURNACE_BRONZE_BAR(941),
BLAST_FURNACE_IRON_BAR(942),
BLAST_FURNACE_STEEL_BAR(943),
BLAST_FURNACE_MITHRIL_BAR(944),
BLAST_FURNACE_ADAMANTITE_BAR(945),
BLAST_FURNACE_RUNITE_BAR(946),
BLAST_FURNACE_SILVER_BAR(948),
BLAST_FURNACE_GOLD_BAR(947),
BLAST_FURNACE_COFFER(5357),
/**
* Pyramid plunder
*/
PYRAMID_PLUNDER_TIMER(2375),
PYRAMID_PLUNDER_ROOM(2374),
/**
* Barrows
*/
BARROWS_KILLED_AHRIM(457),
BARROWS_KILLED_DHAROK(458),
BARROWS_KILLED_GUTHAN(459),
BARROWS_KILLED_KARIL(460),
BARROWS_KILLED_TORAG(461),
BARROWS_KILLED_VERAC(462),
BARROWS_REWARD_POTENTIAL(463),
BARROWS_NPCS_SLAIN(464),
/**
* Spicy stew ingredients
*/
SPICY_STEW_RED_SPICES(1879),
SPICY_STEW_YELLOW_SPICES(1880),
SPICY_STEW_BROWN_SPICES(1881),
SPICY_STEW_ORANGE_SPICES(1882),
/**
* Multicombat area
*/
MULTICOMBAT_AREA(4605),
/**
* In the Wilderness
*/
IN_THE_WILDERNESS(5963),
/**
* Kingdom Management
*/
KINGDOM_FAVOR(72),
KINGDOM_COFFER(74),
/**
* The Hand in the Sand quest status
*/
QUEST_THE_HAND_IN_THE_SAND(1527),
/**
* Daily Tasks (Collection availability)
*/
DAILY_HERB_BOXES_COLLECTED(3961),
DAILY_STAVES_COLLECTED(4539),
DAILY_ESSENCE_COLLECTED(4547),
DAILY_RUNES_COLLECTED(4540),
DAILY_SAND_COLLECTED(4549),
DAILY_ARROWS_STATE(4563),
DAILY_FLAX_STATE(4559),
/**
* This varbit tracks how much bonemeal has been redeemed from Robin
* The player gets 13 for each diary completed above and including Medium, for a maxiumum of 39
*/
DAILY_BONEMEAL_STATE(4543),
DAILY_DYNAMITE_COLLECTED(7939),
/**
* Fairy Ring
*/
FAIR_RING_LAST_DESTINATION(5374),
FAIRY_RING_DIAL_ADCB(3985), //Left dial
FAIRY_RIGH_DIAL_ILJK(3986), //Middle dial
FAIRY_RING_DIAL_PSRQ(3987), //Right dial
/**
* Transmog controllers for farming
*/
FARMING_4771(4771),
FARMING_4772(4772),
FARMING_4773(4773),
FARMING_4774(4774),
FARMING_4775(4775),
FARMING_7904(7904),
FARMING_7905(7905),
FARMING_7906(7906),
FARMING_7907(7907),
FARMING_7908(7908),
FARMING_7909(7909),
FARMING_7910(7910),
FARMING_7911(7911),
/**
* Transmog controllers for grapes
*/
GRAPES_4953(4953),
GRAPES_4954(4954),
GRAPES_4955(4955),
GRAPES_4956(4956),
GRAPES_4957(4957),
GRAPES_4958(4958),
GRAPES_4959(4959),
GRAPES_4960(4960),
GRAPES_4961(4961),
GRAPES_4962(4962),
GRAPES_4963(4963),
GRAPES_4964(4964),
/**
* Automatically weed farming patches
*/
AUTOWEED(5557),
/**
* The varbit that stores the players {@code AccountType}.
*/
ACCOUNT_TYPE(1777),
/**
* Varbit used for Slayer reward points
*/
SLAYER_REWARD_POINTS(4068),
/**
* The varbit that stores the oxygen percentage for player
*/
OXYGEN_LEVEL(5811),
/**
* Corp beast damage
*/
CORP_DAMAGE(999),
/**
* Toggleable slayer unlocks
*/
SUPERIOR_ENABLED(5362),
FOSSIL_ISLAND_WYVERN_DISABLE(6251),
CURRENT_BANK_TAB(4150),
WORLDHOPPER_FAVROITE_1(4597),
WORLDHOPPER_FAVROITE_2(4598),
/**
* Vengeance is active
*/
VENGEANCE_ACTIVE(2450),
/**
* Spell cooldowns
*/
VENGEANCE_COOLDOWN(2451),
/**
* 0 = standard
* 1 = ancients
* 2 = lunars
* 3 = arrceus
**/
SPELLBOOK(4070),
/**
* Amount of items in each bank tab
*/
BANK_TAB_ONE_COUNT(4171),
BANK_TAB_TWO_COUNT(4172),
BANK_TAB_THREE_COUNT(4173),
BANK_TAB_FOUR_COUNT(4174),
BANK_TAB_FIVE_COUNT(4175),
BANK_TAB_SIX_COUNT(4176),
BANK_TAB_SEVEN_COUNT(4177),
BANK_TAB_EIGHT_COUNT(4178),
BANK_TAB_NINE_COUNT(4179),
/**
* Type of GE offer currently being created
* 0 = buy
* 1 = sell
*/
GE_OFFER_CREATION_TYPE(4397),
/**
* Spells being auto-casted
*/
AUTO_CAST_SPELL(276),
/**
* The active tab within the quest interface
*/
QUEST_TAB(8168),
/**
* Explorer ring
*/
EXPLORER_RING_ALCHTYPE(5398),
EXPLORER_RING_TELEPORTS(4552),
EXPLORER_RING_ALCHS(4554),
EXPLORER_RING_RUNENERGY(4553),
/**
* Temple Trekking
*/
TREK_POINTS(1955),
TREK_STARTED(1956),
TREK_EVENT(1958),
TREK_STATUS(6719),
BLOAT_ENTERED_ROOM(6447),
/**
* f2p Quest varbits, these don't hold the completion value.
*/
QUEST_DEMON_SLAYER(2561),
QUEST_GOBLIN_DIPLOMACY(2378),
QUEST_MISTHALIN_MYSTERY(3468),
QUEST_THE_CORSAIR_CURSE(6071),
QUEST_X_MARKS_THE_SPOT(8063),
/**
* member Quest varbits, these don't hold the completion value.
*/
QUEST_ANIMAL_MAGNETISM(3185),
QUEST_BETWEEN_A_ROCK(299),
QUEST_CONTACT(3274),
QUEST_ZOGRE_FLESH_EATERS(487),
QUEST_DARKNESS_OF_HALLOWVALE(2573),
QUEST_DEATH_TO_THE_DORGESHUUN(2258),
QUEST_DESERT_TREASURE(358),
QUEST_DEVIOUS_MINDS(1465),
QUEST_EAGLES_PEAK(2780),
QUEST_ELEMENTAL_WORKSHOP_II(2639),
QUEST_ENAKHRAS_LAMENT(1560),
QUEST_ENLIGHTENED_JOURNEY(2866),
QUEST_THE_EYES_OF_GLOUPHRIE(2497),
QUEST_FAIRYTALE_I_GROWING_PAINS(1803),
QUEST_FAIRYTALE_II_CURE_A_QUEEN(2326),
QUEST_THE_FEUD(334), // 14 = able to pickpocket
QUEST_FORGETTABLE_TALE(822),
QUEST_GARDEN_OF_TRANQUILLITY(961),
QUEST_GHOSTS_AHOY(217),
QUEST_THE_GIANT_DWARF(571),
QUEST_THE_GOLEM(346),
QUEST_HORROR_FROM_THE_DEEP(34),
QUEST_ICTHLARINS_LITTLE_HELPER(418),
QUEST_IN_AID_OF_THE_MYREQUE(1990),
QUEST_THE_LOST_TRIBE(532),
QUEST_LUNAR_DIPLOMACY(2448),
QUEST_MAKING_HISTORY(1383),
QUEST_MOUNTAIN_DAUGHTER(260),
QUEST_MOURNINGS_END_PART_II(1103),
QUEST_MY_ARMS_BIG_ADVENTURE(2790),
QUEST_RATCATCHERS(1404),
QUEST_RECIPE_FOR_DISASTER(1850),
QUEST_RECRUITMENT_DRIVE(657),
QUEST_ROYAL_TROUBLE(2140),
QUEST_THE_SLUG_MENACE(2610),
QUEST_SHADOW_OF_THE_STORM(1372),
QUEST_A_SOULS_BANE(2011),
QUEST_SPIRITS_OF_THE_ELID(1444),
QUEST_SWAN_SONG(2098),
QUEST_A_TAIL_OF_TWO_CATS(1028),
QUEST_TEARS_OF_GUTHIX(451),
QUEST_WANTED(1051),
QUEST_COLD_WAR(3293),
QUEST_THE_FREMENNIK_ISLES(3311),
QUEST_TOWER_OF_LIFE(3337),
QUEST_WHAT_LIES_BELOW(3523),
QUEST_OLAFS_QUEST(3534),
QUEST_ANOTHER_SLICE_OF_HAM(3550),
QUEST_DREAM_MENTOR(3618),
QUEST_GRIM_TALES(2783),
QUEST_KINGS_RANSOM(3888),
QUEST_MONKEY_MADNESS_II(5027),
QUEST_CLIENT_OF_KOUREND(5619),
QUEST_BONE_VOYAGE(5795),
QUEST_THE_QUEEN_OF_THIEVES(6037),
QUEST_THE_DEPTHS_OF_DESPAIR(6027),
QUEST_DRAGON_SLAYER_II(6104),
QUEST_TALE_OF_THE_RIGHTEOUS(6358),
QUEST_A_TASTE_OF_HOPE(6396),
QUEST_MAKING_FRIENDS_WITH_MY_ARM(6528),
QUEST_THE_ASCENT_OF_ARCEUUS(7856),
QUEST_THE_FORSAKEN_TOWER(7796),
//TODO
QUEST_SONG_OF_THE_ELVES(7796),
/**
* mini-quest varbits, these don't hold the completion value.
*/
QUEST_ARCHITECTURAL_ALLIANCE(4982),
QUEST_BEAR_YOUR_SOUL(5078),
QUEST_CURSE_OF_THE_EMPTY_LORD(821),
QUEST_ENCHANTED_KEY(1391),
QUEST_THE_GENERALS_SHADOW(3330),
QUEST_SKIPPY_AND_THE_MOGRES(1344),
QUEST_LAIR_OF_TARN_RAZORLOR(3290),
QUEST_FAMILY_PEST(5347),
QUEST_THE_MAGE_ARENA_II(6067),
//TODO
QUEST_IN_SEARCH_OF_KNOWLEDGE(6067),
/**
* Spellbook filtering (1 = unfiltered, 0 = filtered)
*/
FILTER_SPELLBOOK(6718),
/**
* POH Building mode (1 = yes, 0 = no)
*/
BUILDING_MODE(2176),
WINTERTODT_TIMER(7980),
/**
* 1 if in game, 0 if not
*/
LMS_IN_GAME(5314),
/**
* Amount of pvp kills in current game
*/
LMS_KILLS(5315),
/**
* The x coordinate of the final safespace (world coord)
*/
LMS_SAFE_X(5316),
/**
* Starts at 100, counts down every 10 ticks (6 seconds)
*/
LMS_POISON_PROGRESS(5317),
/**
* The y coordinate of the final safespace (world coord)
*/
LMS_SAFE_Y(5320),
/**
* 1 is true, 0 is false.
*/
GAUNTLET_FINAL_ROOM_ENTERED(9177),
/**
* 1 is true, 0 is false.
*/
GAUNTLET_ENTERED(9178);
/**
* The raw varbit ID.
*/
private final int id;
} | 1 | 15,766 | Can you remove the sculliscep varbits from here too? | open-osrs-runelite | java |
@@ -1162,6 +1162,12 @@ function update_5_9_2018() {
");
}
+function update_8_23_2018() {
+ $retval = do_query("alter table host add index host_cpid (host_cpid)");
+ return $retval && do_query("alter table host add index host_domain_name (domain_name)");
+}
+
+
// Updates are done automatically if you use "upgrade".
//
// If you need to do updates manually, | 1 | <?php
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
// code for one-time database updates goes here.
// Don't run this unless you know what you're doing!
$cli_only = true;
require_once("../inc/util_ops.inc");
$db = BoincDb::get_aux(false);
if (!$db) {
echo "Can't open database\n";
exit;
}
set_time_limit(0);
function do_query($query) {
echo "Doing query:\n$query\n";
$result = _mysql_query($query);
if (!$result) {
echo "Failed:\n"._mysql_error()."\n";
return false;
} else {
echo "Success.\n";
return true;
}
}
function update_4_18_2004() {
do_query("alter table user add cross_project_id varchar(254) not null");
$result = do_query("select * from user");
while ($user = _mysql_fetch_object($result)) {
$x = random_string();
do_query("update user set cross_project_id='$x' where id=$user->id");
}
}
function update_5_12_2004() {
do_query(
"create table trickle_up (
id integer not null auto_increment,
create_time integer not null,
send_time integer not null,
resultid integer not null,
appid integer not null,
hostid integer not null,
handled smallint not null,
xml text,
primary key (id)
)"
);
do_query(
"create table trickle_down (
id integer not null auto_increment,
create_time integer not null,
resultid integer not null,
hostid integer not null,
handled smallint not null,
xml text,
primary key (id)
)"
);
do_query(
"alter table trickle_up add index trickle_handled (appid, handled)"
);
do_query(
"alter table trickle_down add index trickle_host(hostid, handled)"
);
}
function update_5_27_2004() {
do_query(
"alter table host add nresults_today integer not null"
);
}
function update_6_9_2004() {
do_query(
"alter table profile change verification verification integer not null"
);
}
function update_6_15_2004() {
do_query(
"alter table user add index user_name(name)"
);
}
function update_7_02_2004() {
do_query(
"alter table workunit drop column result_template"
);
do_query(
"alter table workunit add column result_template_file varchar(63) not null"
);
do_query(
"update workunit set result_template_file='templates/foo.xml'"
);
}
function update_7_08_2004() {
do_query(
"alter table result drop index ind_res_st"
);
do_query(
"alter table add index ind_res_st(server_state)"
);
}
function update_9_04_2004() {
do_query(
"insert into forum_preferences (userid, signature, posts) select user.id, user.signature, user.posts from user where user.posts > 0 or user.signature<>''");
}
function update_9_05_2004() {
do_query(
"ALTER TABLE forum_preferences ADD special_user INT NOT NULL"
);
}
function update_9_26_2004() {
do_query(
"alter table app add homogeneous_redundancy smallint not null"
);
}
function update_10_09_2004() {
do_query(
"alter table forum_preferences add jump_to_unread tinyint(1) unsigned not null default 1"
);
do_query(
"alter table forum_preferences add hide_signatures tinyint(1) unsigned not null default 0"
);
do_query(
"alter table post add signature tinyint(1) unsigned not null default 0"
);
}
function update_10_25_2004() {
do_query(
"alter table forum_preferences add rated_posts varchar(254) not null"
);
do_query(
"alter table forum_preferences add low_rating_threshold integer not null"
);
do_query(
"alter table forum_preferences add high_rating_threshold integer not null"
);
}
function update_10_26_2004() {
do_query("alter table forum_preferences modify jump_to_unread tinyint(1) unsigned not null default 0");
}
function update_11_24_2004() {
do_query(
"alter table workunit change workseq_next hr_class integer not null"
);
do_query(
"alter table workunit add priority integer not null"
);
do_query(
"alter table workunit add mod_time timestamp"
);
do_query(
"alter table result add priority integer not null"
);
do_query(
"alter table result add mod_time timestamp"
);
do_query(
"alter table host drop column projects"
);
do_query(
"alter table host add avg_turnaround double not null"
);
do_query(
"alter table result drop index ind_res_st"
);
do_query(
"alter table result add index ind_res_st(server_state, priority)"
);
do_query(
"alter table result drop index app_received_time"
);
do_query(
"alter table result add index app_mod_time(appid, mod_time desc)"
);
}
// or alternatively: (can run in parallel)
function update_11_24_2004_result() {
do_query(
"alter table result add priority integer not null, "
."add mod_time timestamp, "
."drop index ind_res_st, "
."add index ind_res_st(server_state, priority), "
."drop index app_received_time, "
."add index app_mod_time(appid, mod_time desc)"
);
}
function update_11_24_2004_workunit() {
do_query(
"alter table workunit "
." change workseq_next hr_class integer not null, "
." add priority integer not null, "
." add mod_time timestamp"
);
}
function update_11_24_2004_host() {
do_query(
"alter table host drop column projects, "
." add avg_turnaround double not null"
);
}
function update_12_27_2004() {
do_query("alter table workunit drop index wu_filedel");
do_query("alter table workunit add index wu_filedel (file_delete_state, mod_time)");
}
function update_1_3_2005() {
do_query("alter table workunit drop index wu_filedel");
do_query("alter table workunit add index wu_filedel (file_delete_state)");
do_query("alter table result drop index app_mod_time");
}
function update_1_7_2005() {
do_query("alter table forum_preferences add ignorelist varchar(254) not null");
}
function update_1_13_2005() {
do_query("alter table thread add hidden integer not null");
do_query("alter table post add hidden integer not null");
}
function update_1_18_2005() {
do_query("ALTER TABLE forum_preferences CHANGE special_user special_user CHAR(12) DEFAULT '0' NOT NULL");
}
function update_1_19_2005() {
do_query("create table tentative_user (
nonce varchar(254) not null,
email_addr varchar(254) not null,
confirmed integer not null,
primary key(nonce)
);"
);
}
function update_1_20_2005() {
do_query("alter table host add host_cpid varchar(254)");
}
function update_1_20a_2005() {
do_query("alter table host add external_ip_addr varchar(254)");
}
function update_2_25_2005() {
do_query("alter table host add max_results_day integer not null");
}
function update_4_20_2005(){
do_query("ALTER TABLE `thread` ADD `sticky` TINYINT UNSIGNED DEFAULT '0' NOT NULL");
do_query("ALTER TABLE `forum` ADD `post_min_total_credit` INT NOT NULL AFTER `posts`");
do_query("ALTER TABLE `forum` ADD `post_min_expavg_credit` INT NOT NULL AFTER `posts`");
do_query("ALTER TABLE `forum` ADD `post_min_interval` INT NOT NULL AFTER `posts`");
do_query("ALTER TABLE `forum` ADD `rate_min_total_credit` INT NOT NULL AFTER `posts`");
do_query("ALTER TABLE `forum` ADD `rate_min_expavg_credit` INT NOT NULL AFTER `posts`");
do_query("ALTER TABLE `forum_preferences` ADD `last_post` INT( 14 ) UNSIGNED NOT NULL AFTER `posts`");
}
function update_4_30_2005(){
do_query("ALTER TABLE `forum_preferences` ADD `ignore_sticky_posts` TINYINT( 1 ) UNSIGNED NOT NULL");
}
function update_6_22_2005() {
do_query("alter table host add cpu_efficiency double not null after active_frac, add duration_correction_factor double not null after cpu_efficiency");
}
function update_8_05_2005() {
do_query("alter table user add passwd_hash varchar(254) not null");
do_query("alter table user add email_validated smallint not null");
do_query("update user set passwd_hash=MD5(concat(authenticator, email_addr))");
do_query("update user set email_validated=1");
}
function update_8_25_2005() {
do_query("alter table user add donated smallint not null");
}
function update_8_26_2005() {
do_query("drop table tentative_user");
}
function update_9_22_2005() {
do_query("update user set country='Macedonia' where country='Macedonia, The Former Yugoslav Republic of'");
}
function update_11_24_2005(){
do_query("ALTER TABLE `forum_preferences` ADD `minimum_wrap_postcount` INT DEFAULT '100' NOT NULL AFTER `high_rating_threshold` ,
ADD `display_wrap_postcount` INT DEFAULT '75' NOT NULL AFTER `minimum_wrap_postcount`");
}
function update_6_16_2006() {
do_query("ALTER TABLE `thread` ADD `score` DOUBLE NOT NULL AFTER `sufferers` , ADD `votes` INT NOT NULL AFTER `score`");
do_query("ALTER TABLE `forum_preferences` ADD `forum_sorting` INT NOT NULL AFTER `sorting`");
do_query("ALTER TABLE `forum_preferences` ADD `thread_sorting` INT NOT NULL AFTER `forum_sorting`");
do_query("CREATE TABLE `post_ratings` (
`post` INT UNSIGNED NOT NULL ,
`user` INT UNSIGNED NOT NULL ,
`rating` TINYINT NOT NULL ,
PRIMARY KEY ( `post` , `user`))");
do_query("ALTER TABLE `forum_preferences` DROP `avatar_type`");
do_query("ALTER TABLE `forum_preferences` CHANGE `low_rating_threshold` `low_rating_threshold` INT( 11 ) DEFAULT '-25' NOT NULL");
do_query("ALTER TABLE `forum_preferences` CHANGE `high_rating_threshold` `high_rating_threshold` INT( 11 ) DEFAULT '5' NOT NULL");
do_query("ALTER TABLE `forum_preferences` CHANGE `jump_to_unread` `jump_to_unread` TINYINT( 1 ) UNSIGNED DEFAULT '1' NOT NULL");
do_query("ALTER TABLE `forum_preferences` DROP `sorting`");
do_query("ALTER TABLE `forum_preferences` CHANGE `no_signature_by_default` `no_signature_by_default` TINYINT( 1 ) UNSIGNED DEFAULT '1' NOT NULL ");
do_query("ALTER TABLE `thread` ADD `status` SMALLINT UNSIGNED NOT NULL AFTER `owner`");
do_query("ALTER TABLE `subscriptions` ADD `notified` TINYINT( 1 ) UNSIGNED DEFAULT '0' NOT NULL");
do_query("ALTER TABLE `subscriptions` CHANGE `notified` `notified_time` INT( 14 ) UNSIGNED DEFAULT '0' NOT NULL");
}
function update_7_11_2006() {
do_query("alter table app add weight double not null");
}
function update_8_8_2006() {
do_query("alter table forum_preferences add banished_until integer not null default 0");
}
function update_10_21_2006() {
do_query("alter table app add beta smallint not null default 0");
}
function update_10_26_2006() {
do_query("ALTER TABLE `team` ADD `ping_user` INT UNSIGNED NOT NULL DEFAULT '0',
ADD `ping_time` INT UNSIGNED NOT NULL DEFAULT '0'");
do_query("ALTER TABLE team ADD INDEX team_userid (userid)");
}
function update_11_10_2006() {
do_query("ALTER TABLE thread ADD locked TINYINT NOT NULL DEFAULT 0");
}
function update_12_22_2006() {
do_query("ALTER TABLE forum ADD is_dev_blog TINYINT NOT NULL DEFAULT 0");
}
function update_4_07_2007() {
do_query('create table sent_email (
userid integer not null,
time_sent integer not null,
email_type smallint not null,
primary key(userid)
) TYPE=MyISAM;'
);
}
function update_4_24_2007() {
do_query('alter table host add error_rate double not null default 0');
}
function update_4_29_2007() {
do_query("CREATE TABLE `private_messages` (
`id` int(10) unsigned NOT NULL auto_increment,
`userid` int(10) unsigned NOT NULL,
`senderid` int(10) unsigned NOT NULL,
`date` int(10) unsigned NOT NULL,
`opened` tinyint(1) unsigned NOT NULL default '0',
`subject` varchar(255) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`),
KEY `userid` (`userid`)
) TYPE=MyISAM;"
);
}
function update_4_30_2007() {
do_query("create table credited_job (
userid integer not null,
workunitid bigint not null
) TYPE=MyISAM;");
do_query("alter table credited_job add index credited_job_user (userid),
add index credited_job_wu (workunitid),
add unique credited_job_user_wu (userid, workunitid);"
);
}
function update_5_27_2007() {
do_query("create table donation_items (
id integer unsigned not null auto_increment,
item_name varchar(32) not null,
title varchar(255) not null,
description varchar(255) not null,
required double unsigned not null default '0',
PRIMARY KEY(id)
) TYPE=MyISAM;");
do_query("create table donation_paypal (
id integer not null auto_increment,
order_time integer unsigned not null,
userid integer not null,
email_addr varchar(255) not null,
order_amount double(6,2) not null,
processed tinyint(1) not null default '0',
payment_time integer unsigned not null,
item_name varchar(255) not null,
item_number varchar(255) not null,
payment_status varchar(255) not null,
payment_amount double(6,2) not null,
payment_fee double(5,2) default null,
payment_currency varchar(255) not null,
txn_id varchar(255) not null,
receiver_email varchar(255) not null,
payer_email varchar(255) not null,
payer_name varchar(255) not null,
PRIMARY KEY(id)
) TYPE=MyISAM;");
}
function update_6_5_2007() {
do_query("ALTER TABLE `forum_preferences` ADD `pm_notification` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '1';");
}
function update_7_26_2007() {
do_query("create table team_delta (
userid integer not null,
teamid integer not null,
timestamp integer not null,
joining tinyint(1) not null,
total_credit double not null
) TYPE=MyISAM;"
);
do_query("alter table team_delta
add index team_delta_teamid (teamid, timestamp);"
);
}
function update_9_26_2007() {
// Change field type from unsigned to signed
do_query("ALTER TABLE team CHANGE ping_user ping_user integer NOT NULL DEFAULT 0");
}
function update_9_28_2007() {
do_query("alter table team engine=myisam");
do_query("alter table team change description description text");
do_query("alter table team add fulltext index team_name_desc(name, description)");
}
function update_10_25_2007() {
do_query("update user set country='Serbia' where country='Serbia and Montenegro'");
do_query("update team set country='Serbia' where country='Serbia and Montenegro'");
}
function update_10_26_2007() {
do_query("create table banishment_vote (
id serial primary key,
userid integer not null,
modid integer not null,
start_time integer not null,
end_time integer not null
) TYPE=MyISAM;"
);
do_query("create table banishment_votes (
id serial primary key,
voteid integer not null,
modid integer not null,
time integer not null,
yes tinyint(1) not null
) TYPE=MyISAM;"
);
}
function update_11_7_2007() {
do_query("create table team_admin (
teamid integer not null,
userid integer not null,
create_time integer not null,
rights integer not null
) type=MyISAM;"
);
do_query("alter table team_admin add unique (teamid, userid);");
}
function update_11_8_2007() {
do_query("alter table forum add parent_type integer not null");
}
function update_11_14_2007() {
do_query("alter table forum drop index category");
do_query("alter table forum add unique pct (parent_type, category, title)");
}
// pm_notification should be 0 by default.
// We don't know who really wants it to be 1, so set everyone to 0;
// projects might want to run a news item notifying user
// that they need to explicitly set this if they want PM notification
//
function update_11_18_2007() {
do_query("update forum_preferences set pm_notification=0");
do_query("alter table forum_preferences change pm_notification pm_notification tinyint not null default 0");
}
function update_11_20_2007() {
do_query("alter table team add fulltext index team_name(name)");
}
function update_12_18_2007() {
do_query("create table friend (
user_src integer not null,
user_dest integer not null,
message varchar(255) not null,
create_time integer not null,
reciprocated tinyint not null
)
");
do_query("create table notify (
id serial primary key,
userid integer not null,
create_time integer not null,
type integer not null,
opaque integer not null
)
");
do_query("alter table friend
add unique friend_u (user_src, user_dest)
");
do_query("alter table notify
add index notify_u (userid)
");
}
function update_12_28_2007() {
do_query("alter table notify drop index notify_u");
do_query("alter table notify
add unique notify_un (userid, type, opaque)
");
}
function update_2_18_2008() {
do_query("create table assignment (
id integer not null auto_increment,
create_time integer not null,
target_id integer not null,
target_type integer not null,
multi tinyint not null,
workunitid integer not null,
resultid integer not null,
primary key (id)
) engine = InnoDB
");
}
// If you haven't done 3_7, skip both of the following:
//
function update_3_7_2008() {
do_query("alter table workunit add column rsc_bandwidth_bound double not null after rsc_disk_bound");
}
function update_3_7_undo_2008() {
do_query("alter table workunit drop column rsc_bandwidth_bound");
}
function update_3_10_2008() {
do_query("alter table workunit add column rsc_bandwidth_bound double not null");
}
function update_3_13_2008() {
do_query("alter table app_version drop index appid");
do_query("alter table app_version add column plan_class varchar(254) not null default ''");
do_query("alter table app_version add unique apvp (appid, platformid, version_num, plan_class)");
}
// The following cleans up from a bug that causes "team transfer pending"
// to be shown even after transfer is finished
//
function update_3_27_2008() {
do_query("update team set ping_user=0, ping_time=0 where ping_user=userid");
}
function update_3_31_2008() {
do_query("alter table app_version change column xml_doc xml_doc mediumblob");
}
function update_6_3_2008() {
do_query("alter table app add target_nresults smallint not null default 0");
}
function update_7_28_2008() {
do_query("create table credit_multiplier (
id serial primary key,
appid integer not null,
time integer not null,
multiplier double not null default 0
) engine=MyISAM
");
}
function update_10_05_2008(){
do_query("alter table forum_preferences add highlight_special tinyint default '1' not null");
}
function update_10_7_2008() {
do_query("alter table team add joinable tinyint default '1' not null");
}
function update_6_16_2009() {
do_query("create table state_counts (
appid integer not null,
last_update_time integer not null,
result_server_state_2 integer not null,
result_server_state_4 integer not null,
result_file_delete_state_1 integer not null,
result_file_delete_state_2 integer not null,
result_server_state_5_and_file_delete_state_0 integer not null,
workunit_need_validate_1 integer not null,
workunit_assimilate_state_1 integer not null,
workunit_file_delete_state_1 integer not null,
workunit_file_delete_state_2 integer not null,
primary key (appid)
) engine=MyISAM
");
}
function update_9_3_2009() {
do_query("alter table result add (
elapsed_time double not null,
flops_estimate double not null,
app_version_id integer not null
)
");
}
function update_3_5_2010() {
do_query("alter table workunit add fileset_id integer not null");
}
function update_3_17_2010() {
do_query("create table host_app_version (
host_id integer not null,
app_version_id integer not null,
pfc_n double not null,
pfc_avg double not null,
et_n double not null,
et_avg double not null,
et_var double not null,
et_q double not null,
host_scale_time double not null,
scale_probation tinyint not null default 1,
error_rate double not null,
max_jobs_per_day integer not null,
n_jobs_today integer not null,
turnaround_n double not null,
turnaround_avg double not null,
turnaround_var double not null,
turnaround_q double not null
) engine = InnoDB
");
do_query("alter table host_app_version
add unique hap(host_id, app_version_id)
");
do_query("alter table app_version
add pfc_n double not null default 0,
add pfc_avg double not null default 0,
add pfc_scale double not null default 0,
add expavg_credit double not null default 0,
add expavg_time double not null default 0
");
do_query("alter table app
add min_avg_pfc double not null default 1,
add host_scale_check tinyint not null,
add max_jobs_in_progress integer not null,
add max_gpu_jobs_in_progress integer not null,
add max_jobs_per_rpc integer not null,
add max_jobs_per_day_init integer not null
");
}
function update_4_21_2010() {
do_query("alter table host_app_version
drop column host_scale_time,
drop column scale_probation,
drop column error_rate,
add column consecutive_valid integer not null
");
}
function update_6_10_2010() {
do_query("alter table app
drop column max_jobs_in_progress,
drop column max_gpu_jobs_in_progress,
drop column max_jobs_per_rpc,
drop column max_jobs_per_day_init
");
}
function update_6_3_2011() {
do_query("alter table app
add homogeneous_app_version tinyint not null default 0
");
do_query("alter table workunit
add app_version_id integer not null default 0
");
}
function update_6_20_2011() {
do_query("
create table batch (
id serial primary key,
user_id integer not null,
create_time integer not null,
logical_start_time double not null,
logical_end_time double not null,
est_completion_time double not null,
njobs integer not null
) engine = InnoDB");
do_query("
create table user_submit (
user_id integer not null,
quota double not null,
logical_start_time double not null,
all_apps tinyint not null
) engine = InnoDB");
do_query("
create table user_submit_app (
user_id integer not null,
app_id integer not null
) engine = InnoDB");
}
function update_7_26_2011() {
do_query("
alter table batch
add fraction_done double not null,
add nerror_jobs integer not null,
add state integer not null,
add completion_time double not null,
add credit_estimate double not null,
add credit_canonical double not null,
add credit_total double not null,
add name varchar(255) not null,
add app_id integer not null
");
}
function update_9_6_2011() {
do_query("
alter table user_submit
add create_apps tinyint not null,
add create_app_versions tinyint not null
");
}
function update_9_15_2011() {
do_query("
alter table result
add runtime_outlier tinyint not null
");
}
function update_9_20_2011() {
do_query("
alter table user_submit
drop column all_apps,
drop column create_apps,
drop column create_app_versions,
add submit_all tinyint not null,
add manage_all tinyint not null
");
do_query("
alter table user_submit_app
add manage tinyint not null
");
}
function update_1_30_2012() {
do_query("
alter table workunit
add transitioner_flags tinyint not null
");
do_query(
"alter table assignment add index asgn_target(target_type, target_id)"
);
}
function update_6_4_2012() {
do_query("
alter table batch
add project_state integer not null,
add description varchar(255) not null
");
}
function update_8_24_2012() {
do_query("
alter table app
add non_cpu_intensive tinyint not null default 0
");
}
function update_8_26_2012() {
do_query("
alter table app
add locality_scheduling integer not null default 0
");
}
function update_11_25_2012() {
do_query("
create table job_file (
id integer not null auto_increment,
md5 char(64) not null,
create_time double not null,
delete_time double not null,
primary key(id)
) engine = InnoDB
");
do_query("
alter table job_file add index md5 (md5)
");
}
function update_4_26_2013() {
do_query("alter table app add n_size_classes smallint not null default 0");
do_query("alter table workunit add size_class smallint not null default -1");
do_query("alter table result add size_class smallint not null default -1");
}
function update_5_23_2013() {
do_query("alter table host add product_name varchar(254) not null");
}
function update_9_10_2013() {
do_query("alter table workunit change mod_time mod_time timestamp default current_timestamp on update current_timestamp");
do_query("alter table result change mod_time mod_time timestamp default current_timestamp on update current_timestamp");
}
function update_9_17_2013() {
do_query("alter table batch add expire_time double not null");
}
function update_12_22_2013() {
do_query("
create table badge (
id serial primary key,
create_time double not null,
type tinyint not null,
name varchar(255) not null,
title varchar(255) not null,
description varchar(255) not null,
image_url varchar(255) not null,
level varchar(255) not null,
tags varchar(255) not null,
sql_rule varchar(255) not null
)
");
do_query("
create table badge_user (
badge_id integer not null,
user_id integer not null,
create_time double not null,
reassign_time double not null
)
");
do_query("
create table badge_team (
badge_id integer not null,
team_id integer not null,
create_time double not null,
reassign_time double not null
)
");
do_query("
alter table badge_user
add unique (user_id, badge_id)
");
do_query("
alter table badge_team
add unique (team_id, badge_id)
");
}
function update_1_13_2014() {
do_query(
"alter table user_submit add max_jobs_in_progress integer not null"
);
}
function update_3_6_2014() {
do_query(
"alter table host add gpu_active_frac double not null"
);
}
function update_4_2_2014() {
do_query(
"alter table result
add peak_working_set_size double not null,
add peak_swap_size double not null,
add peak_disk_usage double not null
"
);
}
function update_5_3_2014() {
do_query(
"alter table app
add fraction_done_exact tinyint not null
"
);
}
function update_6_5_2014() {
do_query(
"alter table app_version
add beta tinyint not null
"
);
}
function update_8_15_2014() {
do_query(
"create table credit_user (
userid integer not null,
appid integer not null,
njobs integer not null,
total double not null,
expavg double not null,
expavg_time double not null,
credit_type integer not null,
primary key (userid, appid, credit_type)
) engine=InnoDB
"
);
do_query(
"create table credit_team (
teamid integer not null,
appid integer not null,
njobs integer not null,
total double not null,
expavg double not null,
expavg_time double not null,
credit_type integer not null,
primary key (teamid, appid, credit_type)
) engine=InnoDB
"
);
}
function update_10_8_2014() {
do_query("alter table user_submit add primary key(user_id)");
do_query("alter table user_submit_app add primary key(user_id, app_id)");
}
function update_4_15_2015() {
do_query("alter table forum
alter timestamp set default 0,
alter threads set default 0,
alter posts set default 0,
alter rate_min_expavg_credit set default 0,
alter rate_min_total_credit set default 0,
alter post_min_interval set default 0,
alter post_min_expavg_credit set default 0,
alter post_min_total_credit set default 0,
alter parent_type set default 0
");
}
// functions to change select ID types to 64-bit
//
function result_big_ids() {
do_query("alter table result
change column id id bigint not null auto_increment
");
do_query("alter table workunit
change column canonical_resultid canonical_resultid bigint not null
");
do_query("alter table assignment
change column resultid resultid bigint not null
");
}
function workunit_big_ids() {
do_query("alter table workunit
change column id id bigint not null auto_increment
");
do_query("alter table result
change column workunitid workunitid bigint not null
");
do_query("alter table assignment
change column workunitid workunitid bigint not null
");
}
// run this if your projects uses HTTPS, to patch up the gravatar URLs
//
function gravatar_update() {
do_query("update forum_preferences
SET avatar = REPLACE(avatar, 'http://www.gravatar.com', '//www.gravatar.com')
");
}
function update_1_27_2016() {
do_query("alter table team add column mod_time timestamp default current_timestamp on update current_timestamp");
}
function update_2_17_2017() {
do_query("alter table job_file change md5 name varchar(255) not null");
}
function update_3_17_2017() {
do_query("alter table credit_user
add index cu_total(appid, total),
add index cu_avg(appid, expavg)
");
do_query("alter table credit_team
add index ct_total(appid, total),
add index ct_avg(appid, expavg)
");
}
function update_6_13_2017() {
do_query("alter table host
add column p_ngpus integer not null,
add column p_gpu_fpops double not null
");
}
function update_7_21_2017() {
do_query("alter table workunit
add column keywords varchar(254) not null
");
}
function update_8_9_2017() {
do_query("alter table workunit
add column app_version_num integer not null
");
}
function update_10_25_2017() {
do_query("alter table user
add column login_token char(32) not null,
add column login_token_time double not null
");
}
function update_3_8_2018() {
do_query("alter table user
modify column login_token char(32) not null default '',
modify column login_token_time double not null default 0
");
}
function update_4_5_2018() {
do_query("create table token (
token varchar(255) not null,
userid integer not null,
type char not null,
create_time integer not null,
expire_time integer,
primary key (token),
index token_userid (userid)
) engine=InnoDB
");
}
function update_4_6_2018() {
do_query("alter table team
modify column total_credit double not null default 0.0,
modify column expavg_credit double not null default 0.0,
modify column seti_id integer not null default 0
");
}
function update_4_18_2018() {
do_query("alter table token
modify column create_time integer not null
");
}
function update_4_19_2018() {
do_query("alter table user
add column previous_email_addr varchar(254) not null default '',
add column email_addr_change_time double not null default 0
");
do_query("alter table user add index user_email_time (email_addr_change_time)");
}
function update_5_9_2018() {
$retval = do_query("create table user_deleted (
userid integer not null,
public_cross_project_id varchar(254) not null,
create_time double not null,
primary key (userid)
) engine=InnoDB;
");
$retval = $retval && do_query("create table host_deleted (
hostid integer not null,
public_cross_project_id varchar(254) not null,
create_time double not null,
primary key (hostid)
) engine=InnoDB;
");
$retval = $retval && do_query("alter table user_deleted
add index user_deleted_create(create_time)
");
$retval = $retval && do_query("alter table host_deleted
add index host_deleted_create(create_time)
");
$retval = $retval && do_query("alter table team_delta
add index team_delta_userid (userid)
");
$retval = $retval && do_query("alter table donation_paypal
add index donation_paypal_userid(userid)
");
$retval = $retval && do_query("alter table banishment_vote
add index banishment_vote_userid(userid)
");
$retval = $retval && do_query("alter table post_ratings
add index post_ratings_user(user)
");
$retval = $retval && do_query("alter table msg_from_host
add index message_hostid(hostid)
");
return $retval && do_query("alter table sent_email
add index sent_email_userid(userid)
");
}
// Updates are done automatically if you use "upgrade".
//
// If you need to do updates manually,
// modify the following to call the function you want.
// Make sure you do all needed functions, in order.
// (Look at your DB structure using "explain" queries to see
// which ones you need).
//update_3_17_2010();
// in the following, the first element is a version number.
// This used to be the Subversion version#,
// but with Git we just use sequential integers
//
$db_updates = array (
array(18490, "update_6_16_2009"),
array(19001, "update_9_3_2009"),
array(20807, "update_3_5_2010"),
array(20932, "update_3_17_2010"),
array(21226, "update_4_21_2010"),
array(21728, "update_6_10_2010"),
array(23635, "update_6_3_2011"),
array(23762, "update_6_20_2011"),
array(23881, "update_7_26_2011"),
array(24137, "update_9_6_2011"),
array(24225, "update_9_15_2011"),
array(24248, "update_9_20_2011"),
array(25169, "update_1_30_2012"),
array(25734, "update_6_4_2012"),
array(26060, "update_8_24_2012"),
array(26062, "update_8_26_2012"),
array(27000, "update_11_25_2012"),
array(27001, "update_4_26_2013"),
array(27002, "update_5_23_2013"),
array(27003, "update_9_10_2013"),
array(27004, "update_9_17_2013"),
array(27005, "update_12_22_2013"),
array(27006, "update_1_13_2014"),
array(27007, "update_3_6_2014"),
array(27008, "update_4_2_2014"),
array(27009, "update_5_3_2014"),
array(27010, "update_6_5_2014"),
array(27011, "update_8_15_2014"),
array(27012, "update_10_8_2014"),
array(27013, "update_4_15_2015"),
array(27014, "update_1_27_2016"),
array(27015, "update_2_17_2017"),
array(27016, "update_3_17_2017"),
array(27017, "update_6_13_2017"),
array(27018, "update_7_21_2017"),
array(27019, "update_8_9_2017"),
array(27020, "update_10_25_2017"),
array(27021, "update_3_8_2018"),
array(27022, "update_4_5_2018"),
array(27023, "update_4_6_2018"),
array(27024, "update_4_18_2018"),
array(27025, "update_4_19_2018"),
array(27026, "update_5_9_2018")
);
?>
| 1 | 11,437 | I understand that it is a common practice in this script to add indexes this way but why don't we check index existence before adding it? I'm not very familiar with MySql but it's can be done easily in MSSQL and I'm pretty sure that there is a way to do the same here. | BOINC-boinc | php |
@@ -39,5 +39,5 @@ class InputDevice(object):
def clear_actions(self):
self.actions = []
- def create_pause(self, duraton=0):
+ def create_pause(self, duration=0):
pass | 1 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC 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.
import uuid
class InputDevice(object):
"""
Describes the input device being used for the action.
"""
def __init__(self, name=None):
if name is None:
self.name = uuid.uuid4()
else:
self.name = name
self.actions = []
def add_action(self, action):
"""
"""
self.actions.append(action)
def clear_actions(self):
self.actions = []
def create_pause(self, duraton=0):
pass
| 1 | 14,870 | we should probably deprecate (and display a warning) the misspelled keyword arg here rather than removing it... and then add the new one. This changes a public API and will break any code that is currently using the misspelled version. | SeleniumHQ-selenium | js |
@@ -47,8 +47,7 @@
void h2o_mruby__abort_exc(mrb_state *mrb, const char *mess, const char *file, int line)
{
- h2o_error_printf("%s at file: \"%s\", line %d: %s\n", mess, file, line, RSTRING_PTR(mrb_inspect(mrb, mrb_obj_value(mrb->exc))));
- abort();
+ h2o_fatal("%s at file: \"%s\", line %d: %s\n", mess, file, line, RSTRING_PTR(mrb_inspect(mrb, mrb_obj_value(mrb->exc))));
}
mrb_value h2o_mruby__new_str(mrb_state *mrb, const char *s, size_t len, int is_static, const char *file, int line) | 1 | /*
* Copyright (c) 2014-2016 DeNA Co., Ltd., Kazuho Oku, Ryosuke Matsumoto,
* Masayoshi Takahashi
*
* 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 <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <mruby.h>
#include <mruby/proc.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/compile.h>
#include <mruby/error.h>
#include <mruby/hash.h>
#include <mruby/opcode.h>
#include <mruby/string.h>
#include <mruby/throw.h>
#include <mruby/variable.h>
#include <mruby_input_stream.h>
#include "h2o.h"
#include "h2o/mruby_.h"
#include "mruby/embedded.c.h"
#define STATUS_FALLTHRU 399
#define FALLTHRU_SET_PREFIX "x-fallthru-set-"
#define FREEZE_STRING(v) MRB_SET_FROZEN_FLAG(mrb_obj_ptr(v))
void h2o_mruby__abort_exc(mrb_state *mrb, const char *mess, const char *file, int line)
{
h2o_error_printf("%s at file: \"%s\", line %d: %s\n", mess, file, line, RSTRING_PTR(mrb_inspect(mrb, mrb_obj_value(mrb->exc))));
abort();
}
mrb_value h2o_mruby__new_str(mrb_state *mrb, const char *s, size_t len, int is_static, const char *file, int line)
{
if (mrb->exc != NULL)
h2o_mruby__abort_exc(mrb, "h2o_mruby_new_str:precondition failure", file, line);
mrb_value ret = is_static ? mrb_str_new_static(mrb, s, len) : mrb_str_new(mrb, s, len);
if (mrb->exc != NULL)
h2o_mruby__abort_exc(mrb, "h2o_mruby_new_str:failed to create string", file, line);
return ret;
}
static void on_gc_dispose_generator(mrb_state *mrb, void *_generator)
{
h2o_mruby_generator_t *generator = _generator;
if (generator == NULL)
return;
generator->refs.generator = mrb_nil_value();
}
static void on_gc_dispose_error_stream(mrb_state *mrb, void *_error_stream)
{
h2o_mruby_error_stream_t *error_stream = _error_stream;
if (error_stream == NULL)
return;
if (error_stream->generator != NULL) {
error_stream->generator->error_stream = NULL;
error_stream->generator->refs.error_stream = mrb_nil_value();
}
free(error_stream);
}
const static struct mrb_data_type generator_type = {"generator", on_gc_dispose_generator};
const static struct mrb_data_type error_stream_type = {"error_stream", on_gc_dispose_error_stream};
h2o_mruby_generator_t *h2o_mruby_get_generator(mrb_state *mrb, mrb_value obj)
{
h2o_mruby_generator_t *generator = mrb_data_check_get_ptr(mrb, obj, &generator_type);
return generator;
}
h2o_mruby_error_stream_t *h2o_mruby_get_error_stream(mrb_state *mrb, mrb_value obj)
{
h2o_mruby_error_stream_t *error_stream = mrb_data_check_get_ptr(mrb, obj, &error_stream_type);
return error_stream;
}
void h2o_mruby_setup_globals(mrb_state *mrb)
{
const char *root = getenv("H2O_ROOT");
if (root == NULL)
root = H2O_TO_STR(H2O_ROOT);
mrb_gv_set(mrb, mrb_intern_lit(mrb, "$H2O_ROOT"), h2o_mruby_new_str(mrb, root, strlen(root)));
h2o_mruby_eval_expr(mrb, "$LOAD_PATH << \"#{$H2O_ROOT}/share/h2o/mruby\"");
h2o_mruby_assert(mrb);
/* require core modules and include built-in libraries */
h2o_mruby_eval_expr(mrb, "require \"#{$H2O_ROOT}/share/h2o/mruby/preloads.rb\"");
if (mrb->exc != NULL) {
h2o_error_printf("an error occurred while loading %s/%s: %s\n", root, "share/h2o/mruby/preloads.rb",
RSTRING_PTR(mrb_inspect(mrb, mrb_obj_value(mrb->exc))));
if (mrb_obj_is_instance_of(mrb, mrb_obj_value(mrb->exc), mrb_class_get(mrb, "LoadError"))) {
h2o_error_printf("Did you forget to run `make install`?\n");
}
abort();
}
}
mrb_value h2o_mruby_to_str(mrb_state *mrb, mrb_value v)
{
if (!mrb_string_p(v))
H2O_MRUBY_EXEC_GUARD({ v = mrb_str_to_str(mrb, v); });
return v;
}
mrb_value h2o_mruby_to_int(mrb_state *mrb, mrb_value v)
{
H2O_MRUBY_EXEC_GUARD({ v = mrb_Integer(mrb, v); });
return v;
}
mrb_value h2o_mruby_eval_expr(mrb_state *mrb, const char *expr)
{
return mrb_funcall(mrb, mrb_top_self(mrb), "eval", 1, mrb_str_new_cstr(mrb, expr));
}
mrb_value h2o_mruby_eval_expr_location(mrb_state *mrb, const char *expr, const char *path, const int lineno)
{
return mrb_funcall(mrb, mrb_top_self(mrb), "eval", 4, mrb_str_new_cstr(mrb, expr), mrb_nil_value(), mrb_str_new_cstr(mrb, path),
mrb_fixnum_value(lineno));
}
void h2o_mruby_define_callback(mrb_state *mrb, const char *name, h2o_mruby_callback_t callback)
{
h2o_mruby_shared_context_t *shared_ctx = mrb->ud;
h2o_vector_reserve(NULL, &shared_ctx->callbacks, shared_ctx->callbacks.size + 1);
shared_ctx->callbacks.entries[shared_ctx->callbacks.size++] = callback;
mrb_value args[2];
args[0] = mrb_str_new_cstr(mrb, name);
args[1] = mrb_fixnum_value(-(int)shared_ctx->callbacks.size);
mrb_funcall_argv(mrb, mrb_top_self(mrb), mrb_intern_lit(mrb, "_h2o_define_callback"), 2, args);
if (mrb->exc != NULL) {
h2o_error_printf("failed to define mruby function: %s\n", name);
h2o_mruby_assert(mrb);
}
}
mrb_value h2o_mruby_create_data_instance(mrb_state *mrb, mrb_value class_obj, void *ptr, const mrb_data_type *type)
{
struct RClass *klass = mrb_class_ptr(class_obj);
struct RData *data = mrb_data_object_alloc(mrb, klass, ptr, type);
return mrb_obj_value(data);
}
struct RProc *h2o_mruby_compile_code(mrb_state *mrb, h2o_mruby_config_vars_t *config, char *errbuf)
{
mrbc_context *cxt;
struct mrb_parser_state *parser;
struct RProc *proc = NULL;
/* parse */
if ((cxt = mrbc_context_new(mrb)) == NULL) {
h2o_error_printf("%s: no memory\n", H2O_MRUBY_MODULE_NAME);
abort();
}
if (config->path != NULL)
mrbc_filename(mrb, cxt, config->path);
cxt->capture_errors = 1;
cxt->lineno = config->lineno;
if ((parser = mrb_parse_nstring(mrb, config->source.base, (int)config->source.len, cxt)) == NULL) {
h2o_error_printf("%s: no memory\n", H2O_MRUBY_MODULE_NAME);
abort();
}
/* return erro if errbuf is supplied, or abort */
if (parser->nerr != 0) {
if (errbuf == NULL) {
h2o_error_printf("%s: internal error (unexpected state)\n", H2O_MRUBY_MODULE_NAME);
abort();
}
snprintf(errbuf, 256, "line %d:%s", parser->error_buffer[0].lineno, parser->error_buffer[0].message);
strcat(errbuf, "\n\n");
if (h2o_str_at_position(errbuf + strlen(errbuf), config->source.base, config->source.len,
parser->error_buffer[0].lineno - config->lineno + 1, parser->error_buffer[0].column) != 0) {
/* remove trailing "\n\n" in case we failed to append the source code at the error location */
errbuf[strlen(errbuf) - 2] = '\0';
}
goto Exit;
}
/* generate code */
if ((proc = mrb_generate_code(mrb, parser)) == NULL) {
h2o_error_printf("%s: internal error (mrb_generate_code failed)\n", H2O_MRUBY_MODULE_NAME);
abort();
}
Exit:
mrb_parser_free(parser);
mrbc_context_free(mrb, cxt);
return proc;
}
static h2o_iovec_t convert_header_name_to_env(h2o_mem_pool_t *pool, const char *name, size_t len)
{
#define KEY_PREFIX "HTTP_"
#define KEY_PREFIX_LEN (sizeof(KEY_PREFIX) - 1)
h2o_iovec_t ret;
ret.len = len + KEY_PREFIX_LEN;
ret.base = h2o_mem_alloc_pool(pool, char, ret.len);
memcpy(ret.base, KEY_PREFIX, KEY_PREFIX_LEN);
char *d = ret.base + KEY_PREFIX_LEN;
for (; len != 0; ++name, --len)
*d++ = *name == '-' ? '_' : h2o_toupper(*name);
return ret;
#undef KEY_PREFIX
#undef KEY_PREFIX_LEN
}
static int handle_early_hints_header(h2o_mruby_shared_context_t *shared_ctx, h2o_iovec_t *name, h2o_iovec_t value, void *_req)
{
h2o_req_t *req = _req;
h2o_add_header_by_str(&req->pool, &req->res.headers, name->base, name->len, 1, NULL, value.base, value.len);
return 0;
}
mrb_value send_early_hints_proc(mrb_state *mrb, mrb_value self)
{
mrb_value headers;
mrb_get_args(mrb, "H", &headers);
h2o_mruby_generator_t *generator = h2o_mruby_get_generator(mrb, mrb_proc_cfunc_env_get(mrb, 0));
if (generator == NULL)
return mrb_nil_value();
if (h2o_mruby_iterate_rack_headers(mrb->ud, headers, handle_early_hints_header, generator->req) == -1)
mrb_exc_raise(mrb, mrb_obj_value(mrb->exc));
generator->req->res.status = 103;
h2o_send_informational(generator->req);
return mrb_nil_value();
}
static mrb_value build_constants(mrb_state *mrb, const char *server_name, size_t server_name_len)
{
mrb_value ary = mrb_ary_new_capa(mrb, H2O_MRUBY_NUM_CONSTANTS);
mrb_int i;
int gc_arena = mrb_gc_arena_save(mrb);
{
h2o_mem_pool_t pool;
h2o_mem_init_pool(&pool);
for (i = 0; i != H2O_MAX_TOKENS; ++i) {
const h2o_token_t *token = h2o__tokens + i;
if (token->buf.len == 0)
continue;
mrb_value lit = h2o_mruby_new_str(mrb, token->buf.base, token->buf.len);
FREEZE_STRING(lit);
mrb_ary_set(mrb, ary, i, lit);
}
for (; i != H2O_MAX_TOKENS * 2; ++i) {
const h2o_token_t *token = h2o__tokens + i - H2O_MAX_TOKENS;
mrb_value lit = mrb_nil_value();
if (token == H2O_TOKEN_CONTENT_TYPE) {
lit = mrb_str_new_lit(mrb, "CONTENT_TYPE");
} else if (token->buf.len != 0) {
h2o_iovec_t n = convert_header_name_to_env(&pool, token->buf.base, token->buf.len);
lit = h2o_mruby_new_str(mrb, n.base, n.len);
}
if (mrb_string_p(lit)) {
FREEZE_STRING(lit);
mrb_ary_set(mrb, ary, i, lit);
}
}
h2o_mem_clear_pool(&pool);
}
#define SET_STRING(idx, value) \
do { \
mrb_value lit = (value); \
FREEZE_STRING(lit); \
mrb_ary_set(mrb, ary, idx, lit); \
} while (0)
#define SET_LITERAL(idx, str) SET_STRING(idx, mrb_str_new_lit(mrb, str))
SET_LITERAL(H2O_MRUBY_LIT_REQUEST_METHOD, "REQUEST_METHOD");
SET_LITERAL(H2O_MRUBY_LIT_SCRIPT_NAME, "SCRIPT_NAME");
SET_LITERAL(H2O_MRUBY_LIT_PATH_INFO, "PATH_INFO");
SET_LITERAL(H2O_MRUBY_LIT_QUERY_STRING, "QUERY_STRING");
SET_LITERAL(H2O_MRUBY_LIT_SERVER_NAME, "SERVER_NAME");
SET_LITERAL(H2O_MRUBY_LIT_SERVER_ADDR, "SERVER_ADDR");
SET_LITERAL(H2O_MRUBY_LIT_SERVER_PORT, "SERVER_PORT");
SET_LITERAL(H2O_MRUBY_LIT_SERVER_PROTOCOL, "SERVER_PROTOCOL");
SET_LITERAL(H2O_MRUBY_LIT_CONTENT_LENGTH, "CONTENT_LENGTH");
SET_LITERAL(H2O_MRUBY_LIT_REMOTE_ADDR, "REMOTE_ADDR");
SET_LITERAL(H2O_MRUBY_LIT_REMOTE_PORT, "REMOTE_PORT");
SET_LITERAL(H2O_MRUBY_LIT_REMOTE_USER, "REMOTE_USER");
SET_LITERAL(H2O_MRUBY_LIT_RACK_URL_SCHEME, "rack.url_scheme");
SET_LITERAL(H2O_MRUBY_LIT_RACK_MULTITHREAD, "rack.multithread");
SET_LITERAL(H2O_MRUBY_LIT_RACK_MULTIPROCESS, "rack.multiprocess");
SET_LITERAL(H2O_MRUBY_LIT_RACK_RUN_ONCE, "rack.run_once");
SET_LITERAL(H2O_MRUBY_LIT_RACK_HIJACK_, "rack.hijack?");
SET_LITERAL(H2O_MRUBY_LIT_RACK_INPUT, "rack.input");
SET_LITERAL(H2O_MRUBY_LIT_RACK_ERRORS, "rack.errors");
SET_LITERAL(H2O_MRUBY_LIT_RACK_EARLY_HINTS, "rack.early_hints");
SET_LITERAL(H2O_MRUBY_LIT_SERVER_SOFTWARE, "SERVER_SOFTWARE");
SET_LITERAL(H2O_MRUBY_LIT_H2O_REMAINING_DELEGATIONS, "h2o.remaining_delegations");
SET_LITERAL(H2O_MRUBY_LIT_H2O_REMAINING_REPROCESSES, "h2o.remaining_reprocesses");
SET_STRING(H2O_MRUBY_LIT_SERVER_SOFTWARE_VALUE, h2o_mruby_new_str(mrb, server_name, server_name_len));
#undef SET_LITERAL
#undef SET_STRING
h2o_mruby_eval_expr_location(mrb, H2O_MRUBY_CODE_CORE, "(h2o)lib/handler/mruby/embedded/core.rb", 1);
h2o_mruby_assert(mrb);
mrb_ary_set(mrb, ary, H2O_MRUBY_PROC_EACH_TO_ARRAY,
mrb_funcall(mrb, mrb_obj_value(mrb->kernel_module), "_h2o_proc_each_to_array", 0));
h2o_mruby_assert(mrb);
mrb_gc_arena_restore(mrb, gc_arena);
return ary;
}
static void handle_exception(h2o_mruby_context_t *ctx, h2o_mruby_generator_t *generator)
{
mrb_state *mrb = ctx->shared->mrb;
assert(mrb->exc != NULL);
if (generator == NULL || generator->req->_generator != NULL) {
h2o_error_printf("mruby raised: %s\n", RSTRING_PTR(mrb_inspect(mrb, mrb_obj_value(mrb->exc))));
} else {
h2o_req_log_error(generator->req, H2O_MRUBY_MODULE_NAME, "mruby raised: %s\n",
RSTRING_PTR(mrb_inspect(mrb, mrb_obj_value(mrb->exc))));
h2o_send_error_500(generator->req, "Internal Server Error", "Internal Server Error", 0);
}
mrb->exc = NULL;
}
mrb_value send_error_callback(h2o_mruby_context_t *ctx, mrb_value input, mrb_value *receiver, mrb_value args, int *run_again)
{
mrb_state *mrb = ctx->shared->mrb;
mrb->exc = mrb_obj_ptr(mrb_ary_entry(args, 0));
h2o_mruby_generator_t *generator = h2o_mruby_get_generator(mrb, mrb_ary_entry(args, 1));
handle_exception(ctx, generator);
return mrb_nil_value();
}
mrb_value block_request_callback(h2o_mruby_context_t *ctx, mrb_value input, mrb_value *receiver, mrb_value args, int *run_again)
{
mrb_state *mrb = ctx->shared->mrb;
mrb_value blocking_req = mrb_ary_new_capa(mrb, 2);
mrb_ary_set(mrb, blocking_req, 0, ctx->proc);
mrb_ary_set(mrb, blocking_req, 1, input);
mrb_ary_push(mrb, ctx->blocking_reqs, blocking_req);
return mrb_nil_value();
}
mrb_value run_blocking_requests_callback(h2o_mruby_context_t *ctx, mrb_value input, mrb_value *receiver, mrb_value args,
int *run_again)
{
mrb_state *mrb = ctx->shared->mrb;
mrb_value exc = mrb_ary_entry(args, 0);
if (!mrb_nil_p(exc)) {
mrb->exc = mrb_obj_ptr(exc);
handle_exception(ctx, NULL);
}
mrb_int i;
mrb_int len = RARRAY_LEN(ctx->blocking_reqs);
for (i = 0; i != len; ++i) {
mrb_value blocking_req = mrb_ary_entry(ctx->blocking_reqs, i);
mrb_value blocking_req_resumer = mrb_ary_entry(blocking_req, 0);
mrb_value blocking_req_input = mrb_ary_entry(blocking_req, 1);
h2o_mruby_run_fiber(ctx, blocking_req_resumer, blocking_req_input, NULL);
}
mrb_ary_clear(mrb, ctx->blocking_reqs);
return mrb_nil_value();
}
mrb_value run_child_fiber_callback(h2o_mruby_context_t *ctx, mrb_value input, mrb_value *receiver, mrb_value args, int *run_again)
{
mrb_state *mrb = ctx->shared->mrb;
mrb_value resumer = mrb_ary_entry(args, 0);
/*
* swap receiver to run child fiber immediately, while storing main fiber resumer
* which will be called after the child fiber is yielded
*/
mrb_ary_push(mrb, ctx->resumers, *receiver);
*receiver = resumer;
*run_again = 1;
return mrb_nil_value();
}
mrb_value finish_child_fiber_callback(h2o_mruby_context_t *ctx, mrb_value input, mrb_value *receiver, mrb_value args,
int *run_again)
{
/* do nothing */
return mrb_nil_value();
}
static mrb_value error_stream_write(mrb_state *mrb, mrb_value self)
{
h2o_mruby_error_stream_t *error_stream;
if ((error_stream = h2o_mruby_get_error_stream(mrb, self)) == NULL) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "ErrorStream#write wrong self");
}
mrb_value msgstr;
mrb_get_args(mrb, "o", &msgstr);
msgstr = h2o_mruby_to_str(mrb, msgstr);
h2o_iovec_t msg = h2o_iovec_init(RSTRING_PTR(msgstr), RSTRING_LEN(msgstr));
if (error_stream->generator != NULL) {
h2o_req_t *req = error_stream->generator->req;
req->error_log_delegate.cb(req->error_log_delegate.data, h2o_iovec_init(NULL, 0), msg);
} else if (error_stream->ctx->handler->pathconf->error_log.emit_request_errors) {
h2o_write_error_log(h2o_iovec_init(NULL, 0), msg);
}
return mrb_fixnum_value(msg.len);
}
static h2o_mruby_shared_context_t *create_shared_context(h2o_context_t *ctx)
{
/* init mruby in every thread */
h2o_mruby_shared_context_t *shared_ctx = h2o_mem_alloc(sizeof(*shared_ctx));
if ((shared_ctx->mrb = mrb_open()) == NULL) {
h2o_error_printf("%s: no memory\n", H2O_MRUBY_MODULE_NAME);
abort();
}
shared_ctx->mrb->ud = shared_ctx;
shared_ctx->ctx = ctx;
shared_ctx->current_context = NULL;
shared_ctx->callbacks = (h2o_mruby_callbacks_t){NULL};
h2o_mruby_setup_globals(shared_ctx->mrb);
shared_ctx->constants = build_constants(shared_ctx->mrb, ctx->globalconf->server_name.base, ctx->globalconf->server_name.len);
shared_ctx->symbols.sym_call = mrb_intern_lit(shared_ctx->mrb, "call");
shared_ctx->symbols.sym_close = mrb_intern_lit(shared_ctx->mrb, "close");
shared_ctx->symbols.sym_method = mrb_intern_lit(shared_ctx->mrb, "method");
shared_ctx->symbols.sym_headers = mrb_intern_lit(shared_ctx->mrb, "headers");
shared_ctx->symbols.sym_body = mrb_intern_lit(shared_ctx->mrb, "body");
shared_ctx->symbols.sym_async = mrb_intern_lit(shared_ctx->mrb, "async");
h2o_mruby_define_callback(shared_ctx->mrb, "_h2o__send_error", send_error_callback);
h2o_mruby_define_callback(shared_ctx->mrb, "_h2o__block_request", block_request_callback);
h2o_mruby_define_callback(shared_ctx->mrb, "_h2o__run_blocking_requests", run_blocking_requests_callback);
h2o_mruby_define_callback(shared_ctx->mrb, "_h2o__run_child_fiber", run_child_fiber_callback);
h2o_mruby_define_callback(shared_ctx->mrb, "_h2o__finish_child_fiber", finish_child_fiber_callback);
h2o_mruby_sender_init_context(shared_ctx);
h2o_mruby_http_request_init_context(shared_ctx);
h2o_mruby_redis_init_context(shared_ctx);
h2o_mruby_sleep_init_context(shared_ctx);
h2o_mruby_middleware_init_context(shared_ctx);
h2o_mruby_channel_init_context(shared_ctx);
struct RClass *module = mrb_define_module(shared_ctx->mrb, "H2O");
mrb_ary_set(shared_ctx->mrb, shared_ctx->constants, H2O_MRUBY_H2O_MODULE, mrb_obj_value(module));
struct RClass *generator_klass = mrb_define_class_under(shared_ctx->mrb, module, "Generator", shared_ctx->mrb->object_class);
mrb_ary_set(shared_ctx->mrb, shared_ctx->constants, H2O_MRUBY_GENERATOR_CLASS, mrb_obj_value(generator_klass));
struct RClass *error_stream_class = mrb_class_get_under(shared_ctx->mrb, module, "ErrorStream");
mrb_ary_set(shared_ctx->mrb, shared_ctx->constants, H2O_MRUBY_ERROR_STREAM_CLASS, mrb_obj_value(error_stream_class));
mrb_define_method(shared_ctx->mrb, error_stream_class, "write", error_stream_write, MRB_ARGS_REQ(1));
return shared_ctx;
}
static void dispose_shared_context(void *data)
{
if (data == NULL)
return;
h2o_mruby_shared_context_t *shared_ctx = (h2o_mruby_shared_context_t *)data;
mrb_close(shared_ctx->mrb);
free(shared_ctx);
}
static h2o_mruby_shared_context_t *get_shared_context(h2o_context_t *ctx)
{
static size_t key = SIZE_MAX;
void **data = h2o_context_get_storage(ctx, &key, dispose_shared_context);
if (*data == NULL) {
*data = create_shared_context(ctx);
}
return *data;
}
mrb_value prepare_fibers(h2o_mruby_context_t *ctx)
{
mrb_state *mrb = ctx->shared->mrb;
h2o_mruby_config_vars_t config = ctx->handler->config;
mrb_value conf = mrb_hash_new_capa(mrb, 3);
mrb_hash_set(mrb, conf, mrb_symbol_value(mrb_intern_lit(mrb, "code")),
h2o_mruby_new_str(mrb, config.source.base, config.source.len));
mrb_hash_set(mrb, conf, mrb_symbol_value(mrb_intern_lit(mrb, "file")),
h2o_mruby_new_str(mrb, config.path, strlen(config.path)));
mrb_hash_set(mrb, conf, mrb_symbol_value(mrb_intern_lit(mrb, "line")), mrb_fixnum_value(config.lineno));
/* run code and generate handler */
mrb_value result = mrb_funcall(mrb, mrb_obj_value(mrb->kernel_module), "_h2o_prepare_app", 1, conf);
h2o_mruby_assert(mrb);
assert(mrb_array_p(result));
return result;
}
static void on_context_init(h2o_handler_t *_handler, h2o_context_t *ctx)
{
h2o_mruby_handler_t *handler = (void *)_handler;
h2o_mruby_context_t *handler_ctx = h2o_mem_alloc(sizeof(*handler_ctx));
handler_ctx->handler = handler;
handler_ctx->shared = get_shared_context(ctx);
mrb_state *mrb = handler_ctx->shared->mrb;
handler_ctx->blocking_reqs = mrb_ary_new(mrb);
handler_ctx->resumers = mrb_ary_new(mrb);
/* compile code (must be done for each thread) */
int arena = mrb_gc_arena_save(mrb);
mrb_value fibers = prepare_fibers(handler_ctx);
assert(mrb_array_p(fibers));
handler_ctx->proc = mrb_ary_entry(fibers, 0);
/* run configurator */
mrb_value configurator = mrb_ary_entry(fibers, 1);
h2o_mruby_run_fiber(handler_ctx, configurator, mrb_nil_value(), NULL);
h2o_mruby_assert(handler_ctx->shared->mrb);
mrb_gc_arena_restore(mrb, arena);
mrb_gc_protect(mrb, handler_ctx->proc);
mrb_gc_protect(mrb, configurator);
h2o_context_set_handler_context(ctx, &handler->super, handler_ctx);
}
static void on_context_dispose(h2o_handler_t *_handler, h2o_context_t *ctx)
{
h2o_mruby_handler_t *handler = (void *)_handler;
h2o_mruby_context_t *handler_ctx = h2o_context_get_handler_context(ctx, &handler->super);
if (handler_ctx == NULL)
return;
free(handler_ctx);
}
static void on_handler_dispose(h2o_handler_t *_handler)
{
h2o_mruby_handler_t *handler = (void *)_handler;
free(handler->config.source.base);
free(handler->config.path);
free(handler);
}
static void stringify_address(h2o_conn_t *conn, socklen_t (*cb)(h2o_conn_t *conn, struct sockaddr *), mrb_state *mrb,
mrb_value *host, mrb_value *port)
{
struct sockaddr_storage ss;
socklen_t sslen;
char buf[NI_MAXHOST];
*host = mrb_nil_value();
*port = mrb_nil_value();
if ((sslen = cb(conn, (void *)&ss)) == 0)
return;
size_t l = h2o_socket_getnumerichost((void *)&ss, sslen, buf);
if (l != SIZE_MAX)
*host = h2o_mruby_new_str(mrb, buf, l);
int32_t p = h2o_socket_getport((void *)&ss);
if (p != -1) {
l = (int)sprintf(buf, "%" PRIu16, (uint16_t)p);
*port = h2o_mruby_new_str(mrb, buf, l);
}
}
static void on_rack_input_free(mrb_state *mrb, const char *base, mrb_int len, void *_input_stream)
{
/* reset ref to input_stream */
mrb_value *input_stream = _input_stream;
*input_stream = mrb_nil_value();
}
static int build_env_sort_header_cb(const void *_x, const void *_y)
{
const h2o_header_t *x = *(const h2o_header_t **)_x, *y = *(const h2o_header_t **)_y;
if (x->name->len < y->name->len)
return -1;
if (x->name->len > y->name->len)
return 1;
if (x->name->base != y->name->base) {
int r = memcmp(x->name->base, y->name->base, x->name->len);
if (r != 0)
return r;
}
assert(x != y);
/* the order of the headers having the same name needs to be retained */
return x < y ? -1 : 1;
}
static mrb_value build_path_info(mrb_state *mrb, h2o_req_t *req, size_t confpath_len_wo_slash)
{
if (req->path_normalized.len == confpath_len_wo_slash)
return mrb_str_new_lit(mrb, "");
assert(req->path_normalized.len > confpath_len_wo_slash);
size_t path_info_start, path_info_end = req->query_at != SIZE_MAX ? req->query_at : req->path.len;
if (req->norm_indexes == NULL) {
path_info_start = confpath_len_wo_slash;
} else if (req->norm_indexes[0] == 0 && confpath_len_wo_slash == 0) {
/* path without leading slash */
path_info_start = 0;
} else {
path_info_start = req->norm_indexes[confpath_len_wo_slash] - 1;
}
return h2o_mruby_new_str(mrb, req->path.base + path_info_start, path_info_end - path_info_start);
}
int h2o_mruby_iterate_native_headers(h2o_mruby_shared_context_t *shared_ctx, h2o_mem_pool_t *pool, h2o_headers_t *headers,
int (*cb)(h2o_mruby_shared_context_t *, h2o_mem_pool_t *, h2o_header_t *, void *),
void *cb_data)
{
h2o_header_t **sorted = alloca(sizeof(*sorted) * headers->size);
size_t i, num_sorted = 0;
for (i = 0; i != headers->size; ++i) {
if (headers->entries[i].name == &H2O_TOKEN_TRANSFER_ENCODING->buf)
continue;
sorted[num_sorted++] = headers->entries + i;
}
qsort(sorted, num_sorted, sizeof(*sorted), build_env_sort_header_cb);
h2o_iovec_t *values = alloca(sizeof(*values) * (num_sorted * 2 - 1));
for (i = 0; i != num_sorted; ++i) {
/* build flattened value of the header field values that have the same name as sorted[i] */
size_t num_values = 0;
values[num_values++] = sorted[i]->value;
while (i < num_sorted - 1 && h2o_header_name_is_equal(sorted[i], sorted[i + 1])) {
++i;
values[num_values++] = h2o_iovec_init(sorted[i]->name == &H2O_TOKEN_COOKIE->buf ? "; " : ", ", 2);
values[num_values++] = sorted[i]->value;
}
h2o_header_t h = *sorted[i];
h.value = num_values == 1 ? values[0] : h2o_concat_list(pool, values, num_values);
if (cb(shared_ctx, pool, &h, cb_data) != 0) {
assert(shared_ctx->mrb->exc != NULL);
return -1;
}
}
return 0;
}
static int iterate_headers_callback(h2o_mruby_shared_context_t *shared_ctx, h2o_mem_pool_t *pool, h2o_header_t *header,
void *cb_data)
{
mrb_value env = mrb_obj_value(cb_data);
mrb_value n;
if (h2o_iovec_is_token(header->name)) {
const h2o_token_t *token = H2O_STRUCT_FROM_MEMBER(h2o_token_t, buf, header->name);
n = h2o_mruby_token_env_key(shared_ctx, token);
} else {
h2o_iovec_t vec = convert_header_name_to_env(pool, header->name->base, header->name->len);
n = h2o_mruby_new_str(shared_ctx->mrb, vec.base, vec.len);
}
mrb_value v = h2o_mruby_new_str(shared_ctx->mrb, header->value.base, header->value.len);
mrb_hash_set(shared_ctx->mrb, env, n, v);
return 0;
}
mrb_value h2o_mruby_token_string(h2o_mruby_shared_context_t *shared, const h2o_token_t *token)
{
return mrb_ary_entry(shared->constants, token - h2o__tokens);
}
mrb_value h2o_mruby_token_env_key(h2o_mruby_shared_context_t *shared, const h2o_token_t *token)
{
return mrb_ary_entry(shared->constants, token - h2o__tokens + H2O_MAX_TOKENS);
}
static mrb_value build_env(h2o_mruby_generator_t *generator)
{
h2o_mruby_shared_context_t *shared = generator->ctx->shared;
mrb_state *mrb = shared->mrb;
mrb_value env = mrb_hash_new_capa(mrb, 16);
char http_version[sizeof("HTTP/1.0")];
size_t http_version_sz;
/* environment */
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_REQUEST_METHOD),
h2o_mruby_new_str(mrb, generator->req->method.base, generator->req->method.len));
size_t confpath_len_wo_slash = generator->req->pathconf->path.len;
if (generator->req->pathconf->path.base[generator->req->pathconf->path.len - 1] == '/')
--confpath_len_wo_slash;
assert(confpath_len_wo_slash <= generator->req->path_normalized.len);
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_SCRIPT_NAME),
h2o_mruby_new_str(mrb, generator->req->pathconf->path.base, confpath_len_wo_slash));
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_PATH_INFO),
build_path_info(mrb, generator->req, confpath_len_wo_slash));
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_QUERY_STRING),
generator->req->query_at != SIZE_MAX
? h2o_mruby_new_str(mrb, generator->req->path.base + generator->req->query_at + 1,
generator->req->path.len - (generator->req->query_at + 1))
: mrb_str_new_lit(mrb, ""));
mrb_hash_set(
mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_SERVER_NAME),
h2o_mruby_new_str(mrb, generator->req->hostconf->authority.host.base, generator->req->hostconf->authority.host.len));
http_version_sz = h2o_stringify_protocol_version(http_version, generator->req->version);
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_SERVER_PROTOCOL),
h2o_mruby_new_str(mrb, http_version, http_version_sz));
{
mrb_value h, p;
stringify_address(generator->req->conn, generator->req->conn->callbacks->get_sockname, mrb, &h, &p);
if (!mrb_nil_p(h))
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_SERVER_ADDR), h);
if (!mrb_nil_p(p))
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_SERVER_PORT), p);
}
mrb_hash_set(mrb, env, h2o_mruby_token_env_key(shared, H2O_TOKEN_HOST),
h2o_mruby_new_str(mrb, generator->req->authority.base, generator->req->authority.len));
if (generator->req->entity.base != NULL) {
char buf[32];
int l = sprintf(buf, "%zu", generator->req->entity.len);
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_CONTENT_LENGTH), h2o_mruby_new_str(mrb, buf, l));
generator->rack_input = mrb_input_stream_value(mrb, NULL, 0);
mrb_input_stream_set_data(mrb, generator->rack_input, generator->req->entity.base, (mrb_int)generator->req->entity.len, 0,
on_rack_input_free, &generator->rack_input);
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_INPUT), generator->rack_input);
}
{
mrb_value h, p;
stringify_address(generator->req->conn, generator->req->conn->callbacks->get_peername, mrb, &h, &p);
if (!mrb_nil_p(h))
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_REMOTE_ADDR), h);
if (!mrb_nil_p(p))
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_REMOTE_PORT), p);
}
{
size_t i;
for (i = 0; i != generator->req->env.size; i += 2) {
h2o_iovec_t *name = generator->req->env.entries + i, *value = name + 1;
mrb_hash_set(mrb, env, h2o_mruby_new_str(mrb, name->base, name->len), h2o_mruby_new_str(mrb, value->base, value->len));
}
}
/* headers */
h2o_mruby_iterate_native_headers(shared, &generator->req->pool, &generator->req->headers, iterate_headers_callback,
mrb_obj_ptr(env));
mrb_value early_data_key = h2o_mruby_token_env_key(shared, H2O_TOKEN_EARLY_DATA);
int found_early_data = !mrb_nil_p(mrb_hash_fetch(mrb, env, early_data_key, mrb_nil_value()));
if (!found_early_data && h2o_conn_is_early_data(generator->req->conn)) {
mrb_hash_set(mrb, env, early_data_key, h2o_mruby_new_str(mrb, "1", 1));
generator->req->reprocess_if_too_early = 1;
}
/* rack.* */
/* TBD rack.version? */
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_URL_SCHEME),
h2o_mruby_new_str(mrb, generator->req->scheme->name.base, generator->req->scheme->name.len));
/* we are using shared-none architecture, and therefore declare ourselves as multiprocess */
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_MULTITHREAD), mrb_false_value());
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_MULTIPROCESS), mrb_true_value());
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_RUN_ONCE), mrb_false_value());
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_HIJACK_), mrb_false_value());
mrb_value error_stream = h2o_mruby_create_data_instance(
shared->mrb, mrb_ary_entry(shared->constants, H2O_MRUBY_ERROR_STREAM_CLASS), generator->error_stream, &error_stream_type);
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_ERRORS), error_stream);
generator->refs.error_stream = error_stream;
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_RACK_EARLY_HINTS),
mrb_obj_value(mrb_proc_new_cfunc_with_env(mrb, send_early_hints_proc, 1, &generator->refs.generator)));
/* server name */
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_SERVER_SOFTWARE),
mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_SERVER_SOFTWARE_VALUE));
/* h2o specific */
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_H2O_REMAINING_DELEGATIONS),
mrb_fixnum_value(generator->req->remaining_delegations));
mrb_hash_set(mrb, env, mrb_ary_entry(shared->constants, H2O_MRUBY_LIT_H2O_REMAINING_REPROCESSES),
mrb_fixnum_value(generator->req->remaining_reprocesses));
return env;
}
int h2o_mruby_set_response_header(h2o_mruby_shared_context_t *shared_ctx, h2o_iovec_t *name, h2o_iovec_t value, void *_req)
{
h2o_req_t *req = _req;
const h2o_token_t *token;
static const h2o_iovec_t fallthru_set_prefix = {H2O_STRLIT(FALLTHRU_SET_PREFIX)};
h2o_iovec_t lc_name;
if (h2o_iovec_is_token(name)) {
token = H2O_STRUCT_FROM_MEMBER(h2o_token_t, buf, name);
} else {
/* convert name to lowercase */
lc_name = h2o_strdup(&req->pool, name->base, name->len);
h2o_strtolower(lc_name.base, lc_name.len);
token = h2o_lookup_token(lc_name.base, lc_name.len);
}
if (token != NULL) {
if (token->flags.proxy_should_drop_for_res) {
/* skip */
} else if (token == H2O_TOKEN_CONTENT_LENGTH) {
req->res.content_length = h2o_strtosize(value.base, value.len);
} else {
value = h2o_strdup(&req->pool, value.base, value.len);
if (token == H2O_TOKEN_LINK) {
h2o_iovec_t new_value = h2o_push_path_in_link_header(req, value.base, value.len);
if (new_value.len)
h2o_add_header(&req->pool, &req->res.headers, token, NULL, new_value.base, new_value.len);
} else {
h2o_add_header(&req->pool, &req->res.headers, token, NULL, value.base, value.len);
}
}
} else if (lc_name.len > fallthru_set_prefix.len &&
h2o_memis(lc_name.base, fallthru_set_prefix.len, fallthru_set_prefix.base, fallthru_set_prefix.len)) {
/* register environment variables (with the name converted to uppercase, and using `_`) */
size_t i;
lc_name.base += fallthru_set_prefix.len;
lc_name.len -= fallthru_set_prefix.len;
for (i = 0; i != lc_name.len; ++i)
lc_name.base[i] = lc_name.base[i] == '-' ? '_' : h2o_toupper(lc_name.base[i]);
h2o_iovec_t *slot = h2o_req_getenv(req, lc_name.base, lc_name.len, 1);
*slot = h2o_strdup(&req->pool, value.base, value.len);
} else {
value = h2o_strdup(&req->pool, value.base, value.len);
h2o_add_header_by_str(&req->pool, &req->res.headers, lc_name.base, lc_name.len, 0, NULL, value.base, value.len);
}
return 0;
}
static void clear_rack_input(h2o_mruby_generator_t *generator)
{
if (!mrb_nil_p(generator->rack_input))
mrb_input_stream_set_data(generator->ctx->shared->mrb, generator->rack_input, NULL, -1, 0, NULL, NULL);
}
static void on_generator_dispose(void *_generator)
{
h2o_mruby_generator_t *generator = _generator;
clear_rack_input(generator);
generator->req = NULL;
if (!mrb_nil_p(generator->refs.generator))
DATA_PTR(generator->refs.generator) = NULL;
if (generator->error_stream != NULL)
generator->error_stream->generator = NULL;
if (generator->sender != NULL)
generator->sender->dispose(generator);
}
static int on_req(h2o_handler_t *_handler, h2o_req_t *req)
{
h2o_mruby_handler_t *handler = (void *)_handler;
h2o_mruby_shared_context_t *shared = get_shared_context(req->conn->ctx);
int gc_arena = mrb_gc_arena_save(shared->mrb);
h2o_mruby_context_t *ctx = h2o_context_get_handler_context(req->conn->ctx, &handler->super);
h2o_mruby_generator_t *generator = h2o_mem_alloc_shared(&req->pool, sizeof(*generator), on_generator_dispose);
generator->super.proceed = NULL;
generator->super.stop = NULL;
generator->req = req;
generator->ctx = ctx;
generator->rack_input = mrb_nil_value();
generator->sender = NULL;
generator->error_stream = h2o_mem_alloc(sizeof(*generator->error_stream));
generator->error_stream->ctx = ctx;
generator->error_stream->generator = generator;
mrb_value gen = h2o_mruby_create_data_instance(shared->mrb, mrb_ary_entry(shared->constants, H2O_MRUBY_GENERATOR_CLASS),
generator, &generator_type);
generator->refs.generator = gen;
mrb_value env = build_env(generator);
mrb_value args = mrb_ary_new(shared->mrb);
mrb_ary_set(shared->mrb, args, 0, env);
mrb_ary_set(shared->mrb, args, 1, gen);
int is_delegate = 0;
h2o_mruby_run_fiber(ctx, ctx->proc, args, &is_delegate);
mrb_gc_arena_restore(shared->mrb, gc_arena);
if (is_delegate)
return -1;
return 0;
}
static int send_response(h2o_mruby_generator_t *generator, mrb_int status, mrb_value resp, int *is_delegate)
{
mrb_state *mrb = generator->ctx->shared->mrb;
mrb_value body;
h2o_iovec_t content = {NULL};
/* set status */
generator->req->res.status = (int)status;
/* set headers */
if (h2o_mruby_iterate_rack_headers(generator->ctx->shared, mrb_ary_entry(resp, 1), h2o_mruby_set_response_header,
generator->req) != 0) {
return -1;
}
/* return without processing body, if status is fallthru */
if (generator->req->res.status == STATUS_FALLTHRU) {
if (is_delegate != NULL) {
*is_delegate = 1;
} else {
assert(generator->req->handler == &generator->ctx->handler->super);
h2o_delegate_request_deferred(generator->req);
}
return 0;
}
/* add date: if it's missing from the response */
if (h2o_find_header(&generator->req->res.headers, H2O_TOKEN_DATE, SIZE_MAX) == -1)
h2o_resp_add_date_header(generator->req);
/* obtain body */
body = mrb_ary_entry(resp, 2);
/* flatten body if possible */
if (mrb_array_p(body)) {
mrb_int i, len = RARRAY_LEN(body);
/* calculate the length of the output, while at the same time converting the elements of the output array to string */
content.len = 0;
for (i = 0; i != len; ++i) {
mrb_value e = mrb_ary_entry(body, i);
if (!mrb_string_p(e)) {
e = h2o_mruby_to_str(mrb, e);
if (mrb->exc != NULL)
return -1;
mrb_ary_set(mrb, body, i, e);
}
content.len += RSTRING_LEN(e);
}
/* allocate memory, and copy the response */
char *dst = content.base = h2o_mem_alloc_pool(&generator->req->pool, char, content.len);
for (i = 0; i != len; ++i) {
mrb_value e = mrb_ary_entry(body, i);
assert(mrb_string_p(e));
memcpy(dst, RSTRING_PTR(e), RSTRING_LEN(e));
dst += RSTRING_LEN(e);
}
/* reset body to nil, now that we have read all data */
body = mrb_nil_value();
}
/* use fiber in case we need to call #each */
if (!mrb_nil_p(body)) {
if (h2o_mruby_init_sender(generator, body) != 0)
return -1;
h2o_start_response(generator->req, &generator->super);
generator->sender->start(generator);
return 0;
}
/* send the entire response immediately */
if (status == 101 || status == 204 || status == 304 ||
h2o_memis(generator->req->input.method.base, generator->req->input.method.len, H2O_STRLIT("HEAD"))) {
h2o_start_response(generator->req, &generator->super);
h2o_send(generator->req, NULL, 0, H2O_SEND_STATE_FINAL);
} else {
if (content.len < generator->req->res.content_length) {
generator->req->res.content_length = content.len;
} else {
content.len = generator->req->res.content_length;
}
h2o_start_response(generator->req, &generator->super);
h2o_send(generator->req, &content, 1, H2O_SEND_STATE_FINAL);
}
return 0;
}
void h2o_mruby_run_fiber(h2o_mruby_context_t *ctx, mrb_value receiver, mrb_value input, int *is_delegate)
{
h2o_mruby_context_t *old_ctx = ctx->shared->current_context;
ctx->shared->current_context = ctx;
mrb_state *mrb = ctx->shared->mrb;
mrb_value output, resp;
mrb_int status = 0;
h2o_mruby_generator_t *generator = NULL;
h2o_mruby_send_response_callback_t send_response_callback = NULL;
while (1) {
/* send input to fiber */
output = mrb_funcall_argv(mrb, receiver, ctx->shared->symbols.sym_call, 1, &input);
if (mrb->exc != NULL)
goto GotException;
if (!mrb_array_p(output)) {
mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, "Fiber.yield must return an array"));
goto GotException;
}
resp = mrb_ary_entry(output, 0);
if (!mrb_array_p(resp)) {
if ((send_response_callback = h2o_mruby_middleware_get_send_response_callback(ctx, resp)) != NULL) {
break;
} else {
mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, "rack app did not return an array"));
goto GotException;
}
}
/* fetch status */
H2O_MRUBY_EXEC_GUARD({ status = mrb_int(mrb, mrb_ary_entry(resp, 0)); });
if (mrb->exc != NULL)
goto GotException;
if (status >= 0) {
if (!(100 <= status && status <= 999)) {
mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, "status returned from rack app is out of range"));
goto GotException;
}
break;
}
receiver = mrb_ary_entry(resp, 1);
mrb_value args = mrb_ary_entry(resp, 2);
int run_again = 0;
size_t callback_index = -status - 1;
if (callback_index >= ctx->shared->callbacks.size) {
input = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, "unexpected callback id sent from rack app");
run_again = 1;
} else {
h2o_mruby_callback_t callback = ctx->shared->callbacks.entries[callback_index];
input = callback(ctx, input, &receiver, args, &run_again);
}
if (mrb->exc != NULL)
goto GotException;
if (run_again == 0) {
if (RARRAY_LEN(ctx->resumers) == 0)
goto Exit;
receiver = mrb_ary_pop(mrb, ctx->resumers);
}
mrb_gc_protect(mrb, receiver);
mrb_gc_protect(mrb, input);
}
/* retrieve and validate generator */
generator = h2o_mruby_get_generator(mrb, mrb_ary_entry(output, 1));
if (generator == NULL)
goto Exit; /* do nothing if req is already closed */
if (send_response_callback == NULL)
send_response_callback = send_response;
if (send_response_callback(generator, status, resp, is_delegate) != 0)
goto GotException;
goto Exit;
GotException:
if (generator == NULL && mrb_array_p(output))
generator = h2o_mruby_get_generator(mrb, mrb_ary_entry(output, 1));
handle_exception(ctx, generator);
Exit:
ctx->shared->current_context = old_ctx;
}
h2o_mruby_handler_t *h2o_mruby_register(h2o_pathconf_t *pathconf, h2o_mruby_config_vars_t *vars)
{
h2o_mruby_handler_t *handler = (void *)h2o_create_handler(pathconf, sizeof(*handler));
handler->super.on_context_init = on_context_init;
handler->super.on_context_dispose = on_context_dispose;
handler->super.dispose = on_handler_dispose;
handler->super.on_req = on_req;
handler->config.source = h2o_strdup(NULL, vars->source.base, vars->source.len);
if (vars->path != NULL)
handler->config.path = h2o_strdup(NULL, vars->path, SIZE_MAX).base;
handler->config.lineno = vars->lineno;
handler->pathconf = pathconf;
return handler;
}
mrb_value h2o_mruby_each_to_array(h2o_mruby_shared_context_t *shared_ctx, mrb_value src)
{
return mrb_funcall_argv(shared_ctx->mrb, mrb_ary_entry(shared_ctx->constants, H2O_MRUBY_PROC_EACH_TO_ARRAY),
shared_ctx->symbols.sym_call, 1, &src);
}
int h2o_mruby_iterate_header_values(h2o_mruby_shared_context_t *shared_ctx, mrb_value name, mrb_value value,
int (*cb)(h2o_mruby_shared_context_t *, h2o_iovec_t *, h2o_iovec_t, void *), void *cb_data)
{
mrb_state *mrb = shared_ctx->mrb;
h2o_iovec_t namevec;
/* convert name and value to string */
name = h2o_mruby_to_str(mrb, name);
if (mrb->exc != NULL)
return -1;
namevec = (h2o_iovec_init(RSTRING_PTR(name), RSTRING_LEN(name)));
value = h2o_mruby_to_str(mrb, value);
if (mrb->exc != NULL)
return -1;
/* call the callback, splitting the values with '\n' */
const char *vstart = RSTRING_PTR(value), *vend = vstart + RSTRING_LEN(value), *eol;
while (1) {
for (eol = vstart; eol != vend; ++eol)
if (*eol == '\n')
break;
if (cb(shared_ctx, &namevec, h2o_iovec_init(vstart, eol - vstart), cb_data) != 0)
return -1;
if (eol == vend)
break;
vstart = eol + 1;
}
return 0;
}
int h2o_mruby_iterate_rack_headers(h2o_mruby_shared_context_t *shared_ctx, mrb_value headers,
int (*cb)(h2o_mruby_shared_context_t *, h2o_iovec_t *, h2o_iovec_t, void *), void *cb_data)
{
mrb_state *mrb = shared_ctx->mrb;
if (!(mrb_hash_p(headers) || mrb_array_p(headers))) {
headers = h2o_mruby_each_to_array(shared_ctx, headers);
if (mrb->exc != NULL)
return -1;
assert(mrb_array_p(headers));
}
if (mrb_hash_p(headers)) {
mrb_value keys = mrb_hash_keys(mrb, headers);
mrb_int i, len = RARRAY_LEN(keys);
for (i = 0; i != len; ++i) {
mrb_value k = mrb_ary_entry(keys, i);
mrb_value v = mrb_hash_get(mrb, headers, k);
if (h2o_mruby_iterate_header_values(shared_ctx, k, v, cb, cb_data) != 0)
return -1;
}
} else {
assert(mrb_array_p(headers));
mrb_int i, len = RARRAY_LEN(headers);
for (i = 0; i != len; ++i) {
mrb_value pair = mrb_ary_entry(headers, i);
if (!mrb_array_p(pair)) {
mrb->exc = mrb_obj_ptr(mrb_exc_new_str_lit(mrb, E_ARGUMENT_ERROR, "array element of headers MUST by an array"));
return -1;
}
if (h2o_mruby_iterate_header_values(shared_ctx, mrb_ary_entry(pair, 0), mrb_ary_entry(pair, 1), cb, cb_data) != 0)
return -1;
}
}
return 0;
}
| 1 | 13,613 | Should we do something like `h2o__fatal(file, line, "fatal error: %s, %s\n", mess, RSTRING_PTR(...))` here? | h2o-h2o | c |
@@ -24,7 +24,8 @@ describe('monitoring', function () {
return mock.createServer().then(server => (mockServer = server));
});
- it('should record roundTripTime', function (done) {
+ // TODO: NODE-3819: Unskip flaky tests.
+ it.skip('should record roundTripTime', function (done) {
mockServer.setMessageHandler(request => {
const doc = request.document;
if (isHello(doc)) { | 1 | 'use strict';
const mock = require('../../tools/mongodb-mock/index');
const { ServerType } = require('../../../src/sdam/common');
const { Topology } = require('../../../src/sdam/topology');
const { Monitor } = require('../../../src/sdam/monitor');
const { expect } = require('chai');
const { ServerDescription } = require('../../../src/sdam/server_description');
const { LEGACY_HELLO_COMMAND } = require('../../../src/constants');
const { isHello } = require('../../../src/utils');
class MockServer {
constructor(options) {
this.s = { pool: { generation: 1 } };
this.description = new ServerDescription(`${options.host}:${options.port}`);
this.description.type = ServerType.Unknown;
}
}
describe('monitoring', function () {
let mockServer;
after(() => mock.cleanup());
beforeEach(function () {
return mock.createServer().then(server => (mockServer = server));
});
it('should record roundTripTime', function (done) {
mockServer.setMessageHandler(request => {
const doc = request.document;
if (isHello(doc)) {
request.reply(Object.assign({}, mock.HELLO));
} else if (doc.endSessions) {
request.reply({ ok: 1 });
}
});
// set `heartbeatFrequencyMS` to 250ms to force a quick monitoring check, and wait 500ms to validate below
const topology = new Topology(mockServer.hostAddress(), { heartbeatFrequencyMS: 250 });
topology.connect(err => {
expect(err).to.not.exist;
setTimeout(() => {
expect(topology).property('description').property('servers').to.have.length(1);
const serverDescription = Array.from(topology.description.servers.values())[0];
expect(serverDescription).property('roundTripTime').to.be.greaterThan(0);
topology.close(done);
}, 500);
});
});
// TODO(NODE-3600): Unskip flaky test
it.skip('should recover on error during initial connect', function (done) {
// This test should take ~1s because initial server selection fails and an immediate check
// is requested. If the behavior of the immediate check is broken, the test will take ~10s
// to complete. We want to ensure validation of the immediate check behavior, and therefore
// hardcode the test timeout to 2s.
this.timeout(2000);
let acceptConnections = false;
mockServer.setMessageHandler(request => {
if (!acceptConnections) {
request.connection.destroy();
return;
}
const doc = request.document;
if (isHello(doc)) {
request.reply(Object.assign({}, mock.HELLO));
} else if (doc.endSessions) {
request.reply({ ok: 1 });
}
});
setTimeout(() => {
acceptConnections = true;
}, 250);
const topology = new Topology(mockServer.hostAddress(), {});
topology.connect(err => {
expect(err).to.not.exist;
expect(topology).property('description').property('servers').to.have.length(1);
const serverDescription = Array.from(topology.description.servers.values())[0];
expect(serverDescription).property('roundTripTime').to.be.greaterThan(0);
topology.close(done);
});
});
describe('Monitor', function () {
it('should connect and issue an initial server check', function (done) {
mockServer.setMessageHandler(request => {
const doc = request.document;
if (isHello(doc)) {
request.reply(Object.assign({}, mock.HELLO));
}
});
const server = new MockServer(mockServer.address());
const monitor = new Monitor(server, {});
this.defer(() => monitor.close());
monitor.on('serverHeartbeatFailed', () => done(new Error('unexpected heartbeat failure')));
monitor.on('serverHeartbeatSucceeded', () => done());
monitor.connect();
});
it('should ignore attempts to connect when not already closed', function (done) {
mockServer.setMessageHandler(request => {
const doc = request.document;
if (isHello(doc)) {
request.reply(Object.assign({}, mock.HELLO));
}
});
const server = new MockServer(mockServer.address());
const monitor = new Monitor(server, {});
this.defer(() => monitor.close());
monitor.on('serverHeartbeatFailed', () => done(new Error('unexpected heartbeat failure')));
monitor.on('serverHeartbeatSucceeded', () => done());
monitor.connect();
monitor.connect();
});
it('should not initiate another check if one is in progress', function (done) {
mockServer.setMessageHandler(request => {
const doc = request.document;
if (isHello(doc)) {
setTimeout(() => request.reply(Object.assign({}, mock.HELLO)), 250);
}
});
const server = new MockServer(mockServer.address());
const monitor = new Monitor(server, {});
const startedEvents = [];
monitor.on('serverHeartbeatStarted', event => startedEvents.push(event));
monitor.on('close', () => {
expect(startedEvents).to.have.length(2);
done();
});
monitor.connect();
monitor.once('serverHeartbeatSucceeded', () => {
monitor.requestCheck();
monitor.requestCheck();
monitor.requestCheck();
monitor.requestCheck();
monitor.requestCheck();
const minHeartbeatFrequencyMS = 500;
setTimeout(() => {
// wait for minHeartbeatFrequencyMS, then request a check and verify another check occurred
monitor.once('serverHeartbeatSucceeded', () => {
monitor.close();
});
monitor.requestCheck();
}, minHeartbeatFrequencyMS);
});
});
it('should not close the monitor on a failed heartbeat', function (done) {
let helloCount = 0;
mockServer.setMessageHandler(request => {
const doc = request.document;
if (isHello(doc)) {
helloCount++;
if (helloCount === 2) {
request.reply({ ok: 0, errmsg: 'forced from mock server' });
return;
}
if (helloCount === 3) {
request.connection.destroy();
return;
}
request.reply(mock.HELLO);
}
});
const server = new MockServer(mockServer.address());
server.description = new ServerDescription(server.description.hostAddress);
const monitor = new Monitor(server, {
heartbeatFrequencyMS: 250,
minHeartbeatFrequencyMS: 50
});
const events = [];
monitor.on('serverHeartbeatFailed', event => events.push(event));
let successCount = 0;
monitor.on('serverHeartbeatSucceeded', () => {
if (successCount++ === 2) {
monitor.close();
}
});
monitor.on('close', () => {
expect(events).to.have.length(2);
done();
});
monitor.connect();
});
it('should upgrade to hello from legacy hello when initial handshake contains helloOk', function (done) {
const docs = [];
mockServer.setMessageHandler(request => {
const doc = request.document;
docs.push(doc);
if (docs.length === 2) {
expect(docs[0]).to.have.property(LEGACY_HELLO_COMMAND, true);
expect(docs[0]).to.have.property('helloOk', true);
expect(docs[1]).to.have.property('hello', true);
done();
} else if (isHello(doc)) {
setTimeout(() => request.reply(Object.assign({ helloOk: true }, mock.HELLO)), 250);
}
});
const server = new MockServer(mockServer.address());
const monitor = new Monitor(server, {});
this.defer(() => monitor.close());
monitor.connect();
monitor.once('serverHeartbeatSucceeded', () => {
const minHeartbeatFrequencyMS = 500;
setTimeout(() => {
// wait for minHeartbeatFrequencyMS, then request a check and verify another check occurred
monitor.once('serverHeartbeatSucceeded', () => {
monitor.close();
});
monitor.requestCheck();
}, minHeartbeatFrequencyMS);
});
});
});
});
| 1 | 21,670 | is this one all platforms? | mongodb-node-mongodb-native | js |
@@ -72,7 +72,7 @@ func TestBytes(t *testing.T) {
t.Run("not found", func(t *testing.T) {
jsonhttptest.Request(t, client, http.MethodGet, resource+"/abcd", http.StatusNotFound,
jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
- Message: "not found",
+ Message: "Not Found",
Code: http.StatusNotFound,
}),
) | 1 | // Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package api_test
import (
"bytes"
"io/ioutil"
"net/http"
"testing"
"github.com/ethersphere/bee/pkg/api"
"github.com/ethersphere/bee/pkg/jsonhttp"
"github.com/ethersphere/bee/pkg/jsonhttp/jsonhttptest"
"github.com/ethersphere/bee/pkg/logging"
"github.com/ethersphere/bee/pkg/storage/mock"
"github.com/ethersphere/bee/pkg/swarm"
"github.com/ethersphere/bee/pkg/tags"
mockbytes "gitlab.com/nolash/go-mockbytes"
)
// TestBytes tests that the data upload api responds as expected when uploading,
// downloading and requesting a resource that cannot be found.
func TestBytes(t *testing.T) {
var (
resource = "/bytes"
targets = "0x222"
expHash = "29a5fb121ce96194ba8b7b823a1f9c6af87e1791f824940a53b5a7efe3f790d9"
mockStorer = mock.NewStorer()
client = newTestServer(t, testServerOptions{
Storer: mockStorer,
Tags: tags.NewTags(),
Logger: logging.New(ioutil.Discard, 5),
})
)
g := mockbytes.New(0, mockbytes.MockTypeStandard).WithModulus(255)
content, err := g.SequentialBytes(swarm.ChunkSize * 2)
if err != nil {
t.Fatal(err)
}
t.Run("upload", func(t *testing.T) {
jsonhttptest.Request(t, client, http.MethodPost, resource, http.StatusOK,
jsonhttptest.WithRequestBody(bytes.NewReader(content)),
jsonhttptest.WithExpectedJSONResponse(api.BytesPostResponse{
Reference: swarm.MustParseHexAddress(expHash),
}),
)
})
t.Run("download", func(t *testing.T) {
resp := request(t, client, http.MethodGet, resource+"/"+expHash, nil, http.StatusOK)
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, content) {
t.Fatalf("data mismatch. got %s, want %s", string(data), string(content))
}
})
t.Run("download-with-targets", func(t *testing.T) {
resp := request(t, client, http.MethodGet, resource+"/"+expHash+"?targets="+targets, nil, http.StatusOK)
if resp.Header.Get(api.TargetsRecoveryHeader) != targets {
t.Fatalf("targets mismatch. got %s, want %s", resp.Header.Get(api.TargetsRecoveryHeader), targets)
}
})
t.Run("not found", func(t *testing.T) {
jsonhttptest.Request(t, client, http.MethodGet, resource+"/abcd", http.StatusNotFound,
jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: "not found",
Code: http.StatusNotFound,
}),
)
})
}
| 1 | 11,951 | why capitals grr? | ethersphere-bee | go |
@@ -0,0 +1,17 @@
+package nameserver
+
+import (
+ . "github.com/zettio/weave/common"
+)
+
+func checkFatal(e error) {
+ if e != nil {
+ Error.Fatal(e)
+ }
+}
+
+func checkWarn(e error) {
+ if e != nil {
+ Warning.Println(e)
+ }
+} | 1 | 1 | 7,769 | Surely all the above should go into `common`. | weaveworks-weave | go |
|
@@ -249,7 +249,6 @@ def test_failing_unwatch(qtbot, caplog, monkeypatch):
assert caplog.records[-1].msg == message
-
@pytest.mark.parametrize('text, caret_position, result', [
('', 0, (1, 1)),
('a', 0, (1, 1)), | 1 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for qutebrowser.misc.editor."""
import time
import os
import os.path
import logging
from PyQt5.QtCore import QProcess
import pytest
from qutebrowser.misc import editor as editormod
from qutebrowser.utils import usertypes
@pytest.fixture(autouse=True)
def patch_things(config_stub, monkeypatch, stubs):
monkeypatch.setattr(editormod.guiprocess, 'QProcess',
stubs.fake_qprocess())
@pytest.fixture
def editor(caplog, qtbot):
ed = editormod.ExternalEditor()
yield ed
with caplog.at_level(logging.ERROR):
ed._remove_file = True
ed._cleanup()
class TestArg:
"""Test argument handling.
Attributes:
editor: The ExternalEditor instance to test.
"""
def test_placeholder(self, config_stub, editor):
"""Test starting editor with placeholder argument."""
config_stub.val.editor.command = ['bin', 'foo', '{}', 'bar']
editor.edit("")
editor._proc._proc.start.assert_called_with(
"bin", ["foo", editor._filename, "bar"])
def test_placeholder_inline(self, config_stub, editor):
"""Test starting editor with placeholder arg inside of another arg."""
config_stub.val.editor.command = ['bin', 'foo{}', 'bar']
editor.edit("")
editor._proc._proc.start.assert_called_with(
"bin", ["foo" + editor._filename, "bar"])
class TestFileHandling:
"""Test creation/deletion of tempfile."""
def test_ok(self, editor):
"""Test file handling when closing with an exit status == 0."""
editor.edit("")
filename = editor._filename
assert os.path.exists(filename)
assert os.path.basename(filename).startswith('qutebrowser-editor-')
editor._proc.finished.emit(0, QProcess.NormalExit)
assert not os.path.exists(filename)
def test_existing_file(self, editor, tmpdir):
"""Test editing an existing file."""
path = tmpdir / 'foo.txt'
path.ensure()
editor.edit_file(str(path))
editor._proc.finished.emit(0, QProcess.NormalExit)
assert path.exists()
def test_error(self, editor):
"""Test file handling when closing with an exit status != 0."""
editor.edit("")
filename = editor._filename
assert os.path.exists(filename)
editor._proc._proc.exitStatus = lambda: QProcess.CrashExit
editor._proc.finished.emit(1, QProcess.NormalExit)
assert os.path.exists(filename)
os.remove(filename)
def test_crash(self, editor):
"""Test file handling when closing with a crash."""
editor.edit("")
filename = editor._filename
assert os.path.exists(filename)
editor._proc._proc.exitStatus = lambda: QProcess.CrashExit
editor._proc.error.emit(QProcess.Crashed)
editor._proc.finished.emit(0, QProcess.CrashExit)
assert os.path.exists(filename)
os.remove(filename)
def test_unreadable(self, message_mock, editor, caplog, qtbot):
"""Test file handling when closing with an unreadable file."""
editor.edit("")
filename = editor._filename
assert os.path.exists(filename)
os.chmod(filename, 0o277)
if os.access(filename, os.R_OK):
# Docker container or similar
pytest.skip("File was still readable")
with caplog.at_level(logging.ERROR):
editor._proc.finished.emit(0, QProcess.NormalExit)
assert not os.path.exists(filename)
msg = message_mock.getmsg(usertypes.MessageLevel.error)
assert msg.text.startswith("Failed to read back edited file: ")
def test_unwritable(self, monkeypatch, message_mock, editor, tmpdir,
caplog):
"""Test file handling when the initial file is not writable."""
tmpdir.chmod(0)
if os.access(str(tmpdir), os.W_OK):
# Docker container or similar
pytest.skip("File was still writable")
monkeypatch.setattr(editormod.tempfile, 'tempdir', str(tmpdir))
with caplog.at_level(logging.ERROR):
editor.edit("")
msg = message_mock.getmsg(usertypes.MessageLevel.error)
assert msg.text.startswith("Failed to create initial file: ")
assert editor._proc is None
def test_double_edit(self, editor):
editor.edit("")
with pytest.raises(ValueError):
editor.edit("")
@pytest.mark.parametrize('initial_text, edited_text', [
('', 'Hello'),
('Hello', 'World'),
('Hällö Wörld', 'Überprüfung'),
('\u2603', '\u2601') # Unicode snowman -> cloud
])
def test_modify(qtbot, editor, initial_text, edited_text):
"""Test if inputs get modified correctly."""
editor.edit(initial_text)
with open(editor._filename, 'r', encoding='utf-8') as f:
assert f.read() == initial_text
with open(editor._filename, 'w', encoding='utf-8') as f:
f.write(edited_text)
with qtbot.wait_signal(editor.file_updated) as blocker:
editor._proc.finished.emit(0, QProcess.NormalExit)
assert blocker.args == [edited_text]
def _update_file(filename, contents):
"""Update the given file and make sure its mtime changed.
This might write the file multiple times, but different systems have
different mtime's, so we can't be sure how long to wait otherwise.
"""
old_mtime = new_mtime = os.stat(filename).st_mtime
while old_mtime == new_mtime:
time.sleep(0.1)
with open(filename, 'w', encoding='utf-8') as f:
f.write(contents)
new_mtime = os.stat(filename).st_mtime
def test_modify_watch(qtbot):
"""Test that saving triggers file_updated when watch=True."""
editor = editormod.ExternalEditor(watch=True)
editor.edit('foo')
with qtbot.wait_signal(editor.file_updated, timeout=3000) as blocker:
_update_file(editor._filename, 'bar')
assert blocker.args == ['bar']
with qtbot.wait_signal(editor.file_updated) as blocker:
_update_file(editor._filename, 'baz')
assert blocker.args == ['baz']
with qtbot.assert_not_emitted(editor.file_updated):
editor._proc.finished.emit(0, QProcess.NormalExit)
def test_failing_watch(qtbot, caplog, monkeypatch):
"""When watching failed, an error should be logged.
Also, updating should still work when closing the process.
"""
editor = editormod.ExternalEditor(watch=True)
monkeypatch.setattr(editor._watcher, 'addPath', lambda _path: False)
with caplog.at_level(logging.ERROR):
editor.edit('foo')
with qtbot.assert_not_emitted(editor.file_updated):
_update_file(editor._filename, 'bar')
with qtbot.wait_signal(editor.file_updated) as blocker:
editor._proc.finished.emit(0, QProcess.NormalExit)
assert blocker.args == ['bar']
message = 'Failed to watch path: {}'.format(editor._filename)
assert caplog.records[0].msg == message
def test_failing_unwatch(qtbot, caplog, monkeypatch):
"""When unwatching failed, an error should be logged."""
editor = editormod.ExternalEditor(watch=True)
monkeypatch.setattr(editor._watcher, 'addPath', lambda _path: True)
monkeypatch.setattr(editor._watcher, 'files', lambda: [editor._filename])
monkeypatch.setattr(editor._watcher, 'removePaths', lambda paths: paths)
editor.edit('foo')
with caplog.at_level(logging.ERROR):
editor._proc.finished.emit(0, QProcess.NormalExit)
message = 'Failed to unwatch paths: [{!r}]'.format(editor._filename)
assert caplog.records[-1].msg == message
@pytest.mark.parametrize('text, caret_position, result', [
('', 0, (1, 1)),
('a', 0, (1, 1)),
('a\nb', 1, (1, 2)),
('a\nb', 2, (2, 1)),
('a\nb', 3, (2, 2)),
('a\nbb\nccc', 4, (2, 3)),
('a\nbb\nccc', 5, (3, 1)),
('a\nbb\nccc', 8, (3, 4)),
('', None, (1, 1)),
])
def test_calculation(editor, text, caret_position, result):
"""Test calculation for line and column given text and caret_position."""
assert editor._calc_line_and_column(text, caret_position) == result
| 1 | 20,689 | This is an unrelated change, but was failing CI... probably introduced in master. | qutebrowser-qutebrowser | py |
@@ -30,7 +30,10 @@ double getAlignmentTransform(const ROMol &prbMol, const ROMol &refMol,
if (atomMap == 0) {
// we have to figure out the mapping between the two molecule
MatchVectType match;
- if (SubstructMatch(refMol, prbMol, match)) {
+ const bool recursionPossible = true;
+ const bool useChirality = false;
+ const bool useQueryQueryMatches = true;
+ if (SubstructMatch(refMol, prbMol, match, recursionPossible, useChirality, useQueryQueryMatches)) {
MatchVectType::const_iterator mi;
for (mi = match.begin(); mi != match.end(); mi++) {
prbPoints.push_back(&prbCnf.getAtomPos(mi->first)); | 1 | // $Id$
//
// Copyright (C) 2001-2008 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "AlignMolecules.h"
#include <Geometry/Transform3D.h>
#include <Numerics/Vector.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Conformer.h>
#include <GraphMol/ROMol.h>
#include <Numerics/Alignment/AlignPoints.h>
#include <GraphMol/MolTransforms/MolTransforms.h>
namespace RDKit {
namespace MolAlign {
double getAlignmentTransform(const ROMol &prbMol, const ROMol &refMol,
RDGeom::Transform3D &trans, int prbCid, int refCid,
const MatchVectType *atomMap,
const RDNumeric::DoubleVector *weights,
bool reflect, unsigned int maxIterations) {
RDGeom::Point3DConstPtrVect refPoints, prbPoints;
const Conformer &prbCnf = prbMol.getConformer(prbCid);
const Conformer &refCnf = refMol.getConformer(refCid);
if (atomMap == 0) {
// we have to figure out the mapping between the two molecule
MatchVectType match;
if (SubstructMatch(refMol, prbMol, match)) {
MatchVectType::const_iterator mi;
for (mi = match.begin(); mi != match.end(); mi++) {
prbPoints.push_back(&prbCnf.getAtomPos(mi->first));
refPoints.push_back(&refCnf.getAtomPos(mi->second));
}
} else {
throw MolAlignException(
"No sub-structure match found between the probe and query mol");
}
} else {
MatchVectType::const_iterator mi;
for (mi = atomMap->begin(); mi != atomMap->end(); mi++) {
prbPoints.push_back(&prbCnf.getAtomPos(mi->first));
refPoints.push_back(&refCnf.getAtomPos(mi->second));
}
}
double ssr = RDNumeric::Alignments::AlignPoints(
refPoints, prbPoints, trans, weights, reflect, maxIterations);
ssr /= (prbPoints.size());
return sqrt(ssr);
}
double alignMol(ROMol &prbMol, const ROMol &refMol, int prbCid, int refCid,
const MatchVectType *atomMap,
const RDNumeric::DoubleVector *weights, bool reflect,
unsigned int maxIterations) {
RDGeom::Transform3D trans;
double res = getAlignmentTransform(prbMol, refMol, trans, prbCid, refCid,
atomMap, weights, reflect, maxIterations);
// now transform the relevant conformation on prbMol
Conformer &conf = prbMol.getConformer(prbCid);
MolTransforms::transformConformer(conf, trans);
return res;
}
void _fillAtomPositions(RDGeom::Point3DConstPtrVect &pts, const Conformer &conf,
const std::vector<unsigned int> *atomIds = 0) {
unsigned int na = conf.getNumAtoms();
pts.clear();
if (atomIds == 0) {
unsigned int ai;
pts.reserve(na);
for (ai = 0; ai < na; ++ai) {
pts.push_back(&conf.getAtomPos(ai));
}
} else {
pts.reserve(atomIds->size());
std::vector<unsigned int>::const_iterator cai;
for (cai = atomIds->begin(); cai != atomIds->end(); cai++) {
pts.push_back(&conf.getAtomPos(*cai));
}
}
}
void alignMolConformers(ROMol &mol, const std::vector<unsigned int> *atomIds,
const std::vector<unsigned int> *confIds,
const RDNumeric::DoubleVector *weights, bool reflect,
unsigned int maxIters, std::vector<double> *RMSlist) {
if (mol.getNumConformers() == 0) {
// nothing to be done ;
return;
}
RDGeom::Point3DConstPtrVect refPoints, prbPoints;
int cid = -1;
if ((confIds != 0) && (confIds->size() > 0)) {
cid = confIds->front();
}
const Conformer &refCnf = mol.getConformer(cid);
_fillAtomPositions(refPoints, refCnf, atomIds);
// now loop throught the remaininf conformations and transform them
RDGeom::Transform3D trans;
double ssd;
if (confIds == 0) {
unsigned int i = 0;
ROMol::ConformerIterator cnfi;
// Conformer *conf;
for (cnfi = mol.beginConformers(); cnfi != mol.endConformers(); cnfi++) {
// conf = (*cnfi);
i += 1;
if (i == 1) {
continue;
}
_fillAtomPositions(prbPoints, *(*cnfi), atomIds);
ssd = RDNumeric::Alignments::AlignPoints(refPoints, prbPoints, trans,
weights, reflect, maxIters);
if (RMSlist) {
ssd /= (prbPoints.size());
RMSlist->push_back(sqrt(ssd));
}
MolTransforms::transformConformer(*(*cnfi), trans);
}
} else {
std::vector<unsigned int>::const_iterator cai;
unsigned int i = 0;
for (cai = confIds->begin(); cai != confIds->end(); cai++) {
i += 1;
if (i == 1) {
continue;
}
Conformer &conf = mol.getConformer(*cai);
_fillAtomPositions(prbPoints, conf, atomIds);
ssd = RDNumeric::Alignments::AlignPoints(refPoints, prbPoints, trans,
weights, reflect, maxIters);
if (RMSlist) {
ssd /= (prbPoints.size());
RMSlist->push_back(sqrt(ssd));
}
MolTransforms::transformConformer(conf, trans);
}
}
}
}
}
| 1 | 14,757 | This piece isn't backwards compatible, but it's enough of an edge case that I think it's unlikely to be a problem. | rdkit-rdkit | cpp |
@@ -81,8 +81,9 @@ import (
var endPoint = "pubsub.googleapis.com:443"
var sendBatcherOpts = &batcher.Options{
- MaxBatchSize: 1000, // The PubSub service limits the number of messages in a single Publish RPC
- MaxHandlers: 2,
+ MaxBatchSize: 1000, // The PubSub service limits the number of messages in a single Publish RPC
+ MaxHandlers: 2,
+ MaxBatchByteSize: 10 * 1000 * 1000, // The PubSub service limits the size of request body in a single Publish RPC
}
var defaultRecvBatcherOpts = &batcher.Options{ | 1 | // Copyright 2018 The Go Cloud Development Kit 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package gcppubsub provides a pubsub implementation that uses GCP
// PubSub. Use OpenTopic to construct a *pubsub.Topic, and/or OpenSubscription
// to construct a *pubsub.Subscription.
//
// URLs
//
// For pubsub.OpenTopic and pubsub.OpenSubscription, gcppubsub registers
// for the scheme "gcppubsub".
// The default URL opener will creating a connection using use default
// credentials from the environment, as described in
// https://cloud.google.com/docs/authentication/production.
// To customize the URL opener, or for more details on the URL format,
// see URLOpener.
// See https://gocloud.dev/concepts/urls/ for background information.
//
// GCP Pub/Sub emulator is supported as per https://cloud.google.com/pubsub/docs/emulator
// So, when environment variable 'PUBSUB_EMULATOR_HOST' is set
// driver connects to the specified emulator host by default.
//
// Message Delivery Semantics
//
// GCP Pub/Sub supports at-least-once semantics; applications must
// call Message.Ack after processing a message, or it will be redelivered.
// See https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
// for more background.
//
// As
//
// gcppubsub exposes the following types for As:
// - Topic: *raw.PublisherClient
// - Subscription: *raw.SubscriberClient
// - Message.BeforeSend: *pb.PubsubMessage
// - Message.AfterSend: *string for the pb.PublishResponse.MessageIds entry corresponding to the message.
// - Message: *pb.PubsubMessage
// - Error: *google.golang.org/grpc/status.Status
package gcppubsub // import "gocloud.dev/pubsub/gcppubsub"
import (
"context"
"fmt"
"net/url"
"os"
"path"
"regexp"
"strconv"
"strings"
"sync"
"time"
raw "cloud.google.com/go/pubsub/apiv1"
"github.com/google/wire"
"gocloud.dev/gcerrors"
"gocloud.dev/gcp"
"gocloud.dev/internal/gcerr"
"gocloud.dev/internal/useragent"
"gocloud.dev/pubsub"
"gocloud.dev/pubsub/batcher"
"gocloud.dev/pubsub/driver"
"google.golang.org/api/option"
pb "google.golang.org/genproto/googleapis/pubsub/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/oauth"
"google.golang.org/grpc/status"
)
var endPoint = "pubsub.googleapis.com:443"
var sendBatcherOpts = &batcher.Options{
MaxBatchSize: 1000, // The PubSub service limits the number of messages in a single Publish RPC
MaxHandlers: 2,
}
var defaultRecvBatcherOpts = &batcher.Options{
// GCP Pub/Sub returns at most 1000 messages per RPC.
MaxBatchSize: 1000,
MaxHandlers: 10,
}
var ackBatcherOpts = &batcher.Options{
// The PubSub service limits the size of Acknowledge/ModifyAckDeadline RPCs.
// (E.g., "Request payload size exceeds the limit: 524288 bytes.").
MaxBatchSize: 1000,
MaxHandlers: 2,
}
func init() {
o := new(lazyCredsOpener)
pubsub.DefaultURLMux().RegisterTopic(Scheme, o)
pubsub.DefaultURLMux().RegisterSubscription(Scheme, o)
}
// Set holds Wire providers for this package.
var Set = wire.NewSet(
Dial,
PublisherClient,
SubscriberClient,
wire.Struct(new(SubscriptionOptions)),
wire.Struct(new(TopicOptions)),
wire.Struct(new(URLOpener), "Conn", "TopicOptions", "SubscriptionOptions"),
)
// lazyCredsOpener obtains Application Default Credentials on the first call
// to OpenTopicURL/OpenSubscriptionURL.
type lazyCredsOpener struct {
init sync.Once
opener *URLOpener
err error
}
func (o *lazyCredsOpener) defaultConn(ctx context.Context) (*URLOpener, error) {
o.init.Do(func() {
var conn *grpc.ClientConn
var err error
if e := os.Getenv("PUBSUB_EMULATOR_HOST"); e != "" {
// Connect to the GCP pubsub emulator by overriding the default endpoint
// if the 'PUBSUB_EMULATOR_HOST' environment variable is set.
// Check https://cloud.google.com/pubsub/docs/emulator for more info.
endPoint = e
conn, err = dialEmulator(ctx, e)
if err != nil {
o.err = err
return
}
} else {
creds, err := gcp.DefaultCredentials(ctx)
if err != nil {
o.err = err
return
}
conn, _, err = Dial(ctx, creds.TokenSource)
if err != nil {
o.err = err
return
}
}
o.opener = &URLOpener{Conn: conn}
})
return o.opener, o.err
}
func (o *lazyCredsOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
opener, err := o.defaultConn(ctx)
if err != nil {
return nil, fmt.Errorf("open topic %v: failed to open default connection: %v", u, err)
}
return opener.OpenTopicURL(ctx, u)
}
func (o *lazyCredsOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
opener, err := o.defaultConn(ctx)
if err != nil {
return nil, fmt.Errorf("open subscription %v: failed to open default connection: %v", u, err)
}
return opener.OpenSubscriptionURL(ctx, u)
}
// Scheme is the URL scheme gcppubsub registers its URLOpeners under on pubsub.DefaultMux.
const Scheme = "gcppubsub"
// URLOpener opens GCP Pub/Sub URLs like "gcppubsub://projects/myproject/topics/mytopic" for
// topics or "gcppubsub://projects/myproject/subscriptions/mysub" for subscriptions.
//
// The shortened forms "gcppubsub://myproject/mytopic" for topics or
// "gcppubsub://myproject/mysub" for subscriptions are also supported.
//
// The following query parameters are supported:
//
// - max_recv_batch_size: sets SubscriptionOptions.MaxBatchSize
//
// Currently their use is limited to subscribers.
type URLOpener struct {
// Conn must be set to a non-nil ClientConn authenticated with
// Cloud Pub/Sub scope or equivalent.
Conn *grpc.ClientConn
// TopicOptions specifies the options to pass to OpenTopic.
TopicOptions TopicOptions
// SubscriptionOptions specifies the options to pass to OpenSubscription.
SubscriptionOptions SubscriptionOptions
}
// OpenTopicURL opens a pubsub.Topic based on u.
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
for param := range u.Query() {
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param)
}
pc, err := PublisherClient(ctx, o.Conn)
if err != nil {
return nil, err
}
topicPath := path.Join(u.Host, u.Path)
if topicPathRE.MatchString(topicPath) {
return OpenTopicByPath(pc, topicPath, &o.TopicOptions)
}
// Shortened form?
topicName := strings.TrimPrefix(u.Path, "/")
return OpenTopic(pc, gcp.ProjectID(u.Host), topicName, &o.TopicOptions), nil
}
// OpenSubscriptionURL opens a pubsub.Subscription based on u.
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
// Set subscription options to use defaults
opts := o.SubscriptionOptions
for param, value := range u.Query() {
switch param {
case "max_recv_batch_size":
maxBatchSize, err := queryParameterInt(value)
if err != nil {
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: %v", u, param, err)
}
if maxBatchSize <= 0 || maxBatchSize > 1000 {
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: must be between 1 and 1000", u, param)
}
opts.MaxBatchSize = maxBatchSize
default:
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param)
}
}
sc, err := SubscriberClient(ctx, o.Conn)
if err != nil {
return nil, err
}
subPath := path.Join(u.Host, u.Path)
if subscriptionPathRE.MatchString(subPath) {
return OpenSubscriptionByPath(sc, subPath, &opts)
}
// Shortened form?
subName := strings.TrimPrefix(u.Path, "/")
return OpenSubscription(sc, gcp.ProjectID(u.Host), subName, &opts), nil
}
type topic struct {
path string
client *raw.PublisherClient
}
// Dial opens a gRPC connection to the GCP Pub Sub API.
//
// The second return value is a function that can be called to clean up
// the connection opened by Dial.
func Dial(ctx context.Context, ts gcp.TokenSource) (*grpc.ClientConn, func(), error) {
conn, err := grpc.DialContext(ctx, endPoint,
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: ts}),
// The default message size limit for gRPC is 4MB, while GCP
// PubSub supports messages up to 10MB. Tell gRPC to support up
// to 10MB.
// https://github.com/googleapis/google-cloud-node/issues/1991
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*10)),
useragent.GRPCDialOption("pubsub"),
)
if err != nil {
return nil, nil, err
}
return conn, func() { conn.Close() }, nil
}
// dialEmulator opens a gRPC connection to the GCP Pub Sub API.
func dialEmulator(ctx context.Context, e string) (*grpc.ClientConn, error) {
conn, err := grpc.DialContext(ctx, e, grpc.WithInsecure(), useragent.GRPCDialOption("pubsub"))
if err != nil {
return nil, err
}
return conn, nil
}
// PublisherClient returns a *raw.PublisherClient that can be used in OpenTopic.
func PublisherClient(ctx context.Context, conn *grpc.ClientConn) (*raw.PublisherClient, error) {
return raw.NewPublisherClient(ctx, option.WithGRPCConn(conn))
}
// SubscriberClient returns a *raw.SubscriberClient that can be used in OpenSubscription.
func SubscriberClient(ctx context.Context, conn *grpc.ClientConn) (*raw.SubscriberClient, error) {
return raw.NewSubscriberClient(ctx, option.WithGRPCConn(conn))
}
// TopicOptions will contain configuration for topics.
type TopicOptions struct{}
// OpenTopic returns a *pubsub.Topic backed by an existing GCP PubSub topic
// in the given projectID. topicName is the last part of the full topic
// path, e.g., "foo" from "projects/<projectID>/topic/foo".
// See the package documentation for an example.
func OpenTopic(client *raw.PublisherClient, projectID gcp.ProjectID, topicName string, opts *TopicOptions) *pubsub.Topic {
topicPath := fmt.Sprintf("projects/%s/topics/%s", projectID, topicName)
return pubsub.NewTopic(openTopic(client, topicPath), sendBatcherOpts)
}
var topicPathRE = regexp.MustCompile("^projects/.+/topics/.+$")
// OpenTopicByPath returns a *pubsub.Topic backed by an existing GCP PubSub
// topic. topicPath must be of the form "projects/<projectID>/topic/<topic>".
// See the package documentation for an example.
func OpenTopicByPath(client *raw.PublisherClient, topicPath string, opts *TopicOptions) (*pubsub.Topic, error) {
if !topicPathRE.MatchString(topicPath) {
return nil, fmt.Errorf("invalid topicPath %q; must match %v", topicPath, topicPathRE)
}
return pubsub.NewTopic(openTopic(client, topicPath), sendBatcherOpts), nil
}
// openTopic returns the driver for OpenTopic. This function exists so the test
// harness can get the driver interface implementation if it needs to.
func openTopic(client *raw.PublisherClient, topicPath string) driver.Topic {
return &topic{topicPath, client}
}
// SendBatch implements driver.Topic.SendBatch.
func (t *topic) SendBatch(ctx context.Context, dms []*driver.Message) error {
var ms []*pb.PubsubMessage
for _, dm := range dms {
psm := &pb.PubsubMessage{Data: dm.Body, Attributes: dm.Metadata}
if dm.BeforeSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(**pb.PubsubMessage); ok {
*p = psm
return true
}
return false
}
if err := dm.BeforeSend(asFunc); err != nil {
return err
}
}
ms = append(ms, psm)
}
req := &pb.PublishRequest{Topic: t.path, Messages: ms}
pr, err := t.client.Publish(ctx, req)
if err != nil {
return err
}
if len(pr.MessageIds) == len(dms) {
for n, dm := range dms {
if dm.AfterSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(*string); ok {
*p = pr.MessageIds[n]
return true
}
return false
}
if err := dm.AfterSend(asFunc); err != nil {
return err
}
}
}
}
return nil
}
// IsRetryable implements driver.Topic.IsRetryable.
func (t *topic) IsRetryable(error) bool {
// The client handles retries.
return false
}
// As implements driver.Topic.As.
func (t *topic) As(i interface{}) bool {
c, ok := i.(**raw.PublisherClient)
if !ok {
return false
}
*c = t.client
return true
}
// ErrorAs implements driver.Topic.ErrorAs
func (*topic) ErrorAs(err error, i interface{}) bool {
return errorAs(err, i)
}
func errorAs(err error, i interface{}) bool {
s, ok := status.FromError(err)
if !ok {
return false
}
p, ok := i.(**status.Status)
if !ok {
return false
}
*p = s
return true
}
func (*topic) ErrorCode(err error) gcerrors.ErrorCode {
return gcerr.GRPCCode(err)
}
// Close implements driver.Topic.Close.
func (*topic) Close() error { return nil }
type subscription struct {
client *raw.SubscriberClient
path string
options *SubscriptionOptions
}
// SubscriptionOptions will contain configuration for subscriptions.
type SubscriptionOptions struct {
// MaxBatchSize caps the maximum batch size used when retrieving messages. It defaults to 1000.
MaxBatchSize int
}
// OpenSubscription returns a *pubsub.Subscription backed by an existing GCP
// PubSub subscription subscriptionName in the given projectID. See the package
// documentation for an example.
func OpenSubscription(client *raw.SubscriberClient, projectID gcp.ProjectID, subscriptionName string, opts *SubscriptionOptions) *pubsub.Subscription {
path := fmt.Sprintf("projects/%s/subscriptions/%s", projectID, subscriptionName)
dsub := openSubscription(client, path, opts)
recvOpts := *defaultRecvBatcherOpts
recvOpts.MaxBatchSize = dsub.options.MaxBatchSize
return pubsub.NewSubscription(dsub, &recvOpts, ackBatcherOpts)
}
var subscriptionPathRE = regexp.MustCompile("^projects/.+/subscriptions/.+$")
// OpenSubscriptionByPath returns a *pubsub.Subscription backed by an existing
// GCP PubSub subscription. subscriptionPath must be of the form
// "projects/<projectID>/subscriptions/<subscription>".
// See the package documentation for an example.
func OpenSubscriptionByPath(client *raw.SubscriberClient, subscriptionPath string, opts *SubscriptionOptions) (*pubsub.Subscription, error) {
if !subscriptionPathRE.MatchString(subscriptionPath) {
return nil, fmt.Errorf("invalid subscriptionPath %q; must match %v", subscriptionPath, subscriptionPathRE)
}
dsub := openSubscription(client, subscriptionPath, opts)
recvOpts := *defaultRecvBatcherOpts
recvOpts.MaxBatchSize = dsub.options.MaxBatchSize
return pubsub.NewSubscription(dsub, &recvOpts, ackBatcherOpts), nil
}
// openSubscription returns a driver.Subscription.
func openSubscription(client *raw.SubscriberClient, subscriptionPath string, opts *SubscriptionOptions) *subscription {
if opts == nil {
opts = &SubscriptionOptions{}
}
if opts.MaxBatchSize == 0 {
opts.MaxBatchSize = defaultRecvBatcherOpts.MaxBatchSize
}
return &subscription{client, subscriptionPath, opts}
}
// ReceiveBatch implements driver.Subscription.ReceiveBatch.
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
// Whether to ask Pull to return immediately, or wait for some messages to
// arrive. If we're making multiple RPCs, we don't want any of them to wait;
// we might have gotten messages from one of the other RPCs.
// maxMessages will only be high enough to set this to true in high-throughput
// situations, so the likelihood of getting 0 messages is small anyway.
returnImmediately := maxMessages == s.options.MaxBatchSize
req := &pb.PullRequest{
Subscription: s.path,
ReturnImmediately: returnImmediately,
MaxMessages: int32(maxMessages),
}
resp, err := s.client.Pull(ctx, req)
if err != nil {
return nil, err
}
if len(resp.ReceivedMessages) == 0 {
// If we did happen to get 0 messages, and we didn't ask the server to wait
// for messages, sleep a bit to avoid spinning.
if returnImmediately {
time.Sleep(100 * time.Millisecond)
}
return nil, nil
}
ms := make([]*driver.Message, 0, len(resp.ReceivedMessages))
for _, rm := range resp.ReceivedMessages {
rmm := rm.Message
m := &driver.Message{
LoggableID: rmm.MessageId,
Body: rmm.Data,
Metadata: rmm.Attributes,
AckID: rm.AckId,
AsFunc: messageAsFunc(rmm),
}
ms = append(ms, m)
}
return ms, nil
}
func messageAsFunc(pm *pb.PubsubMessage) func(interface{}) bool {
return func(i interface{}) bool {
p, ok := i.(**pb.PubsubMessage)
if !ok {
return false
}
*p = pm
return true
}
}
// SendAcks implements driver.Subscription.SendAcks.
func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error {
ids2 := make([]string, 0, len(ids))
for _, id := range ids {
ids2 = append(ids2, id.(string))
}
return s.client.Acknowledge(ctx, &pb.AcknowledgeRequest{Subscription: s.path, AckIds: ids2})
}
// CanNack implements driver.CanNack.
func (s *subscription) CanNack() bool { return true }
// SendNacks implements driver.Subscription.SendNacks.
func (s *subscription) SendNacks(ctx context.Context, ids []driver.AckID) error {
ids2 := make([]string, 0, len(ids))
for _, id := range ids {
ids2 = append(ids2, id.(string))
}
return s.client.ModifyAckDeadline(ctx, &pb.ModifyAckDeadlineRequest{
Subscription: s.path,
AckIds: ids2,
AckDeadlineSeconds: 0,
})
}
// IsRetryable implements driver.Subscription.IsRetryable.
func (s *subscription) IsRetryable(error) bool {
// The client handles retries.
return false
}
// As implements driver.Subscription.As.
func (s *subscription) As(i interface{}) bool {
c, ok := i.(**raw.SubscriberClient)
if !ok {
return false
}
*c = s.client
return true
}
// ErrorAs implements driver.Subscription.ErrorAs
func (*subscription) ErrorAs(err error, i interface{}) bool {
return errorAs(err, i)
}
func (*subscription) ErrorCode(err error) gcerrors.ErrorCode {
return gcerr.GRPCCode(err)
}
// Close implements driver.Subscription.Close.
func (*subscription) Close() error { return nil }
func queryParameterInt(value []string) (int, error) {
if len(value) > 1 {
return 0, fmt.Errorf("expected only one parameter value, got: %v", len(value))
}
return strconv.Atoi(value[0])
}
| 1 | 20,571 | MB is presumably 1024 * 1024. | google-go-cloud | go |
@@ -22,6 +22,12 @@
import DashboardSplashMain from 'GoogleComponents/dashboard-splash/dashboard-splash-main';
import { Suspense as ReactSuspense, lazy as ReactLazy } from 'react';
+/**
+ * WordPress dependencies
+ */
+import { Component, Fragment, Suspense as WPSuspense, lazy as WPlazy } from '@wordpress/element';
+import { __ } from '@wordpress/i18n';
+
/**
* Internal dependencies
*/ | 1 | /**
* DashboardSplashApp component.
*
* Site Kit by Google, Copyright 2019 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import DashboardSplashMain from 'GoogleComponents/dashboard-splash/dashboard-splash-main';
import { Suspense as ReactSuspense, lazy as ReactLazy } from 'react';
/**
* Internal dependencies
*/
import DashboardSplashNotifications from './dashboard-splash-notifications';
import ProgressBar from 'GoogleComponents/progress-bar';
import { sendAnalyticsTrackingEvent } from 'GoogleUtil';
import 'GoogleComponents/publisher-wins';
import 'GoogleComponents/notifications';
const { Component, Fragment } = wp.element;
let { Suspense, lazy } = wp.element;
const { __ } = wp.i18n;
// Check for `Suspense` and `lazy` in `wp.element`; versions before 2.4.0 did
// not include either, so we need to fallback to the React versions. See:
// https://github.com/WordPress/gutenberg/blob/master/packages/element/CHANGELOG.md#240-2019-05-21
if ( ! Suspense ) {
Suspense = ReactSuspense;
}
if ( ! lazy ) {
lazy = ReactLazy;
}
const AUTHENTICATION = 1;
const SETUP = 2;
class DashboardSplashApp extends Component {
constructor( props ) {
super( props );
const { connectURL } = googlesitekit.admin;
const {
showModuleSetupWizard,
isAuthenticated,
isVerified,
hasSearchConsoleProperty,
} = googlesitekit.setup; /*eslint camelcase: 0*/
const {
canAuthenticate,
canSetup,
canViewDashboard,
canPublishPosts,
} = googlesitekit.permissions;
this.state = {
showAuthenticationSetupWizard: canSetup && ( ! isAuthenticated || ! isVerified || ! hasSearchConsoleProperty ),
showModuleSetupWizard,
canViewDashboard,
canPublishPosts,
buttonMode: 0,
connectURL,
};
if ( canAuthenticate && ! isAuthenticated ) {
this.state.buttonMode = AUTHENTICATION;
}
if ( canSetup && ( ! isAuthenticated || ! isVerified || ! hasSearchConsoleProperty ) ) {
this.state.buttonMode = SETUP;
}
this.openAuthenticationSetupWizard = this.openAuthenticationSetupWizard.bind( this );
this.gotoConnectURL = this.gotoConnectURL.bind( this );
}
openAuthenticationSetupWizard() {
sendAnalyticsTrackingEvent( 'plugin_setup', 'setup_sitekit' );
this.setState( {
showAuthenticationSetupWizard: true,
} );
}
gotoConnectURL() {
this.setState( {
showAuthenticationInstructionsWizard: false,
showAuthenticationSetupWizard: false,
} );
sendAnalyticsTrackingEvent( 'plugin_setup', 'connect_account' );
document.location = this.state.connectURL;
}
render() {
// Set webpackPublicPath on-the-fly.
if ( window.googlesitekit && window.googlesitekit.publicPath ) {
// eslint-disable-next-line no-undef
__webpack_public_path__ = window.googlesitekit.publicPath;
}
const { proxySetupURL } = googlesitekit.admin;
// If `proxySetupURL` is set it means the proxy is in use. We should never
// show the GCP splash screen when the proxy is being used, so skip this
// when `proxySetupURL` is set.
// See: https://github.com/google/site-kit-wp/issues/704.
if ( ! proxySetupURL && ! this.state.showAuthenticationSetupWizard && ! this.state.showModuleSetupWizard ) {
let introDescription, outroDescription, buttonLabel, onButtonClick;
switch ( this.state.buttonMode ) {
case AUTHENTICATION:
introDescription = __( 'You’re one step closer to connecting Google services to your WordPress site.', 'google-site-kit' );
outroDescription = __( 'Connecting your account only takes a few minutes. Faster than brewing a cup of coffee.', 'google-site-kit' );
buttonLabel = __( 'Connect your account', 'google-site-kit' );
onButtonClick = this.gotoConnectURL;
break;
case SETUP:
introDescription = __( 'You’re one step closer to connecting Google services to your WordPress site.', 'google-site-kit' );
outroDescription = __( 'Setup only takes a few minutes. Faster than brewing a cup of coffee.', 'google-site-kit' );
buttonLabel = __( 'Set Up Site Kit', 'google-site-kit' );
onButtonClick = this.openAuthenticationSetupWizard;
break;
default:
if ( this.state.canViewDashboard ) {
introDescription = __( 'Start gaining insights on how your site is performing in search by visiting the dashboard.', 'google-site-kit' );
} else if ( this.state.canPublishPosts ) {
introDescription = __( 'Start gaining insights on how your site is performing in search by editing one of your posts.', 'google-site-kit' );
} else {
introDescription = __( 'Start gaining insights on how your site is performing in search by viewing one of your published posts.', 'google-site-kit' );
}
}
return (
<Fragment>
<DashboardSplashNotifications />
<DashboardSplashMain introDescription={ introDescription } outroDescription={ outroDescription } buttonLabel={ buttonLabel } onButtonClick={ onButtonClick } />
</Fragment>
);
}
let Setup = null;
// `proxySetupURL` is only set if the proxy is in use.
if ( proxySetupURL ) {
Setup = lazy( () => import( /* webpackChunkName: "chunk-googlesitekit-setup-wizard-proxy" */'../setup/setup-proxy' ) );
} else if ( this.state.showAuthenticationSetupWizard ) {
Setup = lazy( () => import( /* webpackChunkName: "chunk-googlesitekit-setup-wizard" */'../setup' ) );
} else {
Setup = lazy( () => import( /* webpackChunkName: "chunk-googlesitekit-setup-wrapper" */'../setup/setup-wrapper' ) );
}
return (
<Suspense fallback={
<Fragment>
<div className="googlesitekit-setup">
<div className="mdc-layout-grid">
<div className="mdc-layout-grid__inner">
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-12
">
<div className="googlesitekit-setup__wrapper">
<div className="mdc-layout-grid">
<div className="mdc-layout-grid__inner">
<div className="
mdc-layout-grid__cell
mdc-layout-grid__cell--span-12
">
<ProgressBar />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</Fragment>
}>
<Setup />
</Suspense>
);
}
}
export default DashboardSplashApp;
| 1 | 24,743 | Didn't we extract this logic to a `react-features` helper? | google-site-kit-wp | js |
@@ -24,8 +24,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Filter.Internal
private bool _canWrite = true;
- private object _writeLock = new object();
-
public StreamSocketOutput(string connectionId, Stream outputStream, MemoryPool memory, IKestrelTrace logger)
{
_connectionId = connectionId; | 1 | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Infrastructure;
namespace Microsoft.AspNetCore.Server.Kestrel.Filter.Internal
{
public class StreamSocketOutput : ISocketOutput
{
private static readonly byte[] _endChunkBytes = Encoding.ASCII.GetBytes("\r\n");
private static readonly byte[] _nullBuffer = new byte[0];
private readonly string _connectionId;
private readonly Stream _outputStream;
private readonly MemoryPool _memory;
private readonly IKestrelTrace _logger;
private MemoryPoolBlock _producingBlock;
private bool _canWrite = true;
private object _writeLock = new object();
public StreamSocketOutput(string connectionId, Stream outputStream, MemoryPool memory, IKestrelTrace logger)
{
_connectionId = connectionId;
_outputStream = outputStream;
_memory = memory;
_logger = logger;
}
public void Write(ArraySegment<byte> buffer, bool chunk)
{
lock (_writeLock)
{
if (buffer.Count == 0 )
{
return;
}
try
{
if (!_canWrite)
{
return;
}
if (chunk && buffer.Array != null)
{
var beginChunkBytes = ChunkWriter.BeginChunkBytes(buffer.Count);
_outputStream.Write(beginChunkBytes.Array, beginChunkBytes.Offset, beginChunkBytes.Count);
}
_outputStream.Write(buffer.Array ?? _nullBuffer, buffer.Offset, buffer.Count);
if (chunk && buffer.Array != null)
{
_outputStream.Write(_endChunkBytes, 0, _endChunkBytes.Length);
}
}
catch (Exception ex)
{
_canWrite = false;
_logger.ConnectionError(_connectionId, ex);
}
}
}
public Task WriteAsync(ArraySegment<byte> buffer, bool chunk, CancellationToken cancellationToken)
{
#if NET451
Write(buffer, chunk);
return TaskUtilities.CompletedTask;
#else
if (chunk && buffer.Array != null)
{
return WriteAsyncChunked(buffer, cancellationToken);
}
return _outputStream.WriteAsync(buffer.Array ?? _nullBuffer, buffer.Offset, buffer.Count, cancellationToken);
#endif
}
private async Task WriteAsyncChunked(ArraySegment<byte> buffer, CancellationToken cancellationToken)
{
var beginChunkBytes = ChunkWriter.BeginChunkBytes(buffer.Count);
await _outputStream.WriteAsync(beginChunkBytes.Array, beginChunkBytes.Offset, beginChunkBytes.Count, cancellationToken);
await _outputStream.WriteAsync(buffer.Array, buffer.Offset, buffer.Count, cancellationToken);
await _outputStream.WriteAsync(_endChunkBytes, 0, _endChunkBytes.Length, cancellationToken);
}
public MemoryPoolIterator ProducingStart()
{
_producingBlock = _memory.Lease();
return new MemoryPoolIterator(_producingBlock);
}
public void ProducingComplete(MemoryPoolIterator end)
{
var block = _producingBlock;
while (block != end.Block)
{
// If we don't handle an exception from _outputStream.Write() here, we'll leak memory blocks.
if (_canWrite)
{
try
{
_outputStream.Write(block.Data.Array, block.Data.Offset, block.Data.Count);
}
catch (Exception ex)
{
_canWrite = false;
_logger.ConnectionError(_connectionId, ex);
}
}
var returnBlock = block;
block = block.Next;
returnBlock.Pool.Return(returnBlock);
}
if (_canWrite)
{
try
{
_outputStream.Write(end.Block.Array, end.Block.Data.Offset, end.Index - end.Block.Data.Offset);
}
catch (Exception ex)
{
_canWrite = false;
_logger.ConnectionError(_connectionId, ex);
}
}
end.Block.Pool.Return(end.Block);
}
}
}
| 1 | 9,815 | But But, overlapping async writes will get corrupted | aspnet-KestrelHttpServer | .cs |
@@ -9,6 +9,7 @@ import (
"github.com/filecoin-project/go-filecoin/address"
"github.com/filecoin-project/go-filecoin/chain"
+ "github.com/filecoin-project/go-filecoin/config"
"github.com/filecoin-project/go-filecoin/metrics"
"github.com/filecoin-project/go-filecoin/types"
) | 1 | package core
import (
"context"
"sync"
"github.com/ipfs/go-cid"
"github.com/pkg/errors"
"github.com/filecoin-project/go-filecoin/address"
"github.com/filecoin-project/go-filecoin/chain"
"github.com/filecoin-project/go-filecoin/metrics"
"github.com/filecoin-project/go-filecoin/types"
)
var mpSize = metrics.NewInt64Gauge("message_pool_size", "The size of the message pool")
// MessageTimeOut is the number of tipsets we should receive before timing out messages
const MessageTimeOut = 6
type timedmessage struct {
message *types.SignedMessage
addedAt uint64
}
// BlockTimer defines a interface to a struct that can give the current block height.
type BlockTimer interface {
BlockHeight() (uint64, error)
}
// MessagePool keeps an unordered, de-duplicated set of Messages and supports removal by CID.
// By 'de-duplicated' we mean that insertion of a message by cid that already
// exists is a nop. We use a MessagePool to store all messages received by this node
// via network or directly created via user command that have yet to be included
// in a block. Messages are removed as they are processed.
//
// MessagePool is safe for concurrent access.
type MessagePool struct {
lk sync.RWMutex
timer BlockTimer
pending map[cid.Cid]*timedmessage // all pending messages
}
// Add adds a message to the pool.
func (pool *MessagePool) Add(msg *types.SignedMessage) (cid.Cid, error) {
blockTime, err := pool.timer.BlockHeight()
if err != nil {
return cid.Undef, err
}
return pool.addTimedMessage(&timedmessage{message: msg, addedAt: blockTime})
}
func (pool *MessagePool) addTimedMessage(msg *timedmessage) (cid.Cid, error) {
pool.lk.Lock()
defer pool.lk.Unlock()
c, err := msg.message.Cid()
if err != nil {
return cid.Undef, errors.Wrap(err, "failed to create CID")
}
// Reject messages with invalid signatires
if !msg.message.VerifySignature() {
return cid.Undef, errors.Errorf("failed to add message %s to pool: sig invalid", c.String())
}
pool.pending[c] = msg
mpSize.Set(context.TODO(), int64(len(pool.pending)))
return c, nil
}
// Pending returns all pending messages.
func (pool *MessagePool) Pending() []*types.SignedMessage {
pool.lk.Lock()
defer pool.lk.Unlock()
out := make([]*types.SignedMessage, 0, len(pool.pending))
for _, msg := range pool.pending {
out = append(out, msg.message)
}
return out
}
// Get retrieves a message from the pool by CID.
func (pool *MessagePool) Get(c cid.Cid) (*types.SignedMessage, bool) {
pool.lk.Lock()
defer pool.lk.Unlock()
value, ok := pool.pending[c]
if !ok {
return nil, ok
} else if value == nil {
panic("Found nil message for CID " + c.String())
}
return value.message, ok
}
// Remove removes the message by CID from the pending pool.
func (pool *MessagePool) Remove(c cid.Cid) {
pool.lk.Lock()
defer pool.lk.Unlock()
delete(pool.pending, c)
mpSize.Set(context.TODO(), int64(len(pool.pending)))
}
// NewMessagePool constructs a new MessagePool.
func NewMessagePool(timer BlockTimer) *MessagePool {
return &MessagePool{
timer: timer,
pending: make(map[cid.Cid]*timedmessage),
}
}
// UpdateMessagePool brings the message pool into the correct state after
// we accept a new block. It removes messages from the pool that are
// found in the newly adopted chain and adds back those from the removed
// chain (if any) that do not appear in the new chain. We think
// that the right model for keeping the message pool up to date is
// to think about it like a garbage collector.
//
// TODO there is considerable functionality missing here: don't add
// messages that have expired, respect nonce, do this efficiently,
// etc.
func (pool *MessagePool) UpdateMessagePool(ctx context.Context, store chain.BlockProvider, oldHead, newHead types.TipSet) error {
oldBlocks, newBlocks, err := CollectBlocksToCommonAncestor(ctx, store, oldHead, newHead)
if err != nil {
return err
}
// Add all message from the old blocks to the message pool, so they can be mined again.
for _, blk := range oldBlocks {
for _, msg := range blk.Messages {
_, err = pool.addTimedMessage(&timedmessage{message: msg, addedAt: uint64(blk.Height)})
if err != nil {
return err
}
}
}
// Remove all messages in the new blocks from the pool, now mined.
// Cid() can error, so collect all the CIDs up front.
var removeCids []cid.Cid
for _, blk := range newBlocks {
for _, msg := range blk.Messages {
cid, err := msg.Cid()
if err != nil {
return err
}
removeCids = append(removeCids, cid)
}
}
for _, c := range removeCids {
pool.Remove(c)
}
// prune all messages that have been in the pool too long
return pool.timeoutMessages(ctx, store, newHead)
}
// timeoutMessages removes all messages from the pool that arrived more than MessageTimeout tip sets ago.
// Note that we measure the timeout in the number of tip sets we have received rather than a fixed block
// height. This prevents us from prematurely timing messages that arrive during long chains of null blocks.
// Also when blocks fill, the rate of message processing will correspond more closely to rate of tip
// sets than to the expected block time over short timescales.
func (pool *MessagePool) timeoutMessages(ctx context.Context, store chain.BlockProvider, head types.TipSet) error {
var err error
lowestTipSet := head
minimumHeight, err := lowestTipSet.Height()
if err != nil {
return err
}
// walk back MessageTimeout tip sets to arrive at the lowest viable block height
for i := 0; minimumHeight > 0 && i < MessageTimeOut; i++ {
lowestTipSet, err = chain.GetParentTipSet(ctx, store, lowestTipSet)
if err != nil {
return err
}
minimumHeight, err = lowestTipSet.Height()
if err != nil {
return err
}
}
// remove all messages added before minimumHeight
for cid, msg := range pool.pending {
if msg.addedAt < minimumHeight {
pool.Remove(cid)
}
}
return nil
}
// LargestNonce returns the largest nonce used by a message from address in the pool.
// If no messages from address are found, found will be false.
func (pool *MessagePool) LargestNonce(address address.Address) (largest uint64, found bool) {
for _, m := range pool.Pending() {
if m.From == address {
found = true
if uint64(m.Nonce) > largest {
largest = uint64(m.Nonce)
}
}
}
return
}
| 1 | 18,431 | Not your immediate problem, but having everything depend on a package that has the config for everything else is ick. Can you move the MessagePoolConfig here and reverse the dependency? | filecoin-project-venus | go |
@@ -443,9 +443,6 @@ public class PasscodeActivityTest extends
v.onEditorAction(actionCode);
}
});
- waitSome();
- //the enter key will send ACTION_DOWN and ACTION_UP both events out
- this.sendKeys(KeyEvent.KEYCODE_ENTER);
} catch (Throwable t) {
fail("Failed do editor action " + actionCode);
} | 1 | /*
* Copyright (c) 2011, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software 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 salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.samples.templateapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.security.PasscodeManager;
import com.salesforce.androidsdk.ui.PasscodeActivity;
import com.salesforce.androidsdk.ui.PasscodeActivity.PasscodeMode;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
import com.salesforce.androidsdk.util.test.EventsListenerQueue;
/**
* Tests for PasscodeActivity
*/
public class PasscodeActivityTest extends
ActivityInstrumentationTestCase2<PasscodeActivity> {
private EventsListenerQueue eq;
private Context targetContext;
private PasscodeActivity passcodeActivity;
private PasscodeManager passcodeManager;
public PasscodeActivityTest() {
super(PasscodeActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
eq = new EventsListenerQueue();
// Waits for app initialization to complete.
if (!SalesforceSDKManager.hasInstance()) {
eq.waitForEvent(EventType.AppCreateComplete, 5000);
}
targetContext = getInstrumentation().getTargetContext();
passcodeManager = SalesforceSDKManager.getInstance().getPasscodeManager();
passcodeManager.reset(targetContext);
passcodeManager.setTimeoutMs(600000);
assertTrue("Application should be locked", passcodeManager.isLocked());
assertFalse("Application should not have a passcode", passcodeManager.hasStoredPasscode(targetContext));
}
@Override
public void tearDown() throws Exception {
if (passcodeActivity != null) {
passcodeActivity.finish();
passcodeActivity = null;
}
if (eq != null) {
eq.tearDown();
eq = null;
}
super.tearDown();
}
/**
* Test passcode creation flow when no mistakes are made by user
*/
public void testCreateWithNoMistakes() {
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in create mode", PasscodeMode.Create, passcodeActivity.getMode());
// Entering in 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in check mode", PasscodeMode.CreateConfirm, passcodeActivity.getMode());
// Re-entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
}
/**
* Test passcode change flow when no mistakes are made by user
*/
public void testChangeWithNoMistakes() {
// Get activity
final Intent i = new Intent(SalesforceSDKManager.getInstance().getAppContext(),
SalesforceSDKManager.getInstance().getPasscodeActivity());
i.putExtra(PasscodeManager.CHANGE_PASSCODE_KEY, true);
setActivityIntent(i);
passcodeActivity = getActivity();
assertEquals("Activity expected in change mode", PasscodeMode.Change, passcodeActivity.getMode());
// Entering in 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in check mode", PasscodeMode.CreateConfirm, passcodeActivity.getMode());
// Re-entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
}
/**
* Test passcode creation flow when user try to enter a passcode too short
*/
public void testCreateWithPasscodeTooShort() {
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in create mode", PasscodeMode.Create, passcodeActivity.getMode());
// Entering nothing and submitting -> expect passcode too short error
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in create mode still", PasscodeMode.Create, passcodeActivity.getMode());
assertEquals("Error expected", "The passcode must be at least 4 characters long",
((TextView) passcodeActivity.findViewById(com.salesforce.androidsdk.R.id.sf__passcode_error)).getText());
// Entering in 123 and submitting -> expect passcode too short error
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in create mode still", PasscodeMode.Create, passcodeActivity.getMode());
assertEquals("Error expected", "The passcode must be at least 4 characters long",
((TextView) passcodeActivity.findViewById(com.salesforce.androidsdk.R.id.sf__passcode_error)).getText());
// Entering in 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in create confirm mode", PasscodeMode.CreateConfirm, passcodeActivity.getMode());
// Re-entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
}
/**
* Test passcode creation flow when user enter a passcode too short during confirmation
*/
public void testCreateWithConfirmPasscodeTooShort() {
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in create mode", PasscodeMode.Create, passcodeActivity.getMode());
// Entering in 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in check mode", PasscodeMode.CreateConfirm, passcodeActivity.getMode());
// Entering in 123 and submitting -> expect passcode too short error
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in create confirm mode still", PasscodeMode.CreateConfirm, passcodeActivity.getMode());
assertEquals("Error expected", "The passcode must be at least 4 characters long",
((TextView) passcodeActivity.findViewById(com.salesforce.androidsdk.R.id.sf__passcode_error)).getText());
// Entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
}
/**
* Test passcode creation flow when user enter a different passcode during confirmation
*/
public void testCreateWithWrongConfirmPasscode() {
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in create mode", PasscodeMode.Create, passcodeActivity.getMode());
// Entering in 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should be still locked", passcodeManager.isLocked());
assertEquals("Activity expected in check mode", PasscodeMode.CreateConfirm, passcodeActivity.getMode());
// Entering in 654321 and submitting -> expect passcodes don't match error
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "654321");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should be still locked", passcodeManager.isLocked());
assertEquals("Activity expected in create confirm mode still", PasscodeMode.CreateConfirm, passcodeActivity.getMode());
assertEquals("Error expected", "Passcodes don't match!",
((TextView) passcodeActivity.findViewById(com.salesforce.androidsdk.R.id.sf__passcode_error)).getText());
// Entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
}
/**
* Test passcode verification flow when no mistakes are made by user
*/
public void testVerificationWithNoMistakes() {
// Store passcode and set mode to Check
passcodeManager.store(targetContext, "123456");
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in check mode", PasscodeMode.Check, passcodeActivity.getMode());
// We should still be locked
assertTrue("Application should still be locked", passcodeManager.isLocked());
// Entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
}
/**
* Test passcode verification flow when user enters wrong passcode once
*/
public void testVerificationWithWrongPasscodeOnce() {
// Store passcode and set mode to Check
passcodeManager.store(targetContext, "123456");
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in check mode", PasscodeMode.Check, passcodeActivity.getMode());
// We should still be locked
assertTrue("Application should still be locked", passcodeManager.isLocked());
// Entering 654321 and submitting -> expect passcode incorrect error
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "654321");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in check mode still", PasscodeMode.Check, passcodeActivity.getMode());
assertEquals("Error expected", "The passcode you entered is incorrect. Please try again. You have 9 attempts remaining.",
((TextView) passcodeActivity.findViewById(com.salesforce.androidsdk.R.id.sf__passcode_error)).getText());
assertEquals("Wrong failure count", 1, passcodeManager.getFailedPasscodeAttempts());
// Entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
}
/**
* Test passcode verification flow when user enters wrong passcode twice
*/
public void testVerificationWithWrongPasscodeTwice() {
// Store passcode and set mode to Check
passcodeManager.store(targetContext, "123456");
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in check mode", PasscodeMode.Check, passcodeActivity.getMode());
// We should still be locked
assertTrue("Application should still be locked", passcodeManager.isLocked());
for (int i = 1; i < 10; i++) {
enterWrongPasscode(i);
}
// Entering 123456 and submitting
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "123456");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should be unlocked", passcodeManager.isLocked());
}
/**
* Test passcode verification flow when user enters a passcode too short
*/
public void testVerificationWithPasscodeTooShort() {
// Store passcode and set mode to Check
passcodeManager.store(targetContext, "123456");
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in check mode", PasscodeMode.Check, passcodeActivity.getMode());
// We should still be locked
assertTrue("Application should still be locked", passcodeManager.isLocked());
// Entering 123 and submitting -> expect passcode too short error, not counted as attempt
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "654321");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in check mode still", PasscodeMode.Check, passcodeActivity.getMode());
assertEquals("Error expected", "The passcode you entered is incorrect. Please try again. You have 9 attempts remaining.",
((TextView) passcodeActivity.findViewById(com.salesforce.androidsdk.R.id.sf__passcode_error)).getText());
assertEquals("Wrong failure count", 1, passcodeManager.getFailedPasscodeAttempts());
}
/**
* Test passcode verification flow when user enters wrong passcode too many times
*/
public void testVerificationWithWrongPasscodeTooManyTimes() {
// Store passcode and set mode to Check
passcodeManager.store(targetContext, "123456");
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in check mode", PasscodeMode.Check, passcodeActivity.getMode());
passcodeActivity.enableLogout(false); // logout is async, it creates havoc when running other tests
// We should still be locked
assertTrue("Application should still be locked", passcodeManager.isLocked());
for (int i = 1; i < 10; i++) {
enterWrongPasscode(i);
}
// Entering 132645 and submitting -> expect passcode manager to be reset
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "132645");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertFalse("Application should not have a passcode", passcodeManager.hasStoredPasscode(targetContext));
}
/**
* Test when user clicks on the 'Forgot Passcode' link.
*/
public void testForgotPasscodeLink() throws Throwable {
// Store passcode and set mode to Check.
passcodeManager.store(targetContext, "123456");
assertTrue("Stored passcode should match entered passcode", passcodeManager.check(targetContext, "123456"));
// Get activity
passcodeActivity = getActivity();
assertEquals("Activity expected in check mode", PasscodeMode.Check, passcodeActivity.getMode());
passcodeActivity.enableLogout(false); // logout is async, it creates havoc when running other tests
// We should still be locked.
assertTrue("Application should still be locked", passcodeManager.isLocked());
// Click on 'Forgot Passcode' link.
assertFalse("Logout dialog should not be showing", getActivity().getIsLogoutDialogShowing());
clickView(getActivity().findViewById(com.salesforce.androidsdk.R.id.sf__passcode_forgot));
waitSome();
assertTrue("Logout dialog should be showing", getActivity().getIsLogoutDialogShowing());
// Clicking on 'Cancel' should take us back to the passcode screen.
final AlertDialog logoutDialog = getActivity().getLogoutAlertDialog();
clickView(logoutDialog.getButton(AlertDialog.BUTTON_NEGATIVE));
waitSome();
assertFalse("Logout dialog should not be showing", getActivity().getIsLogoutDialogShowing());
// Clicking on 'Ok' should log the user out.
clickView(getActivity().findViewById(com.salesforce.androidsdk.R.id.sf__passcode_forgot));
waitSome();
clickView(logoutDialog.getButton(AlertDialog.BUTTON_POSITIVE));
waitSome();
assertFalse("Application should not have a passcode", passcodeManager.hasStoredPasscode(targetContext));
}
private void enterWrongPasscode(int count) {
// Entering 321654 and submitting -> expect passcode incorrect error
setText(com.salesforce.androidsdk.R.id.sf__passcode_text, "321654");
doEditorAction(com.salesforce.androidsdk.R.id.sf__passcode_text, EditorInfo.IME_ACTION_GO);
assertTrue("Application should still be locked", passcodeManager.isLocked());
assertEquals("Activity expected in check mode still", PasscodeMode.Check, passcodeActivity.getMode());
if (count == 9) {
assertEquals("Error expected", "Final passcode attempt",
((TextView) passcodeActivity.findViewById(com.salesforce.androidsdk.R.id.sf__passcode_error)).getText());
}
assertEquals("Wrong failure count", count, passcodeManager.getFailedPasscodeAttempts());
}
private void clickView(final View v) {
try {
runTestOnUiThread(new Runnable() {
@Override
public void run() {
v.performClick();
}
});
} catch (Throwable t) {
fail("Failed to click view " + v);
}
}
private void setText(final int textViewId, final String text) {
try {
runTestOnUiThread(new Runnable() {
@Override public void run() {
TextView v = (TextView) getActivity().findViewById(textViewId);
v.setText(text);
if (v instanceof EditText)
((EditText) v).setSelection(v.getText().length());
}
});
} catch (Throwable t) {
fail("Failed to set text " + text);
}
}
private void doEditorAction(final int textViewId, final int actionCode) {
try {
runTestOnUiThread(new Runnable() {
@Override public void run() {
TextView v = (TextView) getActivity().findViewById(textViewId);
v.onEditorAction(actionCode);
}
});
waitSome();
//the enter key will send ACTION_DOWN and ACTION_UP both events out
this.sendKeys(KeyEvent.KEYCODE_ENTER);
} catch (Throwable t) {
fail("Failed do editor action " + actionCode);
}
}
private void waitSome() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
fail("Test interrupted");
}
}
}
| 1 | 15,459 | recently, IME_ACTION_GO action can trigger key_down and key_up event successfully, so we don't need to send enter key separately as before, otherwise will trigger it twice and cause to enter empty passcode, which cause test failed. | forcedotcom-SalesforceMobileSDK-Android | java |
@@ -46,6 +46,7 @@ Status FindPathValidator::validateWhere(WhereClause* where) {
}
where->setFilter(ExpressionUtils::rewriteLabelAttr2EdgeProp(expr));
auto filter = where->filter();
+ NG_RETURN_IF_ERROR(checkExprDepth(filter));
auto typeStatus = deduceExprType(filter);
NG_RETURN_IF_ERROR(typeStatus); | 1 | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include "graph/validator/FindPathValidator.h"
#include "graph/planner/plan/Algo.h"
#include "graph/planner/plan/Logic.h"
#include "graph/util/ExpressionUtils.h"
#include "graph/util/ValidateUtil.h"
namespace nebula {
namespace graph {
Status FindPathValidator::validateImpl() {
auto fpSentence = static_cast<FindPathSentence*>(sentence_);
pathCtx_ = getContext<PathContext>();
pathCtx_->isShortest = fpSentence->isShortest();
pathCtx_->noLoop = fpSentence->noLoop();
pathCtx_->withProp = fpSentence->withProp();
pathCtx_->inputVarName = inputVarName_;
NG_RETURN_IF_ERROR(validateStarts(fpSentence->from(), pathCtx_->from));
NG_RETURN_IF_ERROR(validateStarts(fpSentence->to(), pathCtx_->to));
NG_RETURN_IF_ERROR(ValidateUtil::validateOver(qctx_, fpSentence->over(), pathCtx_->over));
NG_RETURN_IF_ERROR(validateWhere(fpSentence->where()));
NG_RETURN_IF_ERROR(ValidateUtil::validateStep(fpSentence->step(), pathCtx_->steps));
NG_RETURN_IF_ERROR(validateYield(fpSentence->yield()));
return Status::OK();
}
Status FindPathValidator::validateWhere(WhereClause* where) {
if (where == nullptr) {
return Status::OK();
}
// Not Support $-、$var、$$.tag.prop、$^.tag.prop、agg
auto expr = where->filter();
if (ExpressionUtils::findAny(expr,
{Expression::Kind::kAggregate,
Expression::Kind::kSrcProperty,
Expression::Kind::kDstProperty,
Expression::Kind::kVarProperty,
Expression::Kind::kInputProperty})) {
return Status::SemanticError("Not support `%s' in where sentence.", expr->toString().c_str());
}
where->setFilter(ExpressionUtils::rewriteLabelAttr2EdgeProp(expr));
auto filter = where->filter();
auto typeStatus = deduceExprType(filter);
NG_RETURN_IF_ERROR(typeStatus);
auto type = typeStatus.value();
if (type != Value::Type::BOOL && type != Value::Type::NULLVALUE &&
type != Value::Type::__EMPTY__) {
std::stringstream ss;
ss << "`" << filter->toString() << "', expected Boolean, "
<< "but was `" << type << "'";
return Status::SemanticError(ss.str());
}
NG_RETURN_IF_ERROR(deduceProps(filter, pathCtx_->exprProps));
pathCtx_->filter = filter;
return Status::OK();
}
Status FindPathValidator::validateYield(YieldClause* yield) {
if (yield == nullptr) {
return Status::SemanticError("Missing yield clause.");
}
if (yield->columns().size() != 1) {
return Status::SemanticError("Only support yield path");
}
auto col = yield->columns().front();
if (col->expr()->kind() != Expression::Kind::kLabel || col->expr()->toString() != "PATH") {
return Status::SemanticError("Illegal yield clauses `%s'. only support yield path",
col->toString().c_str());
}
outputs_.emplace_back(col->name(), Value::Type::PATH);
pathCtx_->colNames = getOutColNames();
return Status::OK();
}
} // namespace graph
} // namespace nebula
| 1 | 32,626 | It seems that you only need to do this `checkExprDepth()` inside `deduceExprType()`. So you don't have to add this check everywhere. | vesoft-inc-nebula | cpp |
@@ -95,7 +95,8 @@ public class DefaultMailCreatorTest {
executableFlow.setStatus(Status.FAILED);
assertTrue(mailCreator.createErrorEmail(
executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber));
- assertEquals("Flow 'mail-creator-test' has failed on unit-tests", message.getSubject());
+ assertEquals("Flow 'mail-creator-test' has failed on unit-tests",
+ message.getSubject());
assertEquals(read("errorEmail.html"), message.getBody());
}
| 1 | package azkaban.executor.mail;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.ExecutionOptions;
import azkaban.executor.Status;
import azkaban.flow.Flow;
import azkaban.flow.Node;
import azkaban.project.Project;
import azkaban.utils.EmailMessage;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import org.apache.commons.io.IOUtils;
import org.joda.time.DateTimeUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class DefaultMailCreatorTest {
// 2016/07/17 11:54:11 EEST
public static final long START_TIME_MILLIS = 1468745651608L;
// 2016/07/17 11:54:16 EEST (START_TIME_MILLIS + 5 seconds)
public static final long END_TIME_MILLIS = START_TIME_MILLIS + 5_000L;
// 2016/07/17 11:54:21 EEST (START_TIME_MILLIS + 10 seconds)
public static final long FIXED_CURRENT_TIME_MILLIS = START_TIME_MILLIS + 10_000L;
private DefaultMailCreator mailCreator;
private ExecutableFlow executableFlow;
private Flow flow;
private Project project;
private ExecutionOptions options;
private EmailMessage message;
private String azkabanName;
private String scheme;
private String clientHostname;
private String clientPortNumber;
private TimeZone defaultTz;
@Before
public void setUp() throws Exception {
defaultTz = TimeZone.getDefault();
assertNotNull(defaultTz);
// EEST
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Helsinki"));
DateTimeUtils.setCurrentMillisFixed(FIXED_CURRENT_TIME_MILLIS);
mailCreator = new DefaultMailCreator();
flow = new Flow("mail-creator-test");
project = new Project(1, "test-project");
options = new ExecutionOptions();
message = new EmailMessage();
azkabanName = "unit-tests";
scheme = "http";
clientHostname = "localhost";
clientPortNumber = "8081";
Node failedNode = new Node("test-job");
failedNode.setType("noop");
flow.addNode(failedNode);
executableFlow = new ExecutableFlow(project, flow);
executableFlow.setExecutionOptions(options);
executableFlow.setStartTime(START_TIME_MILLIS);
options.setFailureEmails(ImmutableList.of("test@example.com"));
options.setSuccessEmails(ImmutableList.of("test@example.com"));
}
@After
public void tearDown() throws Exception {
if (defaultTz != null) {
TimeZone.setDefault(defaultTz);
}
DateTimeUtils.setCurrentMillisSystem();
}
private void setJobStatus(Status status) {
executableFlow.getExecutableNodes().get(0).setStatus(status);
}
@Test
public void createErrorEmail() throws Exception {
setJobStatus(Status.FAILED);
executableFlow.setEndTime(END_TIME_MILLIS);
executableFlow.setStatus(Status.FAILED);
assertTrue(mailCreator.createErrorEmail(
executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber));
assertEquals("Flow 'mail-creator-test' has failed on unit-tests", message.getSubject());
assertEquals(read("errorEmail.html"), message.getBody());
}
@Test
public void createFirstErrorMessage() throws Exception {
setJobStatus(Status.FAILED);
executableFlow.setStatus(Status.FAILED_FINISHING);
assertTrue(mailCreator.createFirstErrorMessage(
executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber));
assertEquals("Flow 'mail-creator-test' has encountered a failure on unit-tests", message.getSubject());
assertEquals(read("firstErrorMessage.html"), message.getBody());
}
@Test
public void createSuccessEmail() throws Exception {
setJobStatus(Status.SUCCEEDED);
executableFlow.setEndTime(END_TIME_MILLIS);
executableFlow.setStatus(Status.SUCCEEDED);
assertTrue(mailCreator.createSuccessEmail(
executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber));
assertEquals("Flow 'mail-creator-test' has succeeded on unit-tests", message.getSubject());
assertEquals(read("successEmail.html"), message.getBody());
}
private String read(String file) throws Exception {
InputStream is = DefaultMailCreatorTest.class.getResourceAsStream(file);
return IOUtils.toString(is, Charsets.UTF_8).trim();
}
}
| 1 | 13,098 | why split into two lines? | azkaban-azkaban | java |
@@ -48,8 +48,7 @@ import org.apache.iceberg.types.Types;
* represented by a named {@link PartitionField}.
*/
public class PartitionSpec implements Serializable {
- // start assigning IDs for partition fields at 1000
- private static final int PARTITION_DATA_ID_START = 1000;
+ public static final int PARTITION_DATA_ID_START = 1000;
private final Schema schema;
| 1 | /*
* 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.
*/
package org.apache.iceberg;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.iceberg.exceptions.ValidationException;
import org.apache.iceberg.transforms.Transforms;
import org.apache.iceberg.transforms.UnknownTransform;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;
/**
* Represents how to produce partition data for a table.
* <p>
* Partition data is produced by transforming columns in a table. Each column transform is
* represented by a named {@link PartitionField}.
*/
public class PartitionSpec implements Serializable {
// start assigning IDs for partition fields at 1000
private static final int PARTITION_DATA_ID_START = 1000;
private final Schema schema;
// this is ordered so that DataFile has a consistent schema
private final int specId;
private final PartitionField[] fields;
private transient volatile ListMultimap<Integer, PartitionField> fieldsBySourceId = null;
private transient volatile Map<String, PartitionField> fieldsByName = null;
private transient volatile Class<?>[] lazyJavaClasses = null;
private transient volatile List<PartitionField> fieldList = null;
private PartitionSpec(Schema schema, int specId, List<PartitionField> fields) {
this.schema = schema;
this.specId = specId;
this.fields = new PartitionField[fields.size()];
for (int i = 0; i < this.fields.length; i += 1) {
this.fields[i] = fields.get(i);
}
}
/**
* @return the {@link Schema} for this spec.
*/
public Schema schema() {
return schema;
}
/**
* @return the ID of this spec
*/
public int specId() {
return specId;
}
/**
* @return the list of {@link PartitionField partition fields} for this spec.
*/
public List<PartitionField> fields() {
return lazyFieldList();
}
/**
* @param fieldId a field id from the source schema
* @return the {@link PartitionField field} that partitions the given source field
*/
public List<PartitionField> getFieldsBySourceId(int fieldId) {
return lazyFieldsBySourceId().get(fieldId);
}
/**
* @return a {@link Types.StructType} for partition data defined by this spec.
*/
public Types.StructType partitionType() {
List<Types.NestedField> structFields = Lists.newArrayListWithExpectedSize(fields.length);
for (int i = 0; i < fields.length; i += 1) {
PartitionField field = fields[i];
Type sourceType = schema.findType(field.sourceId());
Type resultType = field.transform().getResultType(sourceType);
// assign ids for partition fields starting at PARTITION_DATA_ID_START to leave room for data file's other fields
structFields.add(
Types.NestedField.optional(PARTITION_DATA_ID_START + i, field.name(), resultType));
}
return Types.StructType.of(structFields);
}
public Class<?>[] javaClasses() {
if (lazyJavaClasses == null) {
synchronized (this) {
if (lazyJavaClasses == null) {
Class<?>[] classes = new Class<?>[fields.length];
for (int i = 0; i < fields.length; i += 1) {
PartitionField field = fields[i];
if (field.transform() instanceof UnknownTransform) {
classes[i] = Object.class;
} else {
Type sourceType = schema.findType(field.sourceId());
Type result = field.transform().getResultType(sourceType);
classes[i] = result.typeId().javaClass();
}
}
this.lazyJavaClasses = classes;
}
}
}
return lazyJavaClasses;
}
@SuppressWarnings("unchecked")
private <T> T get(StructLike data, int pos, Class<?> javaClass) {
return data.get(pos, (Class<T>) javaClass);
}
private String escape(String string) {
try {
return URLEncoder.encode(string, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public String partitionToPath(StructLike data) {
StringBuilder sb = new StringBuilder();
Class<?>[] javaClasses = javaClasses();
for (int i = 0; i < javaClasses.length; i += 1) {
PartitionField field = fields[i];
String valueString = field.transform().toHumanString(get(data, i, javaClasses[i]));
if (i > 0) {
sb.append("/");
}
sb.append(field.name()).append("=").append(escape(valueString));
}
return sb.toString();
}
/**
* Returns true if this spec is equivalent to the other, with field names ignored. That is, if
* both specs have the same number of fields, field order, source columns, and transforms.
*
* @param other another PartitionSpec
* @return true if the specs have the same fields, source columns, and transforms.
*/
public boolean compatibleWith(PartitionSpec other) {
if (equals(other)) {
return true;
}
if (fields.length != other.fields.length) {
return false;
}
for (int i = 0; i < fields.length; i += 1) {
PartitionField thisField = fields[i];
PartitionField thatField = other.fields[i];
if (thisField.sourceId() != thatField.sourceId() ||
!thisField.transform().toString().equals(thatField.transform().toString())) {
return false;
}
}
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
PartitionSpec that = (PartitionSpec) other;
if (this.specId != that.specId) {
return false;
}
return Arrays.equals(fields, that.fields);
}
@Override
public int hashCode() {
return Objects.hashCode(Arrays.hashCode(fields));
}
private List<PartitionField> lazyFieldList() {
if (fieldList == null) {
synchronized (this) {
if (fieldList == null) {
this.fieldList = ImmutableList.copyOf(fields);
}
}
}
return fieldList;
}
private Map<String, PartitionField> lazyFieldsByName() {
if (fieldsByName == null) {
synchronized (this) {
if (fieldsByName == null) {
ImmutableMap.Builder<String, PartitionField> builder = ImmutableMap.builder();
for (PartitionField field : fields) {
builder.put(field.name(), field);
}
this.fieldsByName = builder.build();
}
}
}
return fieldsByName;
}
private ListMultimap<Integer, PartitionField> lazyFieldsBySourceId() {
if (fieldsBySourceId == null) {
synchronized (this) {
if (fieldsBySourceId == null) {
ListMultimap<Integer, PartitionField> multiMap = Multimaps
.newListMultimap(Maps.newHashMap(), () -> Lists.newArrayListWithCapacity(fields.length));
for (PartitionField field : fields) {
multiMap.put(field.sourceId(), field);
}
this.fieldsBySourceId = multiMap;
}
}
}
return fieldsBySourceId;
}
/**
* Returns the source field ids for identity partitions.
*
* @return a set of source ids for the identity partitions.
*/
public Set<Integer> identitySourceIds() {
Set<Integer> sourceIds = Sets.newHashSet();
for (PartitionField field : fields()) {
if ("identity".equals(field.transform().toString())) {
sourceIds.add(field.sourceId());
}
}
return sourceIds;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (PartitionField field : fields) {
sb.append("\n");
sb.append(" ").append(field);
}
if (fields.length > 0) {
sb.append("\n");
}
sb.append("]");
return sb.toString();
}
private static final PartitionSpec UNPARTITIONED_SPEC =
new PartitionSpec(new Schema(), 0, ImmutableList.of());
/**
* Returns a spec for unpartitioned tables.
*
* @return a partition spec with no partitions
*/
public static PartitionSpec unpartitioned() {
return UNPARTITIONED_SPEC;
}
/**
* Creates a new {@link Builder partition spec builder} for the given {@link Schema}.
*
* @param schema a schema
* @return a partition spec builder for the given schema
*/
public static Builder builderFor(Schema schema) {
return new Builder(schema);
}
/**
* Used to create valid {@link PartitionSpec partition specs}.
* <p>
* Call {@link #builderFor(Schema)} to create a new builder.
*/
public static class Builder {
private final Schema schema;
private final List<PartitionField> fields = Lists.newArrayList();
private final Set<String> partitionNames = Sets.newHashSet();
private Map<Integer, PartitionField> timeFields = Maps.newHashMap();
private int specId = 0;
private Builder(Schema schema) {
this.schema = schema;
}
private void checkAndAddPartitionName(String name) {
checkAndAddPartitionName(name, null);
}
private void checkAndAddPartitionName(String name, Integer identitySourceColumnId) {
Types.NestedField schemaField = schema.findField(name);
if (identitySourceColumnId != null) {
// for identity transform case we allow conflicts between partition and schema field name as
// long as they are sourced from the same schema field
Preconditions.checkArgument(schemaField == null || schemaField.fieldId() == identitySourceColumnId,
"Cannot create identity partition sourced from different field in schema: %s", name);
} else {
// for all other transforms we don't allow conflicts between partition name and schema field name
Preconditions.checkArgument(schemaField == null,
"Cannot create partition from name that exists in schema: %s", name);
}
Preconditions.checkArgument(name != null && !name.isEmpty(),
"Cannot use empty or null partition name: %s", name);
Preconditions.checkArgument(!partitionNames.contains(name),
"Cannot use partition name more than once: %s", name);
partitionNames.add(name);
}
private void checkForRedundantPartitions(PartitionField field) {
PartitionField timeField = timeFields.get(field.sourceId());
Preconditions.checkArgument(timeField == null,
"Cannot add redundant partition: %s conflicts with %s", timeField, field);
timeFields.put(field.sourceId(), field);
}
public Builder withSpecId(int newSpecId) {
this.specId = newSpecId;
return this;
}
private Types.NestedField findSourceColumn(String sourceName) {
Types.NestedField sourceColumn = schema.findField(sourceName);
Preconditions.checkArgument(sourceColumn != null, "Cannot find source column: %s", sourceName);
return sourceColumn;
}
Builder identity(String sourceName, String targetName) {
Types.NestedField sourceColumn = findSourceColumn(sourceName);
checkAndAddPartitionName(targetName, sourceColumn.fieldId());
fields.add(new PartitionField(
sourceColumn.fieldId(), targetName, Transforms.identity(sourceColumn.type())));
return this;
}
public Builder identity(String sourceName) {
return identity(sourceName, sourceName);
}
public Builder year(String sourceName, String targetName) {
checkAndAddPartitionName(targetName);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
PartitionField field = new PartitionField(
sourceColumn.fieldId(), targetName, Transforms.year(sourceColumn.type()));
checkForRedundantPartitions(field);
fields.add(field);
return this;
}
public Builder year(String sourceName) {
return year(sourceName, sourceName + "_year");
}
public Builder month(String sourceName, String targetName) {
checkAndAddPartitionName(targetName);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
PartitionField field = new PartitionField(
sourceColumn.fieldId(), targetName, Transforms.month(sourceColumn.type()));
checkForRedundantPartitions(field);
fields.add(field);
return this;
}
public Builder month(String sourceName) {
return month(sourceName, sourceName + "_month");
}
public Builder day(String sourceName, String targetName) {
checkAndAddPartitionName(targetName);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
PartitionField field = new PartitionField(
sourceColumn.fieldId(), targetName, Transforms.day(sourceColumn.type()));
checkForRedundantPartitions(field);
fields.add(field);
return this;
}
public Builder day(String sourceName) {
return day(sourceName, sourceName + "_day");
}
public Builder hour(String sourceName, String targetName) {
checkAndAddPartitionName(targetName);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
PartitionField field = new PartitionField(
sourceColumn.fieldId(), targetName, Transforms.hour(sourceColumn.type()));
checkForRedundantPartitions(field);
fields.add(field);
return this;
}
public Builder hour(String sourceName) {
return hour(sourceName, sourceName + "_hour");
}
public Builder bucket(String sourceName, int numBuckets, String targetName) {
checkAndAddPartitionName(targetName);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), targetName, Transforms.bucket(sourceColumn.type(), numBuckets)));
return this;
}
public Builder bucket(String sourceName, int numBuckets) {
return bucket(sourceName, numBuckets, sourceName + "_bucket");
}
public Builder truncate(String sourceName, int width, String targetName) {
checkAndAddPartitionName(targetName);
Types.NestedField sourceColumn = findSourceColumn(sourceName);
fields.add(new PartitionField(
sourceColumn.fieldId(), targetName, Transforms.truncate(sourceColumn.type(), width)));
return this;
}
public Builder truncate(String sourceName, int width) {
return truncate(sourceName, width, sourceName + "_trunc");
}
Builder add(int sourceId, String name, String transform) {
Types.NestedField column = schema.findField(sourceId);
checkAndAddPartitionName(name, column.fieldId());
Preconditions.checkNotNull(column, "Cannot find source column: %d", sourceId);
fields.add(new PartitionField(sourceId, name, Transforms.fromString(column.type(), transform)));
return this;
}
public PartitionSpec build() {
PartitionSpec spec = new PartitionSpec(schema, specId, fields);
checkCompatibility(spec, schema);
return spec;
}
}
static void checkCompatibility(PartitionSpec spec, Schema schema) {
for (PartitionField field : spec.fields) {
Type sourceType = schema.findType(field.sourceId());
ValidationException.check(sourceType != null,
"Cannot find source column for partition field: %s", field);
ValidationException.check(sourceType.isPrimitiveType(),
"Cannot partition by non-primitive source field: %s", sourceType);
ValidationException.check(
field.transform().canTransform(sourceType),
"Invalid source type %s for transform: %s",
sourceType, field.transform());
}
}
}
| 1 | 15,738 | Does this need to be public or can it be package-private? | apache-iceberg | java |
@@ -86,6 +86,11 @@ class FileCard extends Component {
render () {
const file = this.props.files[this.props.fileCardFor]
+ let showEditButton
+ this.props.editors.forEach((target) => {
+ showEditButton = this.props.getPlugin(target.id).сanEditFile(file)
+ })
+
return (
<div
class="uppy-Dashboard-FileCard" | 1 | const { h, Component } = require('preact')
const getFileTypeIcon = require('../../utils/getFileTypeIcon')
const ignoreEvent = require('../../utils/ignoreEvent.js')
const FilePreview = require('../FilePreview')
class FileCard extends Component {
constructor (props) {
super(props)
const file = this.props.files[this.props.fileCardFor]
const metaFields = this.props.metaFields || []
const storedMetaData = {}
metaFields.forEach((field) => {
storedMetaData[field.id] = file.meta[field.id] || ''
})
this.state = {
formState: storedMetaData
}
}
saveOnEnter = (ev) => {
if (ev.keyCode === 13) {
ev.stopPropagation()
ev.preventDefault()
const file = this.props.files[this.props.fileCardFor]
this.props.saveFileCard(this.state.formState, file.id)
}
}
updateMeta = (newVal, name) => {
this.setState({
formState: {
...this.state.formState,
[name]: newVal
}
})
}
handleSave = () => {
const fileID = this.props.fileCardFor
this.props.saveFileCard(this.state.formState, fileID)
}
handleCancel = () => {
this.props.toggleFileCard()
}
renderMetaFields = () => {
const metaFields = this.props.metaFields || []
const fieldCSSClasses = {
text: 'uppy-u-reset uppy-c-textInput uppy-Dashboard-FileCard-input'
}
return metaFields.map((field) => {
const id = `uppy-Dashboard-FileCard-input-${field.id}`
return (
<fieldset key={field.id} class="uppy-Dashboard-FileCard-fieldset">
<label class="uppy-Dashboard-FileCard-label" for={id}>{field.name}</label>
{field.render !== undefined
? field.render({
value: this.state.formState[field.id],
onChange: (newVal) => this.updateMeta(newVal, field.id),
fieldCSSClasses: fieldCSSClasses
}, h)
: (
<input
class={fieldCSSClasses.text}
id={id}
type={field.type || 'text'}
value={this.state.formState[field.id]}
placeholder={field.placeholder}
onkeyup={this.saveOnEnter}
onkeydown={this.saveOnEnter}
onkeypress={this.saveOnEnter}
oninput={ev => this.updateMeta(ev.target.value, field.id)}
data-uppy-super-focusable
/>
)}
</fieldset>
)
})
}
render () {
const file = this.props.files[this.props.fileCardFor]
return (
<div
class="uppy-Dashboard-FileCard"
data-uppy-panelType="FileCard"
onDragOver={ignoreEvent}
onDragLeave={ignoreEvent}
onDrop={ignoreEvent}
onPaste={ignoreEvent}
>
<div class="uppy-DashboardContent-bar">
<div class="uppy-DashboardContent-title" role="heading" aria-level="1">
{this.props.i18nArray('editing', {
file: <span class="uppy-DashboardContent-titleFile">{file.meta ? file.meta.name : file.name}</span>
})}
</div>
<button
class="uppy-DashboardContent-back" type="button" title={this.props.i18n('finishEditingFile')}
onclick={this.handleSave}
>
{this.props.i18n('done')}
</button>
</div>
<div class="uppy-Dashboard-FileCard-inner">
<div class="uppy-Dashboard-FileCard-preview" style={{ backgroundColor: getFileTypeIcon(file.type).color }}>
<FilePreview file={file} />
</div>
<div class="uppy-Dashboard-FileCard-info">
{this.renderMetaFields()}
</div>
<div class="uppy-Dashboard-FileCard-actions">
<button
class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Dashboard-FileCard-actionsBtn"
type="button"
onclick={this.handleSave}
>
{this.props.i18n('saveChanges')}
</button>
<button
class="uppy-u-reset uppy-c-btn uppy-c-btn-link uppy-Dashboard-FileCard-actionsBtn"
type="button"
onclick={this.handleCancel}
>
{this.props.i18n('cancel')}
</button>
</div>
</div>
</div>
)
}
}
module.exports = FileCard
| 1 | 13,285 | Questionable way of looping through editors and calling `canEditFile` to show the edit button. Is there a better way? | transloadit-uppy | js |
@@ -313,8 +313,14 @@ public class IntMultimap<T> implements Traversable<T>, Serializable {
@Override
public <U> Seq<Tuple2<T, U>> zip(Iterable<? extends U> that) {
+ return zipWith(that, Tuple::of);
+ }
+
+ @Override
+ public <U, R> Seq<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) {
Objects.requireNonNull(that, "that is null");
- return Stream.ofAll(iterator().zip(that));
+ Objects.requireNonNull(mapper, "mapper is null");
+ return Stream.ofAll(iterator().zipWith(that, mapper));
}
@Override | 1 | /* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.collection;
import javaslang.API;
import javaslang.Tuple;
import javaslang.Tuple2;
import javaslang.Tuple3;
import javaslang.control.Option;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
public class IntMultimap<T> implements Traversable<T>, Serializable {
private static final long serialVersionUID = 1L;
private final Multimap<Integer, T> original;
public static <T> IntMultimap<T> of(Multimap<Integer, T> original) {
return new IntMultimap<>(original);
}
private IntMultimap(Multimap<Integer, T> original) {
this.original = original;
}
@Override
public int hashCode() {
return original.values().hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof IntMultimap) {
final IntMultimap<?> that = (IntMultimap<?>) o;
return original.equals(that.original) || original.values().equals(that.original.values());
} else if (o instanceof Iterable) {
final Iterable<?> that = (Iterable<?>) o;
return original.values().equals(that);
} else {
return false;
}
}
@Override
public String stringPrefix() {
return "IntMap";
}
@Override
public String toString() {
return original.mkString(stringPrefix() + "(", ", ", ")");
}
@Override
public IntMultimap<T> distinct() {
return IntMultimap.of(original.distinct());
}
@Override
public IntMultimap<T> distinctBy(Comparator<? super T> comparator) {
return IntMultimap.of(original.distinctBy((o1, o2) -> comparator.compare(o1._2, o2._2)));
}
@Override
public <U> IntMultimap<T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
return IntMultimap.of(original.distinctBy(f -> keyExtractor.apply(f._2)));
}
@Override
public IntMultimap<T> drop(long n) {
final Multimap<Integer, T> dropped = original.drop(n);
return dropped == original ? this : IntMultimap.of(dropped);
}
@Override
public IntMultimap<T> dropRight(long n) {
final Multimap<Integer, T> dropped = original.dropRight(n);
return dropped == original ? this : IntMultimap.of(dropped);
}
@Override
public IntMultimap<T> dropUntil(Predicate<? super T> predicate) {
return IntMultimap.of(original.dropUntil(p -> predicate.test(p._2)));
}
@Override
public IntMultimap<T> dropWhile(Predicate<? super T> predicate) {
return IntMultimap.of(original.dropWhile(p -> predicate.test(p._2)));
}
@Override
public IntMultimap<T> filter(Predicate<? super T> predicate) {
return IntMultimap.of(original.filter(p -> predicate.test(p._2)));
}
@Override
public <U> Seq<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) {
return original.flatMap(e -> mapper.apply(e._2));
}
@Override
public <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return original.foldRight(zero, (e, u) -> f.apply(e._2, u));
}
@Override
public <C> Map<C, ? extends IntMultimap<T>> groupBy(Function<? super T, ? extends C> classifier) {
return original.groupBy(e -> classifier.apply(e._2)).map((k, v) -> Tuple.of(k, IntMultimap.of(v)));
}
@Override
public Iterator<IntMultimap<T>> grouped(long size) {
return original.grouped(size).map(IntMultimap::of);
}
@Override
public boolean hasDefiniteSize() {
return original.hasDefiniteSize();
}
@Override
public T head() {
return original.head()._2;
}
@Override
public Option<T> headOption() {
return original.headOption().map(o -> o._2);
}
@Override
public IntMultimap<T> init() {
return IntMultimap.of(original.init());
}
@Override
public Option<? extends IntMultimap<T>> initOption() {
return original.initOption().map(IntMultimap::of);
}
@Override
public boolean isEmpty() {
return original.isEmpty();
}
@Override
public boolean isTraversableAgain() {
return original.isTraversableAgain();
}
@Override
public int length() {
return original.length();
}
@Override
public <U> Seq<U> map(Function<? super T, ? extends U> mapper) {
return original.map(e -> mapper.apply(e._2));
}
@Override
public Tuple2<IntMultimap<T>, IntMultimap<T>> partition(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return original.partition(p -> predicate.test(p._2)).map(IntMultimap::of, IntMultimap::of);
}
@Override
public IntMultimap<T> peek(Consumer<? super T> action) {
return IntMultimap.of(original.peek(e -> action.accept(e._2)));
}
@Override
public IntMultimap<T> replace(T currentElement, T newElement) {
final Option<Tuple2<Integer, T>> currentEntryOpt = original.find(e -> e._2.equals(currentElement));
if (currentEntryOpt.isDefined()) {
final Tuple2<Integer, T> currentEntry = currentEntryOpt.get();
return IntMultimap.of(original.replace(currentEntry, Tuple.of(original.size() + 1, newElement)));
} else {
return this;
}
}
@Override
public IntMultimap<T> replaceAll(T currentElement, T newElement) {
Multimap<Integer, T> result = original;
for (Tuple2<Integer, T> entry : original.filter(e -> e._2.equals(currentElement))) {
result = result.replaceAll(entry, Tuple.of(entry._1, newElement));
}
return IntMultimap.of(result);
}
@Override
public IntMultimap<T> retainAll(Iterable<? extends T> elements) {
final Set<T> elementsSet = HashSet.ofAll(elements);
return IntMultimap.of(original.retainAll(original.filter(e -> elementsSet.contains(e._2))));
}
@Override
public Traversable<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) {
final int[] index = new int[] { 0 };
return original.scan(Tuple.of(-1, zero), (i, t) -> Tuple.of(index[0]++, operation.apply(i._2, t._2))).values();
}
@Override
public <U> Traversable<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) {
return original.scanLeft(zero, (i, t) -> operation.apply(i, t._2));
}
@Override
public <U> Traversable<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) {
return original.scanRight(zero, (t, i) -> operation.apply(t._2, i));
}
@Override
public Iterator<IntMultimap<T>> sliding(long size) {
return original.sliding(size).map(IntMultimap::of);
}
@Override
public Iterator<IntMultimap<T>> sliding(long size, long step) {
return original.sliding(size, step).map(IntMultimap::of);
}
@Override
public Tuple2<? extends IntMultimap<T>, ? extends IntMultimap<T>> span(Predicate<? super T> predicate) {
return original.span(p -> predicate.test(p._2)).map(IntMultimap::of, IntMultimap::of);
}
public Spliterator<T> spliterator() {
class SpliteratorProxy implements Spliterator<T> {
private final Spliterator<Tuple2<Integer, T>> spliterator;
SpliteratorProxy(Spliterator<Tuple2<Integer, T>> spliterator) {
this.spliterator = spliterator;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
return spliterator.tryAdvance(a -> action.accept(a._2));
}
@Override
public Spliterator<T> trySplit() {
return new SpliteratorProxy(spliterator.trySplit());
}
@Override
public long estimateSize() {
return spliterator.estimateSize();
}
@Override
public int characteristics() {
return spliterator.characteristics();
}
}
return new SpliteratorProxy(original.spliterator());
}
@Override
public IntMultimap<T> tail() {
return IntMultimap.of(original.tail());
}
@Override
public Option<IntMultimap<T>> tailOption() {
return original.tailOption().map(IntMultimap::of);
}
@Override
public IntMultimap<T> take(long n) {
return IntMultimap.of(original.take(n));
}
@Override
public IntMultimap<T> takeRight(long n) {
return IntMultimap.of(original.takeRight(n));
}
@Override
public Traversable<T> takeUntil(Predicate<? super T> predicate) {
return IntMultimap.of(original.takeUntil(p -> predicate.test(p._2)));
}
@Override
public IntMultimap<T> takeWhile(Predicate<? super T> predicate) {
return IntMultimap.of(original.takeWhile(p -> predicate.test(p._2)));
}
@Override
public <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return iterator().unzip(unzipper).map(Stream::ofAll, Stream::ofAll);
}
@Override
public <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return iterator().unzip3(unzipper).map(Stream::ofAll, Stream::ofAll, Stream::ofAll);
}
@Override
public <U> Seq<Tuple2<T, U>> zip(Iterable<? extends U> that) {
Objects.requireNonNull(that, "that is null");
return Stream.ofAll(iterator().zip(that));
}
@Override
public <U> Seq<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) {
Objects.requireNonNull(that, "that is null");
return Stream.ofAll(iterator().zipAll(that, thisElem, thatElem));
}
@Override
public Seq<Tuple2<T, Long>> zipWithIndex() {
return Stream.ofAll(iterator().zipWithIndex());
}
}
| 1 | 8,872 | `that is null` doesn't sound very useful to me. Could we rename `that` to `target` or something less context dependent :)? | vavr-io-vavr | java |
@@ -436,6 +436,7 @@ class Status(AbstractCommand):
print(x)
print
self.molecule._print_valid_platforms()
+ print
self.molecule._print_valid_providers()
| 1 | # Copyright (c) 2015 Cisco Systems
#
# 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.
import os
import pexpect
import re
import signal
import sys
from subprocess import CalledProcessError
import prettytable
import sh
import yaml
from colorama import Fore
from docopt import docopt
from jinja2 import Environment
from jinja2 import PackageLoader
import molecule.utilities as utilities
import molecule.validators as validators
from molecule.ansible_galaxy_install import AnsibleGalaxyInstall
from molecule.ansible_playbook import AnsiblePlaybook
from molecule.core import Molecule
class InvalidHost(Exception):
pass
class AbstractCommand:
def __init__(self, command_args, global_args, molecule=False):
"""
Initialize commands
:param command_args: arguments of the command
:param global_args: arguments from the CLI
:param molecule: molecule instance
"""
self.args = docopt(self.__doc__, argv=command_args)
self.args['<command>'] = self.__class__.__name__.lower()
self.command_args = command_args
self.static = False
# give us the option to reuse an existing molecule instance
if not molecule:
self.molecule = Molecule(self.args)
self.molecule.main()
else:
self.molecule = molecule
# init doesn't need to load molecule files
if self.__class__.__name__ == 'Init':
return
# assume static inventory if no vagrant config block is defined
if self.molecule._provisioner is None:
self.static = True
# assume static inventory if no instances are defined in vagrant config block
if self.molecule._provisioner.instances is None:
self.static = True
def disabled(self, cmd):
"""
Prints 'command disabled' message and exits program.
:param cmd: Name of the disabled command to print.
:return: None
"""
fmt = [Fore.RED, cmd, Fore.RESET]
errmsg = "{}The `{}` command isn't supported with static inventory.{}"
print(errmsg.format(*fmt))
sys.exit(1)
def execute(self):
raise NotImplementedError
class Create(AbstractCommand):
"""
Creates all instances defined in molecule.yml.
Usage:
create [--platform=<platform>] [--provider=<provider>] [--debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--debug get more detail
"""
def execute(self):
if self.static:
self.disabled('create')
self.molecule._create_templates()
try:
self.molecule._provisioner.up(no_provision=True)
self.molecule._state['created'] = True
self.molecule._write_state_file()
except CalledProcessError as e:
print('ERROR: {}'.format(e))
sys.exit(e.returncode)
class Destroy(AbstractCommand):
"""
Destroys all instances created by molecule.
Usage:
destroy [--platform=<platform>] [--provider=<provider>] [--debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--debug get more detail
"""
def execute(self):
"""
Removes template files.
Clears state file of all info (default platform).
:return: None
"""
if self.static:
self.disabled('destroy')
self.molecule._create_templates()
try:
self.molecule._provisioner.destroy()
self.molecule._state['default_platform'] = False
self.molecule._state['default_provider'] = False
self.molecule._state['created'] = False
self.molecule._state['converged'] = False
self.molecule._write_state_file()
except CalledProcessError as e:
print('ERROR: {}'.format(e))
sys.exit(e.returncode)
self.molecule._remove_templates()
class Converge(AbstractCommand):
"""
Provisions all instances defined in molecule.yml.
Usage:
converge [--platform=<platform>] [--provider=<provider>] [--tags=<tag1,tag2>...] [--debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--tags=<tag1,tag2> comma separated list of ansible tags to target
--debug get more detail
"""
def execute(self, idempotent=False, create_instances=True, create_inventory=True):
"""
:param idempotent: Optionally provision servers quietly so output can be parsed for idempotence
:param create_inventory: Toggle inventory creation
:param create_instances: Toggle instance creation
:return: Provisioning output
"""
if self.molecule._state.get('created'):
create_instances = False
if self.molecule._state.get('converged'):
create_inventory = False
if self.static:
create_instances = False
create_inventory = False
if create_instances and not idempotent:
c = Create(self.command_args, self.args, self.molecule)
c.execute()
if create_inventory:
self.molecule._create_inventory_file()
# install role dependencies only during `molecule converge`
if not idempotent and 'requirements_file' in self.molecule._config.config['ansible']:
print('{}Installing role dependencies ...{}'.format(Fore.CYAN, Fore.RESET))
galaxy_install = AnsibleGalaxyInstall(self.molecule._config.config['ansible']['requirements_file'])
galaxy_install.add_env_arg('ANSIBLE_CONFIG', self.molecule._config.config['ansible']['config_file'])
galaxy_install.bake()
output = galaxy_install.execute()
ansible = AnsiblePlaybook(self.molecule._config.config['ansible'])
# target tags passed in via CLI
if self.molecule._args.get('--tags'):
ansible.add_cli_arg('tags', self.molecule._args['--tags'].pop(0))
if idempotent:
ansible.remove_cli_arg('_out')
ansible.remove_cli_arg('_err')
ansible.add_env_arg('ANSIBLE_NOCOLOR', 'true')
ansible.add_env_arg('ANSIBLE_FORCE_COLOR', 'false')
# Save the previous callback plugin if any.
callback_plugin = ansible.env.get('ANSIBLE_CALLBACK_PLUGINS', '')
# Set the idempotence plugin.
if callback_plugin:
ansible.add_env_arg('ANSIBLE_CALLBACK_PLUGINS', callback_plugin + ':' + os.path.join(
sys.prefix, 'share/molecule/ansible/plugins/callback/idempotence'))
else:
ansible.add_env_arg('ANSIBLE_CALLBACK_PLUGINS',
os.path.join(sys.prefix, 'share/molecule/ansible/plugins/callback/idempotence'))
ansible.bake()
if self.molecule._args.get('--debug'):
ansible_env = {k: v for (k, v) in ansible.env.items() if 'ANSIBLE' in k}
other_env = {k: v for (k, v) in ansible.env.items() if 'ANSIBLE' not in k}
utilities.debug('OTHER ENVIRONMENT', yaml.dump(other_env, default_flow_style=False, indent=2))
utilities.debug('ANSIBLE ENVIRONMENT', yaml.dump(ansible_env, default_flow_style=False, indent=2))
utilities.debug('ANSIBLE PLAYBOOK', str(ansible.ansible))
output = ansible.execute()
if not self.molecule._state.get('converged'):
self.molecule._state['converged'] = True
self.molecule._write_state_file()
return output
class Idempotence(AbstractCommand):
"""
Provisions instances and parses output to determine idempotence.
Usage:
idempotence [--platform=<platform>] [--provider=<provider>] [--debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provide
--debug get more detail
"""
def execute(self):
if self.static:
self.disabled('idempotence')
print('{}Idempotence test in progress (can take a few minutes)...{}'.format(Fore.MAGENTA, Fore.RESET))
c = Converge(self.command_args, self.args, self.molecule)
output = c.execute(idempotent=True)
idempotent, changed_tasks = self.molecule._parse_provisioning_output(output)
if idempotent:
print('{}Idempotence test passed.{}'.format(Fore.GREEN, Fore.RESET))
print
return
# Display the details of the idempotence test.
if changed_tasks:
print('{}Idempotence test failed because of the following tasks:{}'.format(Fore.RED, Fore.RESET))
print('{}{}{}'.format(Fore.RED, '\n'.join(changed_tasks), Fore.RESET))
else:
# But in case the idempotence callback plugin was not found, we just display an error message.
print('{}Idempotence test failed.{}'.format(Fore.RED, Fore.RESET))
warning_msg = "The idempotence plugin was not found or did not provide the required information. " \
"Therefore the failure details cannot be displayed."
print('{}{}{}'.format(Fore.YELLOW, warning_msg, Fore.RESET))
sys.exit(1)
class Verify(AbstractCommand):
"""
Performs verification steps on running instances.
Usage:
verify [--platform=<platform>] [--provider=<provider>] [--debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--debug get more detail
"""
def execute(self):
if self.static:
self.disabled('verify')
serverspec_dir = self.molecule._config.config['molecule']['serverspec_dir']
testinfra_dir = self.molecule._config.config['molecule']['testinfra_dir']
inventory_file = self.molecule._config.config['ansible']['inventory_file']
rakefile = self.molecule._config.config['molecule']['rakefile_file']
ignore_paths = self.molecule._config.config['molecule']['ignore_paths']
# whitespace & trailing newline check
validators.check_trailing_cruft(ignore_paths=ignore_paths)
# no serverspec or testinfra
if not os.path.isdir(serverspec_dir) and not os.path.isdir(testinfra_dir):
msg = '{}Skipping tests, could not find {}/ or {}/.{}'
print(msg.format(Fore.YELLOW, serverspec_dir, testinfra_dir, Fore.RESET))
return
self.molecule._write_ssh_config()
kwargs = {'env': self.molecule._env}
kwargs['env']['PYTHONDONTWRITEBYTECODE'] = '1'
kwargs['debug'] = True if self.molecule._args.get('--debug') else False
try:
# testinfra
if os.path.isdir(testinfra_dir):
msg = '\n{}Executing testinfra tests found in {}/.{}'
print(msg.format(Fore.MAGENTA, serverspec_dir, Fore.RESET))
validators.testinfra(inventory_file, **kwargs)
print
else:
msg = '{}No testinfra tests found in {}/.\n{}'
print(msg.format(Fore.YELLOW, testinfra_dir, Fore.RESET))
# serverspec / rubocop
if os.path.isdir(serverspec_dir):
msg = '{}Executing rubocop on *.rb files found in {}/.{}'
print(msg.format(Fore.MAGENTA, serverspec_dir, Fore.RESET))
validators.rubocop(serverspec_dir, **kwargs)
print
msg = '{}Executing serverspec tests found in {}/.{}'
print(msg.format(Fore.MAGENTA, serverspec_dir, Fore.RESET))
validators.rake(rakefile, **kwargs)
print
else:
msg = '{}No serverspec tests found in {}/.\n{}'
print(msg.format(Fore.YELLOW, serverspec_dir, Fore.RESET))
except sh.ErrorReturnCode as e:
print('ERROR: {}'.format(e))
sys.exit(e.exit_code)
class Test(AbstractCommand):
"""
Runs a series of commands (defined in config) against instances for a full test/verify run.
Usage:
test [--platform=<platform>] [--provider=<provider>] [--debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--debug get more detail
"""
def execute(self):
if self.static:
self.disabled('test')
for task in self.molecule._config.config['molecule']['test']['sequence']:
command = getattr(sys.modules[__name__], task.capitalize())
c = command(self.command_args, self.args)
c.execute()
class List(AbstractCommand):
"""
Prints a list of currently available platforms
Usage:
list [--debug] [-m]
Options:
--debug get more detail
-m machine readable output
"""
def execute(self):
if self.static:
self.disabled('list')
is_machine_readable = self.molecule._args['-m']
self.molecule._print_valid_platforms(machine_readable=is_machine_readable)
class Status(AbstractCommand):
"""
Prints status of configured instances.
Usage:
status [--debug]
Options:
--debug get more detail
"""
def execute(self):
if self.static:
self.disabled('status')
if not self.molecule._state.get('created'):
errmsg = '{}ERROR: No instances created. Try `{} create` first.{}'
print(errmsg.format(Fore.RED, os.path.basename(sys.argv[0]), Fore.RESET))
sys.exit(1)
try:
status = self.molecule._provisioner.status()
except CalledProcessError as e:
print('ERROR: {}'.format(e))
return e.returncode
x = prettytable.PrettyTable(['Name', 'State', 'Provider'])
x.align = 'l'
for item in status:
if item.state != 'not_created':
state = Fore.GREEN + item.state + Fore.RESET
else:
state = item.state
x.add_row([item.name, state, item.provider])
print(x)
print
self.molecule._print_valid_platforms()
self.molecule._print_valid_providers()
class Login(AbstractCommand):
"""
Initiates an interactive ssh session with the given host.
Usage:
login [<host>]
"""
def execute(self):
if self.static:
self.disabled('login')
# make sure vagrant knows about this host
try:
# Check whether a host was specified.
if self.molecule._args['<host>'] is None:
# If not, collect the list of running hosts.
try:
status = self.molecule._provisioner.status()
except Exception as e:
status = []
# Nowhere to log into if there is no running host.
if len(status) == 0:
raise InvalidHost("There is no running host.")
# One running host is perfect. Log into it.
elif len(status) == 1:
hostname = status[0].name
# But too many hosts is trouble as well.
else:
raise InvalidHost("There are {} running hosts. You can only log into one at a time.".format(len(
status)))
else:
# If the host was specified, try to use it.
hostname = self.molecule._args['<host>']
# Try to retrieve the SSH configuration of the host.
conf = self.molecule._provisioner.conf(vm_name=hostname)
# Prepare the command to SSH into the host.
ssh_args = [conf['HostName'], conf['User'], conf['Port'], conf['IdentityFile'],
' '.join(self.molecule._config.config['molecule']['raw_ssh_args'])]
ssh_cmd = 'ssh {} -l {} -p {} -i {} {}'
except CalledProcessError:
# gets appended to python-vagrant's error message
conf_format = [Fore.RED, self.molecule._args['<host>'], Fore.YELLOW, Fore.RESET]
conf_errmsg = '\n{0}Unknown host {1}. Try {2}molecule status{0} to see available hosts.{3}'
print(conf_errmsg.format(*conf_format))
sys.exit(1)
except InvalidHost as e:
conf_format = [Fore.RED, e.message, Fore.RESET]
conf_errmsg = '{}{}{}'
print(conf_errmsg.format(*conf_format))
sys.exit(1)
lines, columns = os.popen('stty size', 'r').read().split()
dimensions = (int(lines), int(columns))
self.molecule._pt = pexpect.spawn('/usr/bin/env ' + ssh_cmd.format(*ssh_args), dimensions=dimensions)
signal.signal(signal.SIGWINCH, self.molecule._sigwinch_passthrough)
self.molecule._pt.interact()
class Init(AbstractCommand):
"""
Creates the scaffolding for a new role intended for use with molecule.
Usage:
init <role>
"""
def execute(self):
role = self.molecule._args['<role>']
role_path = os.path.join(os.curdir, role)
if not role:
msg = '{}The init command requires a role name. Try:\n\n{}{} init <role>{}'
print(msg.format(Fore.RED, Fore.YELLOW, os.path.basename(sys.argv[0]), Fore.RESET))
sys.exit(1)
if os.path.isdir(role):
msg = '{}The directory {} already exists. Cannot create new role.{}'
print(msg.format(Fore.RED, role_path, Fore.RESET))
sys.exit(1)
try:
sh.ansible_galaxy('init', role)
except (CalledProcessError, sh.ErrorReturnCode_1) as e:
print('ERROR: {}'.format(e))
sys.exit(e.returncode)
env = Environment(loader=PackageLoader('molecule', 'templates'), keep_trailing_newline=True)
t_molecule = env.get_template(self.molecule._config.config['molecule']['init']['templates']['molecule'])
t_playbook = env.get_template(self.molecule._config.config['molecule']['init']['templates']['playbook'])
t_default_spec = env.get_template(self.molecule._config.config['molecule']['init']['templates']['default_spec'])
t_spec_helper = env.get_template(self.molecule._config.config['molecule']['init']['templates']['spec_helper'])
sanitized_role = re.sub('[._]', '-', role)
with open(os.path.join(role_path, self.molecule._config.config['molecule']['molecule_file']), 'w') as f:
f.write(t_molecule.render(config=self.molecule._config.config, role=sanitized_role))
with open(os.path.join(role_path, self.molecule._config.config['ansible']['playbook']), 'w') as f:
f.write(t_playbook.render(role=role))
serverspec_path = os.path.join(role_path, self.molecule._config.config['molecule']['serverspec_dir'])
os.makedirs(serverspec_path)
os.makedirs(os.path.join(serverspec_path, 'hosts'))
os.makedirs(os.path.join(serverspec_path, 'groups'))
with open(os.path.join(serverspec_path, 'default_spec.rb'), 'w') as f:
f.write(t_default_spec.render())
with open(os.path.join(serverspec_path, 'spec_helper.rb'), 'w') as f:
f.write(t_spec_helper.render())
msg = '{}Successfully initialized new role in {}{}'
print(msg.format(Fore.GREEN, role_path, Fore.RESET))
sys.exit(0)
| 1 | 5,949 | Just to be consistent, can we use the print function `print()` instead of the keyword. Same goes for line 437. | ansible-community-molecule | py |
@@ -27,11 +27,17 @@ func SetupGenesisNode(ctx context.Context, node *fat.Filecoin, gcURI string, min
return err
}
- if _, err := node.WalletImport(ctx, minerOwner); err != nil {
+ wallet, err := node.WalletImport(ctx, minerOwner)
+ if err != nil {
return err
}
- if _, err := node.MinerUpdatePeerid(ctx, minerAddress, node.PeerID, fat.AOPrice(big.NewFloat(300)), fat.AOLimit(300)); err != nil {
+ if err := node.ConfigSet(ctx, "wallet.defaultAddress", wallet[0].String()); err != nil {
+ return err
+ }
+
+ _, err = node.MinerUpdatePeerid(ctx, minerAddress, node.PeerID, fat.AOFromAddr(wallet[0]), fat.AOPrice(big.NewFloat(300)), fat.AOLimit(300))
+ if err != nil {
return err
}
| 1 | package series
import (
"context"
"math/big"
"gx/ipfs/QmXWZCd8jfaHmt4UDSnjKmGcrQMw95bDGWqEeVLVJjoANX/go-ipfs-files"
"github.com/filecoin-project/go-filecoin/address"
"github.com/filecoin-project/go-filecoin/tools/fat"
)
// SetupGenesisNode will initialize, start, configure, and issue the "start mining" command to the filecoin process `node`.
// Process `node` will use the genesisfile at `gcURI`, be configured with miner `minerAddress`, and import the address of the
// miner `minerOwner`. Lastly the process `node` will start mining.
func SetupGenesisNode(ctx context.Context, node *fat.Filecoin, gcURI string, minerAddress address.Address, minerOwner files.File) error {
if _, err := node.InitDaemon(ctx, "--genesisfile", gcURI); err != nil {
return err
}
if _, err := node.StartDaemon(ctx, true); err != nil {
return err
}
if err := node.ConfigSet(ctx, "mining.minerAddress", minerAddress.String()); err != nil {
return err
}
if _, err := node.WalletImport(ctx, minerOwner); err != nil {
return err
}
if _, err := node.MinerUpdatePeerid(ctx, minerAddress, node.PeerID, fat.AOPrice(big.NewFloat(300)), fat.AOLimit(300)); err != nil {
return err
}
return node.MiningStart(ctx)
}
| 1 | 16,531 | Having to pass in `price` and `limit` is pretty common. Do we want to have this be another argument, maybe a combined structure that can be used for every action that requires it? | filecoin-project-venus | go |
@@ -30,9 +30,17 @@ export class ComicsPlayer {
return this.setCurrentSrc(elem, options);
}
+ destroy() {
+ // Nothing to do here
+ }
+
stop() {
this.unbindEvents();
+ const stopInfo = {
+ src: this.item
+ };
+ Events.trigger(this, 'stopped', [stopInfo]);
this.archiveSource?.release();
const elem = this.mediaElement; | 1 | // eslint-disable-next-line import/named, import/namespace
import { Archive } from 'libarchive.js';
import loading from '../../components/loading/loading';
import dialogHelper from '../../components/dialogHelper/dialogHelper';
import keyboardnavigation from '../../scripts/keyboardNavigation';
import { appRouter } from '../../components/appRouter';
import ServerConnections from '../../components/ServerConnections';
// eslint-disable-next-line import/named, import/namespace
import { Swiper } from 'swiper/swiper-bundle.esm';
import 'swiper/swiper-bundle.css';
import './style.scss';
export class ComicsPlayer {
constructor() {
this.name = 'Comics Player';
this.type = 'mediaplayer';
this.id = 'comicsplayer';
this.priority = 1;
this.imageMap = new Map();
this.onDialogClosed = this.onDialogClosed.bind(this);
this.onWindowKeyUp = this.onWindowKeyUp.bind(this);
}
play(options) {
this.progress = 0;
const elem = this.createMediaElement();
return this.setCurrentSrc(elem, options);
}
stop() {
this.unbindEvents();
this.archiveSource?.release();
const elem = this.mediaElement;
if (elem) {
dialogHelper.close(elem);
this.mediaElement = null;
}
loading.hide();
}
onDialogClosed() {
this.stop();
}
onWindowKeyUp(e) {
const key = keyboardnavigation.getKeyName(e);
switch (key) {
case 'Escape':
this.stop();
break;
}
}
bindMediaElementEvents() {
const elem = this.mediaElement;
elem?.addEventListener('close', this.onDialogClosed, {once: true});
elem?.querySelector('.btnExit').addEventListener('click', this.onDialogClosed, {once: true});
}
bindEvents() {
this.bindMediaElementEvents();
document.addEventListener('keyup', this.onWindowKeyUp);
}
unbindMediaElementEvents() {
const elem = this.mediaElement;
elem?.removeEventListener('close', this.onDialogClosed);
elem?.querySelector('.btnExit').removeEventListener('click', this.onDialogClosed);
}
unbindEvents() {
this.unbindMediaElementEvents();
document.removeEventListener('keyup', this.onWindowKeyUp);
}
createMediaElement() {
let elem = this.mediaElement;
if (elem) {
return elem;
}
elem = document.getElementById('comicsPlayer');
if (!elem) {
elem = dialogHelper.createDialog({
exitAnimationDuration: 400,
size: 'fullscreen',
autoFocus: false,
scrollY: false,
exitAnimation: 'fadeout',
removeOnClose: true
});
elem.id = 'comicsPlayer';
elem.classList.add('slideshowDialog');
elem.innerHTML = `<div class="slideshowSwiperContainer"><div class="swiper-wrapper"></div></div>
<div class="actionButtons">
<button is="paper-icon-button-light" class="autoSize btnExit" tabindex="-1"><i class="material-icons actionButtonIcon close"></i></button>
</div>`;
dialogHelper.open(elem);
}
this.mediaElement = elem;
this.bindEvents();
return elem;
}
setCurrentSrc(elem, options) {
const item = options.items[0];
this.currentItem = item;
loading.show();
const serverId = item.ServerId;
const apiClient = ServerConnections.getApiClient(serverId);
Archive.init({
workerUrl: appRouter.baseUrl() + '/libraries/worker-bundle.js'
});
const downloadUrl = apiClient.getItemDownloadUrl(item.Id);
this.archiveSource = new ArchiveSource(downloadUrl);
return this.archiveSource.load().then(() => {
loading.hide();
this.swiperInstance = new Swiper(elem.querySelector('.slideshowSwiperContainer'), {
direction: 'horizontal',
// loop is disabled due to the lack of Swiper support in virtual slides
loop: false,
zoom: {
minRatio: 1,
toggle: true,
containerClass: 'slider-zoom-container'
},
autoplay: false,
keyboard: {
enabled: true
},
preloadImages: true,
slidesPerView: 1,
slidesPerColumn: 1,
initialSlide: 0,
// reduces memory consumption for large libraries while allowing preloading of images
virtual: {
slides: this.archiveSource.urls,
cache: true,
renderSlide: this.getImgFromUrl,
addSlidesBefore: 1,
addSlidesAfter: 1
}
});
});
}
getImgFromUrl(url) {
return `<div class="swiper-slide">
<div class="slider-zoom-container">
<img src="${url}" class="swiper-slide-img">
</div>
</div>`;
}
canPlayMediaType(mediaType) {
return (mediaType || '').toLowerCase() === 'book';
}
canPlayItem(item) {
if (item.Path && (item.Path.endsWith('cbz') || item.Path.endsWith('cbr'))) {
return true;
}
return false;
}
}
class ArchiveSource {
constructor(url) {
this.url = url;
this.files = [];
this.urls = [];
}
async load() {
const res = await fetch(this.url);
if (!res.ok) {
return;
}
const blob = await res.blob();
this.archive = await Archive.open(blob);
this.raw = await this.archive.getFilesArray();
await this.archive.extractFiles();
const files = await this.archive.getFilesArray();
files.sort((a, b) => {
if (a.file.name < b.file.name) {
return -1;
} else {
return 1;
}
});
for (const file of files) {
/* eslint-disable-next-line compat/compat */
const url = URL.createObjectURL(file.file);
this.urls.push(url);
}
}
release() {
this.files = [];
/* eslint-disable-next-line compat/compat */
this.urls.forEach(URL.revokeObjectURL);
this.urls = [];
}
}
export default ComicsPlayer;
| 1 | 19,743 | Could you move it after `stop`? | jellyfin-jellyfin-web | js |
@@ -49,10 +49,10 @@ public final class ClassUtils {
// 将一系列body parameter包装成一个class
public static Class<?> getOrCreateBodyClass(OperationGenerator operationGenerator,
- List<BodyParameter> bodyParameters) {
+ List<BodyParameter> bodyParameters, String bodyParamName) {
SwaggerGenerator swaggerGenerator = operationGenerator.getSwaggerGenerator();
Method method = operationGenerator.getProviderMethod();
- String clsName = swaggerGenerator.ensureGetPackageName() + "." + method.getName() + "Body";
+ String clsName = swaggerGenerator.ensureGetPackageName() + "." + bodyParamName;
Class<?> cls = getClassByName(swaggerGenerator.getClassLoader(), clsName);
if (cls != null) {
return cls; | 1 | /*
* 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.
*/
package org.apache.servicecomb.swagger.generator.core.utils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import javax.lang.model.SourceVersion;
import org.apache.servicecomb.common.javassist.ClassConfig;
import org.apache.servicecomb.common.javassist.JavassistUtils;
import org.apache.servicecomb.foundation.common.utils.ReflectUtils;
import org.apache.servicecomb.swagger.converter.ConverterMgr;
import org.apache.servicecomb.swagger.converter.SwaggerToClassGenerator;
import org.apache.servicecomb.swagger.generator.core.OperationGenerator;
import org.apache.servicecomb.swagger.generator.core.SwaggerConst;
import org.apache.servicecomb.swagger.generator.core.SwaggerGenerator;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.JavaType;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
public final class ClassUtils {
private ClassUtils() {
}
public static Class<?> getClassByName(ClassLoader classLoader, String clsName) {
return ReflectUtils.getClassByName(classLoader, clsName);
}
// 将一系列body parameter包装成一个class
public static Class<?> getOrCreateBodyClass(OperationGenerator operationGenerator,
List<BodyParameter> bodyParameters) {
SwaggerGenerator swaggerGenerator = operationGenerator.getSwaggerGenerator();
Method method = operationGenerator.getProviderMethod();
String clsName = swaggerGenerator.ensureGetPackageName() + "." + method.getName() + "Body";
Class<?> cls = getClassByName(swaggerGenerator.getClassLoader(), clsName);
if (cls != null) {
return cls;
}
ClassConfig classConfig = new ClassConfig();
classConfig.setClassName(clsName);
// 1.全是预备body
// 2.预备body与明确body混合
SwaggerToClassGenerator classGenerator = new SwaggerToClassGenerator(swaggerGenerator.getClassLoader(),
swaggerGenerator.getSwagger(), swaggerGenerator.ensureGetPackageName());
for (BodyParameter bp : bodyParameters) {
JavaType javaType = ConverterMgr.findJavaType(classGenerator, bp);
classConfig.addField(bp.getName(), javaType);
}
return JavassistUtils.createClass(swaggerGenerator.getClassLoader(), classConfig);
}
public static boolean hasAnnotation(Class<?> cls, Class<? extends Annotation> annotation) {
if (cls.getAnnotation(annotation) != null) {
return true;
}
for (Method method : cls.getMethods()) {
if (method.getAnnotation(annotation) != null) {
return true;
}
}
return false;
}
public static boolean isRawJsonType(Parameter param) {
Object rawJson = param.getVendorExtensions().get(SwaggerConst.EXT_RAW_JSON_TYPE);
if (Boolean.class.isInstance(rawJson)) {
return (boolean) rawJson;
}
return false;
}
public static String getClassName(Map<String, Object> vendorExtensions) {
return getVendorExtension(vendorExtensions, SwaggerConst.EXT_JAVA_CLASS);
}
public static String getInterfaceName(Map<String, Object> vendorExtensions) {
return getVendorExtension(vendorExtensions, SwaggerConst.EXT_JAVA_INTF);
}
public static String getRawClassName(String canonical) {
if (StringUtils.isEmpty(canonical)) {
return null;
}
int idx = canonical.indexOf("<");
if (idx == 0) {
throw new IllegalStateException("Invalid class canonical: " + canonical);
}
if (idx < 0) {
return canonical;
}
return canonical.substring(0, idx);
}
@SuppressWarnings("unchecked")
public static <T> T getVendorExtension(Map<String, Object> vendorExtensions, String key) {
if (vendorExtensions == null) {
return null;
}
return (T) vendorExtensions.get(key);
}
public static String correctMethodParameterName(String paramName) {
if (SourceVersion.isName(paramName)) {
return paramName;
}
StringBuilder newParam = new StringBuilder();
for (int index = 0; index < paramName.length(); index++) {
char tempChar = paramName.charAt(index);
if (Character.isJavaIdentifierPart(tempChar)) {
newParam.append(paramName.charAt(index));
continue;
}
if (tempChar == '.' || tempChar == '-') {
newParam.append('_');
}
}
return newParam.toString();
}
public static String correctClassName(String name) {
if (SourceVersion.isIdentifier(name) && !SourceVersion.isKeyword(name)) {
return name;
}
String parts[] = name.split("\\.", -1);
for (int idx = 0; idx < parts.length; idx++) {
String part = parts[idx];
if (part.isEmpty()) {
parts[idx] = "_";
continue;
}
part = part.replaceAll("[,;<>-]", "_").replace("[", "array_");
if (Character.isDigit(part.charAt(0)) || SourceVersion.isKeyword(part)) {
part = "_" + part;
}
parts[idx] = part;
}
return String.join(".", parts);
}
}
| 1 | 11,344 | The variable `method` seems not used. Maybe we can remove the parameter `bodyParamName` and generate it by invoking `ParamUtils.generateBodyParameterName(method)` ? | apache-servicecomb-java-chassis | java |
@@ -57,7 +57,6 @@ import static org.apache.solr.cloud.OverseerCollectionMessageHandler.NUM_SLICES;
import static org.apache.solr.common.cloud.ZkStateReader.MAX_SHARDS_PER_NODE;
import static org.apache.solr.common.cloud.ZkStateReader.REPLICATION_FACTOR;
-@Slow
public class ShardSplitTest extends BasicDistributedZkTest {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); | 1 | /*
* 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.
*/
package org.apache.solr.cloud;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.CollectionAdminResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.CompositeIdRouter;
import org.apache.solr.common.cloud.DocRouter;
import org.apache.solr.common.cloud.HashBasedRouter;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CollectionParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.Utils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.solr.cloud.OverseerCollectionMessageHandler.NUM_SLICES;
import static org.apache.solr.common.cloud.ZkStateReader.MAX_SHARDS_PER_NODE;
import static org.apache.solr.common.cloud.ZkStateReader.REPLICATION_FACTOR;
@Slow
public class ShardSplitTest extends BasicDistributedZkTest {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public static final String SHARD1_0 = SHARD1 + "_0";
public static final String SHARD1_1 = SHARD1 + "_1";
public ShardSplitTest() {
schemaString = "schema15.xml"; // we need a string id
}
@Test
public void test() throws Exception {
waitForThingsToLevelOut(15);
if (usually()) {
log.info("Using legacyCloud=false for cluster");
CollectionsAPIDistributedZkTest.setClusterProp(cloudClient, "legacyCloud", "false");
}
incompleteOrOverlappingCustomRangeTest();
splitByUniqueKeyTest();
splitByRouteFieldTest();
splitByRouteKeyTest();
// todo can't call waitForThingsToLevelOut because it looks for jettys of all shards
// and the new sub-shards don't have any.
waitForRecoveriesToFinish(true);
//waitForThingsToLevelOut(15);
}
@Test
public void testSplitShardWithRule() throws Exception {
waitForThingsToLevelOut(15);
if (usually()) {
log.info("Using legacyCloud=false for cluster");
CollectionsAPIDistributedZkTest.setClusterProp(cloudClient, "legacyCloud", "false");
}
log.info("Starting testSplitShardWithRule");
String collectionName = "shardSplitWithRule";
CollectionAdminRequest.Create createRequest = new CollectionAdminRequest.Create()
.setCollectionName(collectionName)
.setNumShards(1)
.setReplicationFactor(2)
.setRule("shard:*,replica:<2,node:*");
CollectionAdminResponse response = createRequest.process(cloudClient);
assertEquals(0, response.getStatus());
CollectionAdminRequest.SplitShard splitShardRequest = new CollectionAdminRequest.SplitShard()
.setCollectionName(collectionName)
.setShardName("shard1");
response = splitShardRequest.process(cloudClient);
assertEquals(String.valueOf(response.getErrorMessages()), 0, response.getStatus());
}
private void incompleteOrOverlappingCustomRangeTest() throws Exception {
ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();
final DocRouter router = clusterState.getCollection(AbstractDistribZkTestBase.DEFAULT_COLLECTION).getRouter();
Slice shard1 = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1);
DocRouter.Range shard1Range = shard1.getRange() != null ? shard1.getRange() : router.fullRange();
List<DocRouter.Range> subRanges = new ArrayList<>();
List<DocRouter.Range> ranges = router.partitionRange(4, shard1Range);
// test with only one range
subRanges.add(ranges.get(0));
try {
splitShard(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1, subRanges, null);
fail("Shard splitting with just one custom hash range should not succeed");
} catch (HttpSolrClient.RemoteSolrException e) {
log.info("Expected exception:", e);
}
subRanges.clear();
// test with ranges with a hole in between them
subRanges.add(ranges.get(3)); // order shouldn't matter
subRanges.add(ranges.get(0));
try {
splitShard(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1, subRanges, null);
fail("Shard splitting with missing hashes in between given ranges should not succeed");
} catch (HttpSolrClient.RemoteSolrException e) {
log.info("Expected exception:", e);
}
subRanges.clear();
// test with overlapping ranges
subRanges.add(ranges.get(0));
subRanges.add(ranges.get(1));
subRanges.add(ranges.get(2));
subRanges.add(new DocRouter.Range(ranges.get(3).min - 15, ranges.get(3).max));
try {
splitShard(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1, subRanges, null);
fail("Shard splitting with overlapping ranges should not succeed");
} catch (HttpSolrClient.RemoteSolrException e) {
log.info("Expected exception:", e);
}
subRanges.clear();
}
private void splitByUniqueKeyTest() throws Exception {
ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();
final DocRouter router = clusterState.getCollection(AbstractDistribZkTestBase.DEFAULT_COLLECTION).getRouter();
Slice shard1 = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1);
DocRouter.Range shard1Range = shard1.getRange() != null ? shard1.getRange() : router.fullRange();
List<DocRouter.Range> subRanges = new ArrayList<>();
if (usually()) {
List<DocRouter.Range> ranges = router.partitionRange(4, shard1Range);
// 75% of range goes to shard1_0 and the rest to shard1_1
subRanges.add(new DocRouter.Range(ranges.get(0).min, ranges.get(2).max));
subRanges.add(ranges.get(3));
} else {
subRanges = router.partitionRange(2, shard1Range);
}
final List<DocRouter.Range> ranges = subRanges;
final int[] docCounts = new int[ranges.size()];
int numReplicas = shard1.getReplicas().size();
del("*:*");
for (int id = 0; id <= 100; id++) {
String shardKey = "" + (char)('a' + (id % 26)); // See comment in ShardRoutingTest for hash distribution
indexAndUpdateCount(router, ranges, docCounts, shardKey + "!" + String.valueOf(id), id);
}
commit();
Thread indexThread = new Thread() {
@Override
public void run() {
Random random = random();
int max = atLeast(random, 401);
int sleep = atLeast(random, 25);
log.info("SHARDSPLITTEST: Going to add " + max + " number of docs at 1 doc per " + sleep + "ms");
Set<String> deleted = new HashSet<>();
for (int id = 101; id < max; id++) {
try {
indexAndUpdateCount(router, ranges, docCounts, String.valueOf(id), id);
Thread.sleep(sleep);
if (usually(random)) {
String delId = String.valueOf(random.nextInt(id - 101 + 1) + 101);
if (deleted.contains(delId)) continue;
try {
deleteAndUpdateCount(router, ranges, docCounts, delId);
deleted.add(delId);
} catch (Exception e) {
log.error("Exception while deleting docs", e);
}
}
} catch (Exception e) {
log.error("Exception while adding doc id = " + id, e);
// do not select this id for deletion ever
deleted.add(String.valueOf(id));
}
}
}
};
indexThread.start();
try {
for (int i = 0; i < 3; i++) {
try {
splitShard(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1, subRanges, null);
log.info("Layout after split: \n");
printLayout();
break;
} catch (HttpSolrClient.RemoteSolrException e) {
if (e.code() != 500) {
throw e;
}
log.error("SPLITSHARD failed. " + (i < 2 ? " Retring split" : ""), e);
if (i == 2) {
fail("SPLITSHARD was not successful even after three tries");
}
}
}
} finally {
try {
indexThread.join();
} catch (InterruptedException e) {
log.error("Indexing thread interrupted", e);
}
}
waitForRecoveriesToFinish(true);
checkDocCountsAndShardStates(docCounts, numReplicas);
}
public void splitByRouteFieldTest() throws Exception {
log.info("Starting testSplitWithRouteField");
String collectionName = "routeFieldColl";
int numShards = 4;
int replicationFactor = 2;
int maxShardsPerNode = (((numShards * replicationFactor) / getCommonCloudSolrClient()
.getZkStateReader().getClusterState().getLiveNodes().size())) + 1;
HashMap<String, List<Integer>> collectionInfos = new HashMap<>();
String shard_fld = "shard_s";
try (CloudSolrClient client = createCloudClient(null)) {
Map<String, Object> props = Utils.makeMap(
REPLICATION_FACTOR, replicationFactor,
MAX_SHARDS_PER_NODE, maxShardsPerNode,
NUM_SLICES, numShards,
"router.field", shard_fld);
createCollection(collectionInfos, collectionName,props,client);
}
List<Integer> list = collectionInfos.get(collectionName);
checkForCollection(collectionName, list, null);
waitForRecoveriesToFinish(false);
String url = getUrlFromZk(getCommonCloudSolrClient().getZkStateReader().getClusterState(), collectionName);
try (HttpSolrClient collectionClient = getHttpSolrClient(url)) {
ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();
final DocRouter router = clusterState.getCollection(collectionName).getRouter();
Slice shard1 = clusterState.getSlice(collectionName, SHARD1);
DocRouter.Range shard1Range = shard1.getRange() != null ? shard1.getRange() : router.fullRange();
final List<DocRouter.Range> ranges = router.partitionRange(2, shard1Range);
final int[] docCounts = new int[ranges.size()];
for (int i = 100; i <= 200; i++) {
String shardKey = "" + (char) ('a' + (i % 26)); // See comment in ShardRoutingTest for hash distribution
collectionClient.add(getDoc(id, i, "n_ti", i, shard_fld, shardKey));
int idx = getHashRangeIdx(router, ranges, shardKey);
if (idx != -1) {
docCounts[idx]++;
}
}
for (int i = 0; i < docCounts.length; i++) {
int docCount = docCounts[i];
log.info("Shard {} docCount = {}", "shard1_" + i, docCount);
}
collectionClient.commit();
for (int i = 0; i < 3; i++) {
try {
splitShard(collectionName, SHARD1, null, null);
break;
} catch (HttpSolrClient.RemoteSolrException e) {
if (e.code() != 500) {
throw e;
}
log.error("SPLITSHARD failed. " + (i < 2 ? " Retring split" : ""), e);
if (i == 2) {
fail("SPLITSHARD was not successful even after three tries");
}
}
}
waitForRecoveriesToFinish(collectionName, false);
assertEquals(docCounts[0], collectionClient.query(new SolrQuery("*:*").setParam("shards", "shard1_0")).getResults().getNumFound());
assertEquals(docCounts[1], collectionClient.query(new SolrQuery("*:*").setParam("shards", "shard1_1")).getResults().getNumFound());
}
}
private void splitByRouteKeyTest() throws Exception {
log.info("Starting splitByRouteKeyTest");
String collectionName = "splitByRouteKeyTest";
int numShards = 4;
int replicationFactor = 2;
int maxShardsPerNode = (((numShards * replicationFactor) / getCommonCloudSolrClient()
.getZkStateReader().getClusterState().getLiveNodes().size())) + 1;
HashMap<String, List<Integer>> collectionInfos = new HashMap<>();
try (CloudSolrClient client = createCloudClient(null)) {
Map<String, Object> props = Utils.makeMap(
REPLICATION_FACTOR, replicationFactor,
MAX_SHARDS_PER_NODE, maxShardsPerNode,
NUM_SLICES, numShards);
createCollection(collectionInfos, collectionName,props,client);
}
List<Integer> list = collectionInfos.get(collectionName);
checkForCollection(collectionName, list, null);
waitForRecoveriesToFinish(false);
String url = getUrlFromZk(getCommonCloudSolrClient().getZkStateReader().getClusterState(), collectionName);
try (HttpSolrClient collectionClient = getHttpSolrClient(url)) {
String splitKey = "b!";
ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();
final DocRouter router = clusterState.getCollection(collectionName).getRouter();
Slice shard1 = clusterState.getSlice(collectionName, SHARD1);
DocRouter.Range shard1Range = shard1.getRange() != null ? shard1.getRange() : router.fullRange();
final List<DocRouter.Range> ranges = ((CompositeIdRouter) router).partitionRangeByKey(splitKey, shard1Range);
final int[] docCounts = new int[ranges.size()];
int uniqIdentifier = (1 << 12);
int splitKeyDocCount = 0;
for (int i = 100; i <= 200; i++) {
String shardKey = "" + (char) ('a' + (i % 26)); // See comment in ShardRoutingTest for hash distribution
String idStr = shardKey + "!" + i;
collectionClient.add(getDoc(id, idStr, "n_ti", (shardKey + "!").equals(splitKey) ? uniqIdentifier : i));
int idx = getHashRangeIdx(router, ranges, idStr);
if (idx != -1) {
docCounts[idx]++;
}
if (splitKey.equals(shardKey + "!"))
splitKeyDocCount++;
}
for (int i = 0; i < docCounts.length; i++) {
int docCount = docCounts[i];
log.info("Shard {} docCount = {}", "shard1_" + i, docCount);
}
log.info("Route key doc count = {}", splitKeyDocCount);
collectionClient.commit();
for (int i = 0; i < 3; i++) {
try {
splitShard(collectionName, null, null, splitKey);
break;
} catch (HttpSolrClient.RemoteSolrException e) {
if (e.code() != 500) {
throw e;
}
log.error("SPLITSHARD failed. " + (i < 2 ? " Retring split" : ""), e);
if (i == 2) {
fail("SPLITSHARD was not successful even after three tries");
}
}
}
waitForRecoveriesToFinish(collectionName, false);
SolrQuery solrQuery = new SolrQuery("*:*");
assertEquals("DocCount on shard1_0 does not match", docCounts[0], collectionClient.query(solrQuery.setParam("shards", "shard1_0")).getResults().getNumFound());
assertEquals("DocCount on shard1_1 does not match", docCounts[1], collectionClient.query(solrQuery.setParam("shards", "shard1_1")).getResults().getNumFound());
assertEquals("DocCount on shard1_2 does not match", docCounts[2], collectionClient.query(solrQuery.setParam("shards", "shard1_2")).getResults().getNumFound());
solrQuery = new SolrQuery("n_ti:" + uniqIdentifier);
assertEquals("shard1_0 must have 0 docs for route key: " + splitKey, 0, collectionClient.query(solrQuery.setParam("shards", "shard1_0")).getResults().getNumFound());
assertEquals("Wrong number of docs on shard1_1 for route key: " + splitKey, splitKeyDocCount, collectionClient.query(solrQuery.setParam("shards", "shard1_1")).getResults().getNumFound());
assertEquals("shard1_2 must have 0 docs for route key: " + splitKey, 0, collectionClient.query(solrQuery.setParam("shards", "shard1_2")).getResults().getNumFound());
}
}
protected void checkDocCountsAndShardStates(int[] docCounts, int numReplicas) throws Exception {
ClusterState clusterState = null;
Slice slice1_0 = null, slice1_1 = null;
int i = 0;
for (i = 0; i < 10; i++) {
ZkStateReader zkStateReader = cloudClient.getZkStateReader();
clusterState = zkStateReader.getClusterState();
slice1_0 = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, "shard1_0");
slice1_1 = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, "shard1_1");
if (slice1_0.getState() == Slice.State.ACTIVE && slice1_1.getState() == Slice.State.ACTIVE) {
break;
}
Thread.sleep(500);
}
log.info("ShardSplitTest waited for {} ms for shard state to be set to active", i * 500);
assertNotNull("Cluster state does not contain shard1_0", slice1_0);
assertNotNull("Cluster state does not contain shard1_0", slice1_1);
assertSame("shard1_0 is not active", Slice.State.ACTIVE, slice1_0.getState());
assertSame("shard1_1 is not active", Slice.State.ACTIVE, slice1_1.getState());
assertEquals("Wrong number of replicas created for shard1_0", numReplicas, slice1_0.getReplicas().size());
assertEquals("Wrong number of replicas created for shard1_1", numReplicas, slice1_1.getReplicas().size());
commit();
// can't use checkShardConsistency because it insists on jettys and clients for each shard
checkSubShardConsistency(SHARD1_0);
checkSubShardConsistency(SHARD1_1);
SolrQuery query = new SolrQuery("*:*").setRows(1000).setFields("id", "_version_");
query.set("distrib", false);
ZkCoreNodeProps shard1_0 = getLeaderUrlFromZk(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1_0);
QueryResponse response;
try (HttpSolrClient shard1_0Client = getHttpSolrClient(shard1_0.getCoreUrl())) {
response = shard1_0Client.query(query);
}
long shard10Count = response.getResults().getNumFound();
ZkCoreNodeProps shard1_1 = getLeaderUrlFromZk(
AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1_1);
QueryResponse response2;
try (HttpSolrClient shard1_1Client = getHttpSolrClient(shard1_1.getCoreUrl())) {
response2 = shard1_1Client.query(query);
}
long shard11Count = response2.getResults().getNumFound();
logDebugHelp(docCounts, response, shard10Count, response2, shard11Count);
assertEquals("Wrong doc count on shard1_0. See SOLR-5309", docCounts[0], shard10Count);
assertEquals("Wrong doc count on shard1_1. See SOLR-5309", docCounts[1], shard11Count);
}
protected void checkSubShardConsistency(String shard) throws SolrServerException, IOException {
SolrQuery query = new SolrQuery("*:*").setRows(1000).setFields("id", "_version_");
query.set("distrib", false);
ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();
Slice slice = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, shard);
long[] numFound = new long[slice.getReplicasMap().size()];
int c = 0;
for (Replica replica : slice.getReplicas()) {
String coreUrl = new ZkCoreNodeProps(replica).getCoreUrl();
QueryResponse response;
try (HttpSolrClient client = getHttpSolrClient(coreUrl)) {
response = client.query(query);
}
numFound[c++] = response.getResults().getNumFound();
log.info("Shard: " + shard + " Replica: {} has {} docs", coreUrl, String.valueOf(response.getResults().getNumFound()));
assertTrue("Shard: " + shard + " Replica: " + coreUrl + " has 0 docs", response.getResults().getNumFound() > 0);
}
for (int i = 0; i < slice.getReplicasMap().size(); i++) {
assertEquals(shard + " is not consistent", numFound[0], numFound[i]);
}
}
protected void splitShard(String collection, String shardId, List<DocRouter.Range> subRanges, String splitKey) throws SolrServerException, IOException {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("action", CollectionParams.CollectionAction.SPLITSHARD.toString());
params.set("collection", collection);
if (shardId != null) {
params.set("shard", shardId);
}
if (subRanges != null) {
StringBuilder ranges = new StringBuilder();
for (int i = 0; i < subRanges.size(); i++) {
DocRouter.Range subRange = subRanges.get(i);
ranges.append(subRange.toString());
if (i < subRanges.size() - 1)
ranges.append(",");
}
params.set("ranges", ranges.toString());
}
if (splitKey != null) {
params.set("split.key", splitKey);
}
SolrRequest request = new QueryRequest(params);
request.setPath("/admin/collections");
String baseUrl = ((HttpSolrClient) shardToJetty.get(SHARD1).get(0).client.solrClient)
.getBaseURL();
baseUrl = baseUrl.substring(0, baseUrl.length() - "collection1".length());
try (HttpSolrClient baseServer = getHttpSolrClient(baseUrl)) {
baseServer.setConnectionTimeout(30000);
baseServer.setSoTimeout(60000 * 5);
baseServer.request(request);
}
}
protected void indexAndUpdateCount(DocRouter router, List<DocRouter.Range> ranges, int[] docCounts, String id, int n) throws Exception {
index("id", id, "n_ti", n);
int idx = getHashRangeIdx(router, ranges, id);
if (idx != -1) {
docCounts[idx]++;
}
}
protected void deleteAndUpdateCount(DocRouter router, List<DocRouter.Range> ranges, int[] docCounts, String id) throws Exception {
controlClient.deleteById(id);
cloudClient.deleteById(id);
int idx = getHashRangeIdx(router, ranges, id);
if (idx != -1) {
docCounts[idx]--;
}
}
public static int getHashRangeIdx(DocRouter router, List<DocRouter.Range> ranges, String id) {
int hash = 0;
if (router instanceof HashBasedRouter) {
HashBasedRouter hashBasedRouter = (HashBasedRouter) router;
hash = hashBasedRouter.sliceHash(id, null, null,null);
}
for (int i = 0; i < ranges.size(); i++) {
DocRouter.Range range = ranges.get(i);
if (range.includes(hash))
return i;
}
return -1;
}
protected void logDebugHelp(int[] docCounts, QueryResponse response, long shard10Count, QueryResponse response2, long shard11Count) {
for (int i = 0; i < docCounts.length; i++) {
int docCount = docCounts[i];
log.info("Expected docCount for shard1_{} = {}", i, docCount);
}
log.info("Actual docCount for shard1_0 = {}", shard10Count);
log.info("Actual docCount for shard1_1 = {}", shard11Count);
Map<String, String> idVsVersion = new HashMap<>();
Map<String, SolrDocument> shard10Docs = new HashMap<>();
Map<String, SolrDocument> shard11Docs = new HashMap<>();
for (int i = 0; i < response.getResults().size(); i++) {
SolrDocument document = response.getResults().get(i);
idVsVersion.put(document.getFieldValue("id").toString(), document.getFieldValue("_version_").toString());
SolrDocument old = shard10Docs.put(document.getFieldValue("id").toString(), document);
if (old != null) {
log.error("EXTRA: ID: " + document.getFieldValue("id") + " on shard1_0. Old version: " + old.getFieldValue("_version_") + " new version: " + document.getFieldValue("_version_"));
}
}
for (int i = 0; i < response2.getResults().size(); i++) {
SolrDocument document = response2.getResults().get(i);
String value = document.getFieldValue("id").toString();
String version = idVsVersion.get(value);
if (version != null) {
log.error("DUPLICATE: ID: " + value + " , shard1_0Version: " + version + " shard1_1Version:" + document.getFieldValue("_version_"));
}
SolrDocument old = shard11Docs.put(document.getFieldValue("id").toString(), document);
if (old != null) {
log.error("EXTRA: ID: " + document.getFieldValue("id") + " on shard1_1. Old version: " + old.getFieldValue("_version_") + " new version: " + document.getFieldValue("_version_"));
}
}
}
@Override
protected SolrClient createNewSolrClient(String collection, String baseUrl) {
HttpSolrClient client = (HttpSolrClient) super.createNewSolrClient(collection, baseUrl);
client.setSoTimeout(5 * 60 * 1000);
return client;
}
@Override
protected SolrClient createNewSolrClient(int port) {
HttpSolrClient client = (HttpSolrClient) super.createNewSolrClient(port);
client.setSoTimeout(5 * 60 * 1000);
return client;
}
@Override
protected CloudSolrClient createCloudClient(String defaultCollection) {
CloudSolrClient client = super.createCloudClient(defaultCollection);
return client;
}
}
| 1 | 25,987 | I don't think this should be here? | apache-lucene-solr | java |
@@ -26,8 +26,9 @@ type SyscallsImpl interface {
HashBlake2b(data []byte) [32]byte
ComputeUnsealedSectorCID(ctx context.Context, proof abi.RegisteredProof, pieces []abi.PieceInfo) (cid.Cid, error)
VerifySeal(ctx context.Context, info abi.SealVerifyInfo) error
- VerifyPoSt(ctx context.Context, info abi.PoStVerifyInfo) error
- VerifyConsensusFault(ctx context.Context, h1, h2, extra []byte, head block.TipSetKey, view SyscallsStateView, earliest abi.ChainEpoch) (*specsruntime.ConsensusFault, error)
+ VerifyWinningPoSt(ctx context.Context, info abi.WinningPoStVerifyInfo) error
+ VerifyPoSt(ctx context.Context, info abi.WindowPoStVerifyInfo) error
+ VerifyConsensusFault(ctx context.Context, h1, h2, extra []byte, head block.TipSetKey, view SyscallsStateView) (*specsruntime.ConsensusFault, error)
}
type syscalls struct { | 1 | package vmcontext
import (
"context"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/specs-actors/actors/abi"
specsruntime "github.com/filecoin-project/specs-actors/actors/runtime"
"github.com/ipfs/go-cid"
"github.com/filecoin-project/go-filecoin/internal/pkg/block"
"github.com/filecoin-project/go-filecoin/internal/pkg/crypto"
"github.com/filecoin-project/go-filecoin/internal/pkg/state"
"github.com/filecoin-project/go-filecoin/internal/pkg/vm/internal/gascost"
)
type SyscallsStateView interface {
state.AccountStateView
MinerControlAddresses(ctx context.Context, maddr address.Address) (owner, worker address.Address, err error)
}
// Syscall implementation interface.
// These methods take the chain epoch and other context that is implicit in the runtime as explicit parameters.
type SyscallsImpl interface {
VerifySignature(ctx context.Context, view SyscallsStateView, signature crypto.Signature, signer address.Address, plaintext []byte) error
HashBlake2b(data []byte) [32]byte
ComputeUnsealedSectorCID(ctx context.Context, proof abi.RegisteredProof, pieces []abi.PieceInfo) (cid.Cid, error)
VerifySeal(ctx context.Context, info abi.SealVerifyInfo) error
VerifyPoSt(ctx context.Context, info abi.PoStVerifyInfo) error
VerifyConsensusFault(ctx context.Context, h1, h2, extra []byte, head block.TipSetKey, view SyscallsStateView, earliest abi.ChainEpoch) (*specsruntime.ConsensusFault, error)
}
type syscalls struct {
impl SyscallsImpl
ctx context.Context
gasTank *GasTracker
pricelist gascost.Pricelist
head block.TipSetKey
state SyscallsStateView
}
var _ specsruntime.Syscalls = (*syscalls)(nil)
func (sys syscalls) VerifySignature(signature crypto.Signature, signer address.Address, plaintext []byte) error {
sys.gasTank.Charge(sys.pricelist.OnVerifySignature(signature.Type, len(plaintext)), "VerifySignature")
return sys.impl.VerifySignature(sys.ctx, sys.state, signature, signer, plaintext)
}
func (sys syscalls) HashBlake2b(data []byte) [32]byte {
sys.gasTank.Charge(sys.pricelist.OnHashing(len(data)), "HashBlake2b")
return sys.impl.HashBlake2b(data)
}
func (sys syscalls) ComputeUnsealedSectorCID(proof abi.RegisteredProof, pieces []abi.PieceInfo) (cid.Cid, error) {
sys.gasTank.Charge(sys.pricelist.OnComputeUnsealedSectorCid(proof, &pieces), "ComputeUnsealedSectorCID")
return sys.impl.ComputeUnsealedSectorCID(sys.ctx, proof, pieces)
}
func (sys syscalls) VerifySeal(info abi.SealVerifyInfo) error {
sys.gasTank.Charge(sys.pricelist.OnVerifySeal(info), "VerifySeal")
return sys.impl.VerifySeal(sys.ctx, info)
}
func (sys syscalls) VerifyPoSt(info abi.PoStVerifyInfo) error {
sys.gasTank.Charge(sys.pricelist.OnVerifyPost(info), "VerifyPoSt")
return sys.impl.VerifyPoSt(sys.ctx, info)
}
func (sys syscalls) VerifyConsensusFault(h1, h2, extra []byte, earliest abi.ChainEpoch) (*specsruntime.ConsensusFault, error) {
sys.gasTank.Charge(sys.pricelist.OnVerifyConsensusFault(), "VerifyConsensusFault")
return sys.impl.VerifyConsensusFault(sys.ctx, h1, h2, extra, sys.head, sys.state, earliest)
}
| 1 | 23,605 | Either I'm missing something or specs actors should remove this call cc @anorth | filecoin-project-venus | go |
@@ -119,12 +119,12 @@ namespace Reporting
var counterWidth = Math.Max(test.Counters.Max(c => c.Name.Length) + 1, 15);
var resultWidth = Math.Max(test.Counters.Max(c => c.Results.Max().ToString("F3").Length + c.MetricName.Length) + 2, 15);
ret.AppendLine(test.Name);
- ret.AppendLine($"{LeftJustify("Metric", counterWidth)}|{LeftJustify("Average",resultWidth)}|{LeftJustify("Min", resultWidth)}|{LeftJustify("Max",resultWidth)}");
+ ret.AppendLine($"{LeftJustify("Metric", counterWidth)}|{LeftJustify("Average", resultWidth)}|{LeftJustify("Min", resultWidth)}|{LeftJustify("Max", resultWidth)}");
ret.AppendLine($"{new String('-', counterWidth)}|{new String('-', resultWidth)}|{new String('-', resultWidth)}|{new String('-', resultWidth)}");
-
+
ret.AppendLine(Print(defaultCounter, counterWidth, resultWidth));
- foreach(var counter in topCounters)
+ foreach (var counter in topCounters)
{
ret.AppendLine(Print(counter, counterWidth, resultWidth));
} | 1 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment;
namespace Reporting
{
public class Reporter
{
private Run run;
private Os os;
private Build build;
private List<Test> tests = new List<Test>();
protected IEnvironment environment;
private Reporter() { }
public void AddTest(Test test)
{
if (tests.Any(t => t.Name.Equals(test.Name)))
throw new Exception($"Duplicate test name, {test.Name}");
tests.Add(test);
}
/// <summary>
/// Get a Reporter. Relies on environment variables.
/// </summary>
/// <param name="environment">Optional environment variable provider</param>
/// <returns>A Reporter instance or null if the environment is incorrect.</returns>
public static Reporter CreateReporter(IEnvironment environment = null)
{
var ret = new Reporter();
ret.environment = environment == null ? new EnvironmentProvider() : environment;
if (ret.InLab)
{
ret.Init();
}
return ret;
}
private void Init()
{
run = new Run
{
CorrelationId = environment.GetEnvironmentVariable("HELIX_CORRELATION_ID"),
PerfRepoHash = environment.GetEnvironmentVariable("PERFLAB_PERFHASH"),
Name = environment.GetEnvironmentVariable("PERFLAB_RUNNAME"),
Queue = environment.GetEnvironmentVariable("PERFLAB_QUEUE"),
};
Boolean.TryParse(environment.GetEnvironmentVariable("PERFLAB_HIDDEN"), out bool hidden);
run.Hidden = hidden;
var configs = environment.GetEnvironmentVariable("PERFLAB_CONFIGS");
if (!String.IsNullOrEmpty(configs)) // configs should be optional.
{
foreach (var kvp in configs.Split(';'))
{
var split = kvp.Split('=');
run.Configurations.Add(split[0], split[1]);
}
}
os = new Os()
{
Name = $"{RuntimeEnvironment.OperatingSystem} {RuntimeEnvironment.OperatingSystemVersion}",
Architecture = RuntimeInformation.OSArchitecture.ToString(),
Locale = CultureInfo.CurrentUICulture.ToString()
};
build = new Build
{
Repo = environment.GetEnvironmentVariable("PERFLAB_REPO"),
Branch = environment.GetEnvironmentVariable("PERFLAB_BRANCH"),
Architecture = environment.GetEnvironmentVariable("PERFLAB_BUILDARCH"),
Locale = environment.GetEnvironmentVariable("PERFLAB_LOCALE"),
GitHash = environment.GetEnvironmentVariable("PERFLAB_HASH"),
BuildName = environment.GetEnvironmentVariable("PERFLAB_BUILDNUM"),
TimeStamp = DateTime.Parse(environment.GetEnvironmentVariable("PERFLAB_BUILDTIMESTAMP")),
};
build.AdditionalData["productVersion"] = environment.GetEnvironmentVariable("DOTNET_VERSION");
}
public string GetJson()
{
if (!InLab)
{
return null;
}
var jsonobj = new
{
build,
os,
run,
tests
};
var settings = new JsonSerializerSettings();
var resolver = new DefaultContractResolver();
resolver.NamingStrategy = new CamelCaseNamingStrategy() { ProcessDictionaryKeys = false };
settings.ContractResolver = resolver;
return JsonConvert.SerializeObject(jsonobj, Formatting.Indented, settings);
}
public string WriteResultTable()
{
StringBuilder ret = new StringBuilder();
foreach (var test in tests)
{
var defaultCounter = test.Counters.Single(c => c.DefaultCounter);
var topCounters = test.Counters.Where(c => c.TopCounter && !c.DefaultCounter);
var restCounters = test.Counters.Where(c => !(c.TopCounter || c.DefaultCounter));
var counterWidth = Math.Max(test.Counters.Max(c => c.Name.Length) + 1, 15);
var resultWidth = Math.Max(test.Counters.Max(c => c.Results.Max().ToString("F3").Length + c.MetricName.Length) + 2, 15);
ret.AppendLine(test.Name);
ret.AppendLine($"{LeftJustify("Metric", counterWidth)}|{LeftJustify("Average",resultWidth)}|{LeftJustify("Min", resultWidth)}|{LeftJustify("Max",resultWidth)}");
ret.AppendLine($"{new String('-', counterWidth)}|{new String('-', resultWidth)}|{new String('-', resultWidth)}|{new String('-', resultWidth)}");
ret.AppendLine(Print(defaultCounter, counterWidth, resultWidth));
foreach(var counter in topCounters)
{
ret.AppendLine(Print(counter, counterWidth, resultWidth));
}
foreach (var counter in restCounters)
{
ret.AppendLine(Print(counter, counterWidth, resultWidth));
}
}
return ret.ToString();
}
private string Print(Counter counter, int counterWidth, int resultWidth)
{
string average = $"{counter.Results.Average():F3} {counter.MetricName}";
string max = $"{counter.Results.Max():F3} {counter.MetricName}";
string min = $"{counter.Results.Min():F3} {counter.MetricName}";
return $"{LeftJustify(counter.Name, counterWidth)}|{LeftJustify(average, resultWidth)}|{LeftJustify(min, resultWidth)}|{LeftJustify(max, resultWidth)}";
}
private string LeftJustify(string str, int width)
{
return String.Format("{0,-" + width + "}", str);
}
public bool InLab => environment.GetEnvironmentVariable("PERFLAB_INLAB")?.Equals("1") ?? false;
}
}
| 1 | 12,552 | Please undo all these changes as they are white-space only. | dotnet-performance | .cs |
@@ -114,9 +114,11 @@ final class CountryConfigurator implements FieldConfiguratorInterface
private function generateFormTypeChoices(string $countryCodeFormat): array
{
$choices = [];
+ $countriesAlpha2 = Countries::getNames();
$countries = CountryField::FORMAT_ISO_3166_ALPHA3 === $countryCodeFormat ? Countries::getAlpha3Names() : Countries::getNames();
foreach ($countries as $countryCode => $countryName) {
- $flagImageName = \in_array($countryCode, self::FLAGS_WITH_IMAGE_FILE, true) ? $countryCode : 'UNKNOWN';
+ $countryCodeAlpha2 = array_search($countryName, $countriesAlpha2, true);
+ $flagImageName = \in_array($countryCodeAlpha2, self::FLAGS_WITH_IMAGE_FILE, true) ? $countryCodeAlpha2 : 'UNKNOWN';
$flagImagePath = $this->assetPackages->getUrl(sprintf('bundles/easyadmin/images/flags/%s.png', $flagImageName));
$choiceKey = sprintf('<img src="%s" class="country-flag" loading="lazy" alt="%s"> %s', $flagImagePath, $countryName, $countryName);
| 1 | <?php
namespace EasyCorp\Bundle\EasyAdminBundle\Field\Configurator;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\TextAlign;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldConfiguratorInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\CountryField;
use Symfony\Component\Asset\Packages;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Intl\Exception\MissingResourceException;
/**
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
final class CountryConfigurator implements FieldConfiguratorInterface
{
// This list reflects the PNG files stored in src/Resources/public/images/flags/
private const FLAGS_WITH_IMAGE_FILE = [
'AD', 'AE', 'AF', 'AG', 'AL', 'AM', 'AR', 'AT', 'AU', 'AZ', 'BA', 'BB',
'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BN', 'BO', 'BR', 'BS', 'BT',
'BW', 'BY', 'BZ', 'CA', 'CD', 'CF', 'CG', 'CH', 'CI', 'CL', 'CM', 'CN',
'CO', 'CR', 'CU', 'CV', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ',
'EC', 'EE', 'EG', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FM', 'FR', 'GA', 'GB',
'GD', 'GE', 'GH', 'GM', 'GN', 'GQ', 'GR', 'GT', 'GW', 'GY', 'HK', 'HN',
'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IN', 'IQ', 'IR', 'IS', 'IT', 'JM',
'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KZ',
'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA',
'MC', 'MD', 'ME', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MR', 'MT', 'MU',
'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NE', 'NG', 'NI', 'NL', 'NO', 'NP',
'NR', 'NZ', 'OM', 'PA', 'PE', 'PG', 'PH', 'PK', 'PL', 'PR', 'PS', 'PT',
'PW', 'PY', 'QA', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE',
'SG', 'SI', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SY',
'SZ', 'TD', 'TG', 'TH', 'TJ', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV',
'TW', 'TZ', 'UA', 'UG', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VN', 'VU',
'WS', 'XK', 'YE', 'ZA', 'ZM', 'ZW',
];
private $assetPackages;
public function __construct(Packages $assetPackages)
{
$this->assetPackages = $assetPackages;
}
public function supports(FieldDto $field, EntityDto $entityDto): bool
{
return CountryField::class === $field->getFieldFqcn();
}
public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $context): void
{
$field->setFormTypeOptionIfNotSet('attr.data-widget', 'select2');
$countryCodeFormat = $field->getCustomOption(CountryField::OPTION_COUNTRY_CODE_FORMAT);
$field->setCustomOption(CountryField::OPTION_FLAG_CODE, $this->getFlagCode($field->getValue(), $countryCodeFormat));
$field->setFormattedValue($this->getCountryName($field->getValue(), $countryCodeFormat));
if (null === $field->getTextAlign() && false === $field->getCustomOption(CountryField::OPTION_SHOW_NAME)) {
$field->setTextAlign(TextAlign::CENTER);
}
if (\in_array($context->getCrud()->getCurrentPage(), [Crud::PAGE_EDIT, Crud::PAGE_NEW], true)) {
$field->setFormTypeOption('choices', $this->generateFormTypeChoices($countryCodeFormat));
// the value of this form option must be a string to properly propagate it as an HTML attribute value
$field->setFormTypeOption('attr.data-ea-escape-markup', 'false');
}
}
private function getCountryName(?string $countryCode, string $countryCodeFormat): ?string
{
if (null === $countryCode) {
return null;
}
try {
if (CountryField::FORMAT_ISO_3166_ALPHA3 === $countryCodeFormat) {
return Countries::getAlpha3Name($countryCode);
}
return Countries::getName($countryCode);
} catch (MissingResourceException $e) {
return null;
}
}
private function getFlagCode(?string $countryCode, string $countryCodeFormat): ?string
{
if (null === $countryCode) {
return null;
}
try {
$flagCode = $countryCode;
if (CountryField::FORMAT_ISO_3166_ALPHA3 === $countryCodeFormat) {
$flagCode = Countries::getAlpha2Code($flagCode);
}
if (empty($flagCode) || !\in_array($flagCode, self::FLAGS_WITH_IMAGE_FILE)) {
$flagCode = 'UNKNOWN';
}
return $flagCode;
} catch (MissingResourceException $e) {
return null;
}
}
private function generateFormTypeChoices(string $countryCodeFormat): array
{
$choices = [];
$countries = CountryField::FORMAT_ISO_3166_ALPHA3 === $countryCodeFormat ? Countries::getAlpha3Names() : Countries::getNames();
foreach ($countries as $countryCode => $countryName) {
$flagImageName = \in_array($countryCode, self::FLAGS_WITH_IMAGE_FILE, true) ? $countryCode : 'UNKNOWN';
$flagImagePath = $this->assetPackages->getUrl(sprintf('bundles/easyadmin/images/flags/%s.png', $flagImageName));
$choiceKey = sprintf('<img src="%s" class="country-flag" loading="lazy" alt="%s"> %s', $flagImagePath, $countryName, $countryName);
$choices[$choiceKey] = $countryCode;
}
return $choices;
}
}
| 1 | 13,132 | You forgot an optimization? `$countries = CountryField::FORMAT_ISO_3166_ALPHA3 === $countryCodeFormat ? Countries::getAlpha3Names() : $countriesAlpha2;` | EasyCorp-EasyAdminBundle | php |
@@ -311,7 +311,7 @@ def _comment(string):
def _format_option_value(optdict, value):
"""return the user input's value from a 'compiled' value"""
if optdict.get("type", None) == "py_version":
- value = ".".join(str(item) for item in value)
+ value = "current Python interpreter version (e.g., '3.8')"
elif isinstance(value, (list, tuple)):
value = ",".join(_format_option_value(optdict, item) for item in value)
elif isinstance(value, dict): | 1 | # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
try:
import isort.api
HAS_ISORT_5 = True
except ImportError: # isort < 5
import isort
HAS_ISORT_5 = False
import codecs
import os
import re
import sys
import textwrap
import tokenize
from io import BufferedReader, BytesIO
from typing import (
TYPE_CHECKING,
List,
Optional,
Pattern,
TextIO,
Tuple,
TypeVar,
Union,
overload,
)
from astroid import Module, modutils, nodes
from pylint.constants import PY_EXTS
if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal
if TYPE_CHECKING:
from pylint.checkers.base_checker import BaseChecker
DEFAULT_LINE_LENGTH = 79
# These are types used to overload get_global_option() and refer to the options type
GLOBAL_OPTION_BOOL = Literal[
"ignore-mixin-members",
"suggestion-mode",
"analyse-fallback-blocks",
"allow-global-unused-variables",
]
GLOBAL_OPTION_INT = Literal["max-line-length", "docstring-min-length"]
GLOBAL_OPTION_LIST = Literal["ignored-modules"]
GLOBAL_OPTION_PATTERN = Literal[
"no-docstring-rgx", "dummy-variables-rgx", "ignored-argument-names"
]
GLOBAL_OPTION_TUPLE_INT = Literal["py-version"]
GLOBAL_OPTION_NAMES = Union[
GLOBAL_OPTION_BOOL,
GLOBAL_OPTION_INT,
GLOBAL_OPTION_LIST,
GLOBAL_OPTION_PATTERN,
GLOBAL_OPTION_TUPLE_INT,
]
T_GlobalOptionReturnTypes = TypeVar(
"T_GlobalOptionReturnTypes", bool, int, List[str], Pattern, Tuple[int, ...]
)
def normalize_text(text, line_len=DEFAULT_LINE_LENGTH, indent=""):
"""Wrap the text on the given line length."""
return "\n".join(
textwrap.wrap(
text, width=line_len, initial_indent=indent, subsequent_indent=indent
)
)
CMPS = ["=", "-", "+"]
# py3k has no more cmp builtin
def cmp(a, b): # pylint: disable=redefined-builtin
return (a > b) - (a < b)
def diff_string(old, new):
"""given an old and new int value, return a string representing the
difference
"""
diff = abs(old - new)
diff_str = f"{CMPS[cmp(old, new)]}{diff and f'{diff:.2f}' or ''}"
return diff_str
def get_module_and_frameid(node):
"""return the module name and the frame id in the module"""
frame = node.frame()
module, obj = "", []
while frame:
if isinstance(frame, Module):
module = frame.name
else:
obj.append(getattr(frame, "name", "<lambda>"))
try:
frame = frame.parent.frame()
except AttributeError:
break
obj.reverse()
return module, ".".join(obj)
def get_rst_title(title, character):
"""Permit to get a title formatted as ReStructuredText test (underlined with a chosen character)."""
return f"{title}\n{character * len(title)}\n"
def get_rst_section(section, options, doc=None):
"""format an options section using as a ReStructuredText formatted output"""
result = ""
if section:
result += get_rst_title(section, "'")
if doc:
formatted_doc = normalize_text(doc)
result += f"{formatted_doc}\n\n"
for optname, optdict, value in options:
help_opt = optdict.get("help")
result += f":{optname}:\n"
if help_opt:
formatted_help = normalize_text(help_opt, indent=" ")
result += f"{formatted_help}\n"
if value:
value = str(_format_option_value(optdict, value))
result += f"\n Default: ``{value.replace('`` ', '```` ``')}``\n"
return result
def decoding_stream(
stream: Union[BufferedReader, BytesIO],
encoding: str,
errors: Literal["strict"] = "strict",
) -> codecs.StreamReader:
try:
reader_cls = codecs.getreader(encoding or sys.getdefaultencoding())
except LookupError:
reader_cls = codecs.getreader(sys.getdefaultencoding())
return reader_cls(stream, errors)
def tokenize_module(node: nodes.Module) -> List[tokenize.TokenInfo]:
with node.stream() as stream:
readline = stream.readline
return list(tokenize.tokenize(readline))
def register_plugins(linter, directory):
"""load all module and package in the given directory, looking for a
'register' function in each one, used to register pylint checkers
"""
imported = {}
for filename in os.listdir(directory):
base, extension = os.path.splitext(filename)
if base in imported or base == "__pycache__":
continue
if (
extension in PY_EXTS
and base != "__init__"
or (
not extension
and os.path.isdir(os.path.join(directory, base))
and not filename.startswith(".")
)
):
try:
module = modutils.load_module_from_file(
os.path.join(directory, filename)
)
except ValueError:
# empty module name (usually emacs auto-save files)
continue
except ImportError as exc:
print(f"Problem importing module {filename}: {exc}", file=sys.stderr)
else:
if hasattr(module, "register"):
module.register(linter)
imported[base] = 1
@overload
def get_global_option(
checker: "BaseChecker", option: GLOBAL_OPTION_BOOL, default: Optional[bool] = None
) -> bool:
...
@overload
def get_global_option(
checker: "BaseChecker", option: GLOBAL_OPTION_INT, default: Optional[int] = None
) -> int:
...
@overload
def get_global_option(
checker: "BaseChecker",
option: GLOBAL_OPTION_LIST,
default: Optional[List[str]] = None,
) -> List[str]:
...
@overload
def get_global_option(
checker: "BaseChecker",
option: GLOBAL_OPTION_PATTERN,
default: Optional[Pattern] = None,
) -> Pattern:
...
@overload
def get_global_option(
checker: "BaseChecker",
option: GLOBAL_OPTION_TUPLE_INT,
default: Optional[Tuple[int, ...]] = None,
) -> Tuple[int, ...]:
...
def get_global_option(
checker: "BaseChecker",
option: GLOBAL_OPTION_NAMES,
default: Optional[T_GlobalOptionReturnTypes] = None,
) -> Optional[T_GlobalOptionReturnTypes]:
"""Retrieve an option defined by the given *checker* or
by all known option providers.
It will look in the list of all options providers
until the given *option* will be found.
If the option wasn't found, the *default* value will be returned.
"""
# First, try in the given checker's config.
# After that, look in the options providers.
try:
return getattr(checker.config, option.replace("-", "_"))
except AttributeError:
pass
for provider in checker.linter.options_providers:
for options in provider.options:
if options[0] == option:
return getattr(provider.config, option.replace("-", "_"))
return default
def _splitstrip(string, sep=","):
"""return a list of stripped string by splitting the string given as
argument on `sep` (',' by default). Empty string are discarded.
>>> _splitstrip('a, b, c , 4,,')
['a', 'b', 'c', '4']
>>> _splitstrip('a')
['a']
>>> _splitstrip('a,\nb,\nc,')
['a', 'b', 'c']
:type string: str or unicode
:param string: a csv line
:type sep: str or unicode
:param sep: field separator, default to the comma (',')
:rtype: str or unicode
:return: the unquoted string (or the input string if it wasn't quoted)
"""
return [word.strip() for word in string.split(sep) if word.strip()]
def _unquote(string):
"""remove optional quotes (simple or double) from the string
:type string: str or unicode
:param string: an optionally quoted string
:rtype: str or unicode
:return: the unquoted string (or the input string if it wasn't quoted)
"""
if not string:
return string
if string[0] in "\"'":
string = string[1:]
if string[-1] in "\"'":
string = string[:-1]
return string
def _check_csv(value):
if isinstance(value, (list, tuple)):
return value
return _splitstrip(value)
def _comment(string):
"""return string as a comment"""
lines = [line.strip() for line in string.splitlines()]
return "# " + f"{os.linesep}# ".join(lines)
def _format_option_value(optdict, value):
"""return the user input's value from a 'compiled' value"""
if optdict.get("type", None) == "py_version":
value = ".".join(str(item) for item in value)
elif isinstance(value, (list, tuple)):
value = ",".join(_format_option_value(optdict, item) for item in value)
elif isinstance(value, dict):
value = ",".join(f"{k}:{v}" for k, v in value.items())
elif hasattr(value, "match"): # optdict.get('type') == 'regexp'
# compiled regexp
value = value.pattern
elif optdict.get("type") == "yn":
value = "yes" if value else "no"
elif isinstance(value, str) and value.isspace():
value = f"'{value}'"
return value
def format_section(
stream: TextIO, section: str, options: List[Tuple], doc: Optional[str] = None
) -> None:
"""format an options section using the INI format"""
if doc:
print(_comment(doc), file=stream)
print(f"[{section}]", file=stream)
_ini_format(stream, options)
def _ini_format(stream: TextIO, options: List[Tuple]) -> None:
"""format options using the INI format"""
for optname, optdict, value in options:
value = _format_option_value(optdict, value)
help_opt = optdict.get("help")
if help_opt:
help_opt = normalize_text(help_opt, indent="# ")
print(file=stream)
print(help_opt, file=stream)
else:
print(file=stream)
if value is None:
print(f"#{optname}=", file=stream)
else:
value = str(value).strip()
if re.match(r"^([\w-]+,)+[\w-]+$", str(value)):
separator = "\n " + " " * len(optname)
value = separator.join(x + "," for x in str(value).split(","))
# remove trailing ',' from last element of the list
value = value[:-1]
print(f"{optname}={value}", file=stream)
class IsortDriver:
"""A wrapper around isort API that changed between versions 4 and 5."""
def __init__(self, config):
if HAS_ISORT_5:
self.isort5_config = isort.api.Config(
# There is not typo here. EXTRA_standard_library is
# what most users want. The option has been named
# KNOWN_standard_library for ages in pylint and we
# don't want to break compatibility.
extra_standard_library=config.known_standard_library,
known_third_party=config.known_third_party,
)
else:
self.isort4_obj = isort.SortImports( # pylint: disable=no-member
file_contents="",
known_standard_library=config.known_standard_library,
known_third_party=config.known_third_party,
)
def place_module(self, package):
if HAS_ISORT_5:
return isort.api.place_module(package, self.isort5_config)
return self.isort4_obj.place_module(package)
| 1 | 16,205 | Shouldn't this also return the current value specified by the user? At least that's what the docstring says and what the previous version did. | PyCQA-pylint | py |
@@ -95,6 +95,9 @@ def get_listens(user_name):
:param max_ts: If you specify a ``max_ts`` timestamp, listens with listened_at less than (but not including) this value will be returned.
:param min_ts: If you specify a ``min_ts`` timestamp, listens with listened_at greater than (but not including) this value will be returned.
:param count: Optional, number of listens to return. Default: :data:`~webserver.views.api.DEFAULT_ITEMS_PER_GET` . Max: :data:`~webserver.views.api.MAX_ITEMS_PER_GET`
+ :param time_range: This parameter determines the time range the listen search. Each increment of the time_range corresponds to a range of 5 days and the default
+ time_range of 3 means that 15 days will be searched.
+ Default: :data:`~webserver.views.api.DEFAULT_TIME_RANGE` . Max: :data:`~webserver.views.api.MAX_TIME_RANGE`
:statuscode 200: Yay, you have data!
:resheader Content-Type: *application/json*
""" | 1 | import ujson
from flask import Blueprint, request, jsonify, current_app
from listenbrainz.webserver.errors import APIBadRequest, APIInternalServerError, APIUnauthorized, APINotFound, APIServiceUnavailable
from listenbrainz.db.exceptions import DatabaseException
from listenbrainz.webserver.decorators import crossdomain
from listenbrainz.webserver.views.follow import parse_user_list
from listenbrainz import webserver
import listenbrainz.db.user as db_user
from listenbrainz.webserver.rate_limiter import ratelimit
import listenbrainz.webserver.redis_connection as redis_connection
from listenbrainz.webserver.views.api_tools import insert_payload, log_raise_400, validate_listen, MAX_LISTEN_SIZE, MAX_ITEMS_PER_GET,\
DEFAULT_ITEMS_PER_GET, LISTEN_TYPE_SINGLE, LISTEN_TYPE_IMPORT, LISTEN_TYPE_PLAYING_NOW
import time
import psycopg2
api_bp = Blueprint('api_v1', __name__)
DEFAULT_TIME_RANGE = 3
MAX_TIME_RANGE = 73
@api_bp.route("/submit-listens", methods=["POST", "OPTIONS"])
@crossdomain(headers="Authorization, Content-Type")
@ratelimit()
def submit_listen():
"""
Submit listens to the server. A user token (found on https://listenbrainz.org/profile/ ) must
be provided in the Authorization header! Each request should also contain at least one listen
in the payload.
Listens should be submitted for tracks when the user has listened to half the track or 4 minutes of
the track, whichever is lower. If the user hasn't listened to 4 minutes or half the track, it doesn't
fully count as a listen and should not be submitted.
For complete details on the format of the JSON to be POSTed to this endpoint, see :ref:`json-doc`.
:reqheader Authorization: Token <user token>
:statuscode 200: listen(s) accepted.
:statuscode 400: invalid JSON sent, see error message for details.
:statuscode 401: invalid authorization. See error message for details.
:resheader Content-Type: *application/json*
"""
user = _validate_auth_header()
raw_data = request.get_data()
try:
data = ujson.loads(raw_data.decode("utf-8"))
except ValueError as e:
log_raise_400("Cannot parse JSON document: %s" % e, raw_data)
try:
payload = data['payload']
if len(payload) == 0:
log_raise_400("JSON document does not contain any listens", payload)
if len(raw_data) > len(payload) * MAX_LISTEN_SIZE:
log_raise_400("JSON document is too large. In aggregate, listens may not "
"be larger than %d characters." % MAX_LISTEN_SIZE, payload)
if data['listen_type'] not in ('playing_now', 'single', 'import'):
log_raise_400("JSON document requires a valid listen_type key.", payload)
listen_type = _get_listen_type(data['listen_type'])
if (listen_type == LISTEN_TYPE_SINGLE or listen_type == LISTEN_TYPE_PLAYING_NOW) and len(payload) > 1:
log_raise_400("JSON document contains more than listen for a single/playing_now. "
"It should contain only one.", payload)
except KeyError:
log_raise_400("Invalid JSON document submitted.", raw_data)
# validate listens to make sure json is okay
for listen in payload:
validate_listen(listen, listen_type)
try:
insert_payload(payload, user, listen_type=_get_listen_type(data['listen_type']))
except APIServiceUnavailable as e:
raise
except Exception as e:
raise APIInternalServerError("Something went wrong. Please try again.")
return jsonify({'status': 'ok'})
@api_bp.route("/user/<user_name>/listens")
@crossdomain()
@ratelimit()
def get_listens(user_name):
"""
Get listens for user ``user_name``. The format for the JSON returned is defined in our :ref:`json-doc`.
If none of the optional arguments are given, this endpoint will return the :data:`~webserver.views.api.DEFAULT_ITEMS_PER_GET` most recent listens.
The optional ``max_ts`` and ``min_ts`` UNIX epoch timestamps control at which point in time to start returning listens. You may specify max_ts or
min_ts, but not both in one call. Listens are always returned in descending timestamp order.
:param max_ts: If you specify a ``max_ts`` timestamp, listens with listened_at less than (but not including) this value will be returned.
:param min_ts: If you specify a ``min_ts`` timestamp, listens with listened_at greater than (but not including) this value will be returned.
:param count: Optional, number of listens to return. Default: :data:`~webserver.views.api.DEFAULT_ITEMS_PER_GET` . Max: :data:`~webserver.views.api.MAX_ITEMS_PER_GET`
:statuscode 200: Yay, you have data!
:resheader Content-Type: *application/json*
"""
current_time = int(time.time())
max_ts = _parse_int_arg("max_ts")
min_ts = _parse_int_arg("min_ts")
time_range = _parse_int_arg("time_range", DEFAULT_TIME_RANGE)
if time_range < 1 or time_range > MAX_TIME_RANGE:
log_raise_400("time_range must be between 1 and %d." % MAX_TIME_RANGE)
# if no max given, use now()
if max_ts and min_ts:
log_raise_400("You may only specify max_ts or min_ts, not both.")
db_conn = webserver.create_timescale(current_app)
(min_ts_per_user, max_ts_per_user) = db_conn.get_timestamps_for_user(user_name)
# If none are given, start with now and go down
if max_ts == None and min_ts == None:
max_ts = max_ts_per_user + 1
# Validate requetsed listen count is positive
count = min(_parse_int_arg("count", DEFAULT_ITEMS_PER_GET), MAX_ITEMS_PER_GET)
if count < 0:
log_raise_400("Number of listens requested should be positive")
listens = db_conn.fetch_listens(
user_name,
limit=count,
from_ts=min_ts,
to_ts=max_ts,
time_range=time_range
)
listen_data = []
for listen in listens:
listen_data.append(listen.to_api())
return jsonify({'payload': {
'user_id': user_name,
'count': len(listen_data),
'listens': listen_data,
'latest_listen_ts': max_ts_per_user,
}})
@api_bp.route("/user/<user_name>/listen-count")
@crossdomain()
@ratelimit()
def get_listen_count(user_name):
"""
Get the number of listens for a user ``user_name``.
The returned listen count has an element 'payload' with only key: 'count'
which unsurprisingly contains the listen count for the user.
:statuscode 200: Yay, you have listen counts!
:resheader Content-Type: *application/json*
"""
try:
db_conn = webserver.create_timescale(current_app)
listen_count = db_conn.get_listen_count_for_user(user_name)
if listen_count < 0:
raise APINotFound("Cannot find user: %s" % user_name)
except psycopg2.OperationalError as err:
current_app.logger.error("cannot fetch user listen count: ", str(err))
raise APIServiceUnavailable("Cannot fetch user listen count right now.")
return jsonify({'payload': {
'count': listen_count
}})
@api_bp.route("/user/<user_name>/playing-now")
@crossdomain()
@ratelimit()
def get_playing_now(user_name):
"""
Get the listen being played right now for user ``user_name``.
This endpoint returns a JSON document with a single listen in the same format as the ``/user/<user_name>/listens`` endpoint,
with one key difference, there will only be one listen returned at maximum and the listen will not contain a ``listened_at`` element.
The format for the JSON returned is defined in our :ref:`json-doc`.
:statuscode 200: Yay, you have data!
:resheader Content-Type: *application/json*
"""
user = db_user.get_by_mb_id(user_name)
if user is None:
raise APINotFound("Cannot find user: %s" % user_name)
playing_now_listen = redis_connection._redis.get_playing_now(user['id'])
listen_data = []
count = 0
if playing_now_listen:
count += 1
listen_data = [{
'track_metadata': playing_now_listen.data,
}]
return jsonify({
'payload': {
'count': count,
'user_id': user_name,
'playing_now': True,
'listens': listen_data,
},
})
@api_bp.route("/users/<user_list>/recent-listens")
@crossdomain(headers='Authorization, Content-Type')
@ratelimit()
def get_recent_listens_for_user_list(user_list):
"""
Fetch the most recent listens for a comma separated list of users. Take care to properly HTTP escape
user names that contain commas!
:statuscode 200: Fetched listens successfully.
:statuscode 400: Your user list was incomplete or otherwise invalid.
:resheader Content-Type: *application/json*
"""
limit = _parse_int_arg("limit", 2)
users = parse_user_list(user_list)
if not len(users):
raise APIBadRequest("user_list is empty or invalid.")
db_conn = webserver.create_timescale(current_app)
listens = db_conn.fetch_recent_listens_for_users(
users,
limit=limit
)
listen_data = []
for listen in listens:
listen_data.append(listen.to_api())
return jsonify({'payload': {
'user_list': user_list,
'count': len(listen_data),
'listens': listen_data,
}})
@api_bp.route('/latest-import', methods=['GET', 'POST', 'OPTIONS'])
@crossdomain(headers='Authorization, Content-Type')
@ratelimit()
def latest_import():
"""
Get and update the timestamp of the newest listen submitted in previous imports to ListenBrainz.
In order to get the timestamp for a user, make a GET request to this endpoint. The data returned will
be JSON of the following format:
{
'musicbrainz_id': the MusicBrainz ID of the user,
'latest_import': the timestamp of the newest listen submitted in previous imports. Defaults to 0
}
:param user_name: the MusicBrainz ID of the user whose data is needed
:statuscode 200: Yay, you have data!
:resheader Content-Type: *application/json*
In order to update the timestamp of a user, you'll have to provide a user token in the Authorization
Header. User tokens can be found on https://listenbrainz.org/profile/ .
The JSON that needs to be posted must contain a field named `ts` in the root with a valid unix timestamp.
:reqheader Authorization: Token <user token>
:statuscode 200: latest import timestamp updated
:statuscode 400: invalid JSON sent, see error message for details.
:statuscode 401: invalid authorization. See error message for details.
"""
if request.method == 'GET':
user_name = request.args.get('user_name', '')
user = db_user.get_by_mb_id(user_name)
if user is None:
raise APINotFound("Cannot find user: {user_name}".format(user_name=user_name))
return jsonify({
'musicbrainz_id': user['musicbrainz_id'],
'latest_import': 0 if not user['latest_import'] else int(user['latest_import'].strftime('%s'))
})
elif request.method == 'POST':
user = _validate_auth_header()
try:
ts = ujson.loads(request.get_data()).get('ts', 0)
except ValueError:
raise APIBadRequest('Invalid data sent')
try:
db_user.increase_latest_import(user['musicbrainz_id'], int(ts))
except DatabaseException as e:
current_app.logger.error("Error while updating latest import: {}".format(e))
raise APIInternalServerError('Could not update latest_import, try again')
return jsonify({'status': 'ok'})
@api_bp.route('/validate-token', methods=['GET'])
@ratelimit()
def validate_token():
"""
Check whether a User Token is a valid entry in the database.
In order to query this endpoint, send a GET request with the token to check
as the `token` argument (example: /validate-token?token=token-to-check)
A JSON response, with the following format, will be returned.
- If the given token is valid::
{
"code": 200,
"message": "Token valid.",
"valid": True,
"user": "MusicBrainz ID of the user with the passed token"
}
- If the given token is invalid::
{
"code": 200,
"message": "Token invalid.",
"valid": False,
}
:statuscode 200: The user token is valid/invalid.
:statuscode 400: No token was sent to the endpoint.
"""
auth_token = request.args.get('token', '')
if not auth_token:
raise APIBadRequest("You need to provide an Authorization token.")
user = db_user.get_by_token(auth_token)
if user is None:
return jsonify({
'code': 200,
'message': 'Token invalid.',
'valid': False,
})
else:
return jsonify({
'code': 200,
'message': 'Token valid.',
'valid': True,
'user_name': user['musicbrainz_id'],
})
def _parse_int_arg(name, default=None):
value = request.args.get(name)
if value:
try:
return int(value)
except ValueError:
raise APIBadRequest("Invalid %s argument: %s" % (name, value))
else:
return default
def _validate_auth_header():
auth_token = request.headers.get('Authorization')
if not auth_token:
raise APIUnauthorized("You need to provide an Authorization header.")
try:
auth_token = auth_token.split(" ")[1]
except IndexError:
raise APIUnauthorized("Provided Authorization header is invalid.")
user = db_user.get_by_token(auth_token)
if user is None:
raise APIUnauthorized("Invalid authorization token.")
return user
def _get_listen_type(listen_type):
return {
'single': LISTEN_TYPE_SINGLE,
'import': LISTEN_TYPE_IMPORT,
'playing_now': LISTEN_TYPE_PLAYING_NOW
}.get(listen_type)
| 1 | 16,964 | > the time range the listen search the time range of the listen search? | metabrainz-listenbrainz-server | py |
@@ -777,6 +777,8 @@ read_evex(byte *pc, decode_info_t *di, byte instr_byte,
NULL_TERMINATE_BUFFER(pc_addr);
DO_ONCE(SYSLOG(SYSLOG_ERROR, AVX_512_SUPPORT_INCOMPLETE, 2,
get_application_name(), get_application_pid(), pc_addr));
+ if (ZMM_ENABLED())
+ dynamo_preserve_zmm_caller_saved = true;
#endif
info = &evex_prefix_extensions[0][1];
} else { | 1 | /* **********************************************************
* Copyright (c) 2011-2019 Google, Inc. All rights reserved.
* Copyright (c) 2000-2010 VMware, Inc. 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 VMware, Inc. 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 VMWARE, INC. 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.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/* Copyright (c) 2001-2003 Massachusetts Institute of Technology */
/* Copyright (c) 2000-2001 Hewlett-Packard Company */
/* decode.c -- a full x86 decoder */
#include "../globals.h"
#include "arch.h"
#include "instr.h"
#include "decode.h"
#include "decode_fast.h"
#include "decode_private.h"
/*
* XXX i#431: consider cpuid features when deciding invalid instrs:
* for core DR, it doesn't really matter: the only bad thing is thinking
* a valid instr is invalid, esp decoding its size improperly.
* but for completeness and use as disassembly library might be nice.
*
* XXX (these are very old):
* 1) several opcodes gdb thinks bad/not bad -- changes to ISA?
* 2) why does gdb use Ex, Ed, & Ev for all float opcodes w/ modrm < 0xbf?
* a float instruction's modrm cannot specify a register, right?
* sizes are single-real => d, double-real => q, extended-real = 90 bits,
* 14/28 bytes, and 98/108 bytes!
* should address sizes all be 'v'?
* 3) there don't seem to be any immediate float values...?!?
* 4) fld (0xd9 0xc0-7) in Table A-10 has 2 operands in different order
* than expected, plus asm prints using just 2nd one
* 5) I don't see T...is there a T? gdb has it for 0f26mov
*/
/* N.B.: must justify each assert, since we do not want to assert on a bad
* instruction -- we want to fail gracefully and have the caller deal with it
*/
#ifdef DEBUG
/* case 10450: give messages to clients */
/* we can't undef ASSERT b/c of DYNAMO_OPTION */
# undef ASSERT_TRUNCATE
# undef ASSERT_BITFIELD_TRUNCATE
# undef ASSERT_NOT_REACHED
# define ASSERT_TRUNCATE DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
# define ASSERT_BITFIELD_TRUNCATE DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
# define ASSERT_NOT_REACHED DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
#endif
/* used for VEX decoding */
#define xx TYPE_NONE, OPSZ_NA
static const instr_info_t escape_instr = { ESCAPE, 0x000000, "(bad)", xx, xx, xx,
xx, xx, 0, 0, 0 };
static const instr_info_t escape_38_instr = {
ESCAPE_3BYTE_38, 0x000000, "(bad)", xx, xx, xx, xx, xx, 0, 0, 0
};
static const instr_info_t escape_3a_instr = {
ESCAPE_3BYTE_3a, 0x000000, "(bad)", xx, xx, xx, xx, xx, 0, 0, 0
};
/* used for XOP decoding */
static const instr_info_t xop_8_instr = { XOP_8_EXT, 0x000000, "(bad)", xx, xx, xx,
xx, xx, 0, 0, 0 };
static const instr_info_t xop_9_instr = { XOP_9_EXT, 0x000000, "(bad)", xx, xx, xx,
xx, xx, 0, 0, 0 };
static const instr_info_t xop_a_instr = { XOP_A_EXT, 0x000000, "(bad)", xx, xx, xx,
xx, xx, 0, 0, 0 };
#undef xx
bool
is_isa_mode_legal(dr_isa_mode_t mode)
{
#ifdef X64
return (mode == DR_ISA_IA32 || mode == DR_ISA_AMD64);
#else
return (mode == DR_ISA_IA32);
#endif
}
app_pc
canonicalize_pc_target(dcontext_t *dcontext, app_pc pc)
{
return pc;
}
#ifdef X64
bool
set_x86_mode(dcontext_t *dcontext, bool x86)
{
dr_isa_mode_t old_mode;
if (!dr_set_isa_mode(dcontext, x86 ? DR_ISA_IA32 : DR_ISA_AMD64, &old_mode))
return false;
return old_mode == DR_ISA_IA32;
}
bool
get_x86_mode(dcontext_t *dcontext)
{
return dr_get_isa_mode(dcontext) == DR_ISA_IA32;
}
#endif
/****************************************************************************
* All code below based on tables in the ``Intel Architecture Software
* Developer's Manual,'' Volume 2: Instruction Set Reference, 2001.
*/
#if defined(DEBUG) && !defined(STANDALONE_DECODER) /* currently only used in ASSERTs */
static bool
is_variable_size(opnd_size_t sz)
{
switch (sz) {
case OPSZ_2_short1:
case OPSZ_4_short2:
case OPSZ_4x8:
case OPSZ_4x8_short2:
case OPSZ_4x8_short2xi8:
case OPSZ_4_short2xi4:
case OPSZ_4_rex8_short2:
case OPSZ_4_rex8:
case OPSZ_6_irex10_short4:
case OPSZ_6x10:
case OPSZ_8_short2:
case OPSZ_8_short4:
case OPSZ_28_short14:
case OPSZ_108_short94:
case OPSZ_1_reg4:
case OPSZ_2_reg4:
case OPSZ_4_reg16:
case OPSZ_32_short16:
case OPSZ_8_rex16:
case OPSZ_8_rex16_short4:
case OPSZ_12_rex40_short6:
case OPSZ_16_vex32:
case OPSZ_16_vex32_evex64:
case OPSZ_vex32_evex64: return true;
default: return false;
}
}
#endif
opnd_size_t
resolve_var_reg_size(opnd_size_t sz, bool is_reg)
{
switch (sz) {
case OPSZ_1_reg4: return (is_reg ? OPSZ_4 : OPSZ_1);
case OPSZ_2_reg4: return (is_reg ? OPSZ_4 : OPSZ_2);
case OPSZ_4_reg16:
return (is_reg ? OPSZ_4 /* i#1382: we distinguish sub-xmm now */
: OPSZ_4);
}
return sz;
}
/* Like all our code, we assume cs specifies default data and address sizes.
* This routine assumes the size varies by data, NOT by address!
*/
opnd_size_t
resolve_variable_size(decode_info_t *di /*IN: x86_mode, prefixes*/, opnd_size_t sz,
bool is_reg)
{
switch (sz) {
case OPSZ_2_short1: return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_1 : OPSZ_2);
case OPSZ_4_short2: return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_2 : OPSZ_4);
case OPSZ_4x8: return (X64_MODE(di) ? OPSZ_8 : OPSZ_4);
case OPSZ_4x8_short2:
return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_2
: (X64_MODE(di) ? OPSZ_8 : OPSZ_4));
case OPSZ_4x8_short2xi8:
return (X64_MODE(di) ? (proc_get_vendor() == VENDOR_INTEL
? OPSZ_8
: (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_2 : OPSZ_8))
: (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_2 : OPSZ_4));
case OPSZ_4_short2xi4:
return ((X64_MODE(di) && proc_get_vendor() == VENDOR_INTEL)
? OPSZ_4
: (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_2 : OPSZ_4));
case OPSZ_4_rex8_short2: /* rex.w trumps data prefix */
return (TEST(PREFIX_REX_W, di->prefixes)
? OPSZ_8
: (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_2 : OPSZ_4));
case OPSZ_4_rex8: return (TEST(PREFIX_REX_W, di->prefixes) ? OPSZ_8 : OPSZ_4);
case OPSZ_6_irex10_short4: /* rex.w trumps data prefix, but is ignored on AMD */
DODEBUG({
/* less annoying than a CURIOSITY assert when testing */
if (TEST(PREFIX_REX_W, di->prefixes))
SYSLOG_INTERNAL_INFO_ONCE("curiosity: rex.w on OPSZ_6_irex10_short4!");
});
return ((TEST(PREFIX_REX_W, di->prefixes) && proc_get_vendor() != VENDOR_AMD)
? OPSZ_10
: (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_4 : OPSZ_6));
case OPSZ_6x10: return (X64_MODE(di) ? OPSZ_10 : OPSZ_6);
case OPSZ_8_short2: return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_2 : OPSZ_8);
case OPSZ_8_short4: return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_4 : OPSZ_8);
case OPSZ_8_rex16: return (TEST(PREFIX_REX_W, di->prefixes) ? OPSZ_16 : OPSZ_8);
case OPSZ_8_rex16_short4: /* rex.w trumps data prefix */
return (TEST(PREFIX_REX_W, di->prefixes)
? OPSZ_16
: (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_4 : OPSZ_8));
case OPSZ_12_rex40_short6: /* rex.w trumps data prefix */
return (TEST(PREFIX_REX_W, di->prefixes)
? OPSZ_40
: (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_6 : OPSZ_12));
case OPSZ_16_vex32: return (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_32 : OPSZ_16);
case OPSZ_32_short16: return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_16 : OPSZ_32);
case OPSZ_28_short14: return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_14 : OPSZ_28);
case OPSZ_108_short94: return (TEST(PREFIX_DATA, di->prefixes) ? OPSZ_94 : OPSZ_108);
case OPSZ_1_reg4:
case OPSZ_2_reg4:
case OPSZ_4_reg16: return resolve_var_reg_size(sz, is_reg);
/* The _of_ types are not exposed to the user so convert here */
case OPSZ_1_of_16: return OPSZ_1;
case OPSZ_2_of_8:
case OPSZ_2_of_16: return OPSZ_2;
case OPSZ_4_of_8:
case OPSZ_4_of_16: return OPSZ_4;
case OPSZ_4_rex8_of_16: return (TEST(PREFIX_REX_W, di->prefixes) ? OPSZ_8 : OPSZ_4);
case OPSZ_8_of_16: return OPSZ_8;
case OPSZ_12_of_16: return OPSZ_12;
case OPSZ_12_rex8_of_16: return (TEST(PREFIX_REX_W, di->prefixes) ? OPSZ_8 : OPSZ_12);
case OPSZ_14_of_16: return OPSZ_14;
case OPSZ_15_of_16: return OPSZ_15;
case OPSZ_8_of_16_vex32: return (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_32 : OPSZ_8);
case OPSZ_16_of_32:
case OPSZ_16_of_32_evex64: return OPSZ_16;
case OPSZ_32_of_64: return OPSZ_32;
case OPSZ_4_of_32_evex64: return OPSZ_4;
case OPSZ_8_of_32_evex64: return OPSZ_8;
case OPSZ_16_vex32_evex64:
/* XXX i#1312: There may be a conflict since LL' is also used for rounding
* control in AVX-512 if used in combination.
*/
return (TEST(PREFIX_EVEX_LL, di->prefixes)
? OPSZ_64
: (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_32 : OPSZ_16));
case OPSZ_vex32_evex64:
/* XXX i#1312: There may be a conflict since LL' is also used for rounding
* control in AVX-512 if used in combination.
*/
return (TEST(PREFIX_EVEX_LL, di->prefixes) ? OPSZ_64 : OPSZ_32);
case OPSZ_half_16_vex32: return (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_16 : OPSZ_8);
case OPSZ_half_16_vex32_evex64:
return (TEST(PREFIX_EVEX_LL, di->prefixes)
? OPSZ_32
: (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_16 : OPSZ_8));
case OPSZ_quarter_16_vex32:
return (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_8 : OPSZ_4);
case OPSZ_quarter_16_vex32_evex64:
return (TEST(PREFIX_EVEX_LL, di->prefixes)
? OPSZ_16
: (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_8 : OPSZ_4));
case OPSZ_eighth_16_vex32:
return (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_4 : OPSZ_2);
case OPSZ_eighth_16_vex32_evex64:
return (TEST(PREFIX_EVEX_LL, di->prefixes)
? OPSZ_8
: (TEST(PREFIX_VEX_L, di->prefixes) ? OPSZ_4 : OPSZ_2));
}
return sz;
}
opnd_size_t
expand_subreg_size(opnd_size_t sz)
{
/* XXX i#1312: please note the comment in decode_reg. For mixed vector register sizes
* within the instruction, this is fragile and relies on the fact that we return
* OPSZ_16 or OPSZ_32 here. This should be handled in a better way.
*/
switch (sz) {
case OPSZ_2_of_8:
case OPSZ_4_of_8: return OPSZ_8;
case OPSZ_1_of_16:
case OPSZ_2_of_16:
case OPSZ_4_of_16:
case OPSZ_4_rex8_of_16:
case OPSZ_8_of_16:
case OPSZ_12_of_16:
case OPSZ_12_rex8_of_16:
case OPSZ_14_of_16:
case OPSZ_15_of_16:
case OPSZ_4_reg16: return OPSZ_16;
case OPSZ_16_of_32: return OPSZ_32;
case OPSZ_32_of_64: return OPSZ_64;
case OPSZ_8_of_16_vex32:
case OPSZ_half_16_vex32: return OPSZ_16_vex32;
case OPSZ_half_16_vex32_evex64: return OPSZ_16_vex32_evex64;
case OPSZ_quarter_16_vex32: return OPSZ_half_16_vex32;
case OPSZ_quarter_16_vex32_evex64: return OPSZ_half_16_vex32_evex64;
case OPSZ_eighth_16_vex32: return OPSZ_quarter_16_vex32;
case OPSZ_eighth_16_vex32_evex64: return OPSZ_quarter_16_vex32_evex64;
}
return sz;
}
opnd_size_t
resolve_variable_size_dc(dcontext_t *dcontext, uint prefixes, opnd_size_t sz, bool is_reg)
{
decode_info_t di;
IF_X64(di.x86_mode = get_x86_mode(dcontext));
di.prefixes = prefixes;
return resolve_variable_size(&di, sz, is_reg);
}
opnd_size_t
resolve_addr_size(decode_info_t *di /*IN: x86_mode, prefixes*/)
{
if (TEST(PREFIX_ADDR, di->prefixes))
return (X64_MODE(di) ? OPSZ_4 : OPSZ_2);
else
return (X64_MODE(di) ? OPSZ_8 : OPSZ_4);
}
bool
optype_is_indir_reg(int optype)
{
switch (optype) {
case TYPE_INDIR_VAR_XREG:
case TYPE_INDIR_VAR_XREG_OFFS_1:
case TYPE_INDIR_VAR_XREG_OFFS_N:
case TYPE_INDIR_VAR_XIREG:
case TYPE_INDIR_VAR_XIREG_OFFS_1:
case TYPE_INDIR_VAR_REG:
case TYPE_INDIR_VAR_REG_OFFS_2:
case TYPE_INDIR_VAR_REG_SIZEx2:
case TYPE_INDIR_VAR_XREG_OFFS_8:
case TYPE_INDIR_VAR_XREG_SIZEx8:
case TYPE_INDIR_VAR_REG_SIZEx3x5: return true;
}
return false;
}
opnd_size_t
indir_var_reg_size(decode_info_t *di, int optype)
{
switch (optype) {
case TYPE_INDIR_VAR_XREG:
case TYPE_INDIR_VAR_XREG_OFFS_1:
case TYPE_INDIR_VAR_XREG_OFFS_N:
/* non-zero immed int adds additional, but we require client to handle that
* b/c our decoding and encoding can't see the rest of the operands
*/
return OPSZ_VARSTACK;
case TYPE_INDIR_VAR_XIREG:
case TYPE_INDIR_VAR_XIREG_OFFS_1: return OPSZ_ret;
case TYPE_INDIR_VAR_REG: return OPSZ_REXVARSTACK;
case TYPE_INDIR_VAR_REG_OFFS_2:
case TYPE_INDIR_VAR_REG_SIZEx2: return OPSZ_8_rex16_short4;
case TYPE_INDIR_VAR_XREG_OFFS_8:
case TYPE_INDIR_VAR_XREG_SIZEx8: return OPSZ_32_short16;
case TYPE_INDIR_VAR_REG_SIZEx3x5: return OPSZ_12_rex40_short6;
default: CLIENT_ASSERT(false, "internal error: invalid indir reg type");
}
return OPSZ_0;
}
/* Returns multiplier of the operand size to use as the base-disp offs */
int
indir_var_reg_offs_factor(int optype)
{
switch (optype) {
case TYPE_INDIR_VAR_XREG_OFFS_1:
case TYPE_INDIR_VAR_XREG_OFFS_8:
case TYPE_INDIR_VAR_XREG_OFFS_N:
case TYPE_INDIR_VAR_XIREG_OFFS_1:
case TYPE_INDIR_VAR_REG_OFFS_2: return -1;
}
return 0;
}
/****************************************************************************
* Reading all bytes of instruction
*/
static byte *
read_immed(byte *pc, decode_info_t *di, opnd_size_t size, ptr_int_t *result)
{
size = resolve_variable_size(di, size, false);
/* all data immediates are sign-extended. we use the compiler's casts with
* signed types to do our sign extensions for us.
*/
switch (size) {
case OPSZ_1:
*result = (ptr_int_t)(char)*pc; /* sign-extend */
pc++;
break;
case OPSZ_2:
*result = (ptr_int_t) * ((short *)pc); /* sign-extend */
pc += 2;
break;
case OPSZ_4:
*result = (ptr_int_t) * ((int *)pc); /* sign-extend */
pc += 4;
break;
case OPSZ_8:
CLIENT_ASSERT(X64_MODE(di), "decode immediate: invalid size");
CLIENT_ASSERT(sizeof(ptr_int_t) == 8, "decode immediate: internal size error");
*result = *((ptr_int_t *)pc);
pc += 8;
break;
default:
/* called internally w/ instr_info_t fields or hardcoded values,
* so ok to assert */
CLIENT_ASSERT(false, "decode immediate: unknown size");
}
return pc;
}
/* reads any trailing immed bytes */
static byte *
read_operand(byte *pc, decode_info_t *di, byte optype, opnd_size_t opsize)
{
ptr_int_t val = 0;
opnd_size_t size = opsize;
switch (optype) {
case TYPE_A: {
CLIENT_ASSERT(!X64_MODE(di), "x64 has no type A instructions");
/* ok b/c only instr_info_t fields passed */
CLIENT_ASSERT(opsize == OPSZ_6_irex10_short4, "decode A operand error");
if (TEST(PREFIX_DATA, di->prefixes)) {
/* 4-byte immed */
pc = read_immed(pc, di, OPSZ_4, &val);
#ifdef X64
if (!X64_MODE(di)) {
/* we do not want the sign extension that read_immed() applied */
val &= (ptr_int_t)0x00000000ffffffff;
}
#endif
/* ok b/c only instr_info_t fields passed */
CLIENT_ASSERT(di->size_immed == OPSZ_NA && di->size_immed2 == OPSZ_NA,
"decode A operand error");
di->size_immed = resolve_variable_size(di, opsize, false);
ASSERT(di->size_immed == OPSZ_4);
di->immed = val;
} else {
/* 6-byte immed */
ptr_int_t val2 = 0;
/* little-endian: segment comes last */
pc = read_immed(pc, di, OPSZ_4, &val2);
pc = read_immed(pc, di, OPSZ_2, &val);
#ifdef X64
if (!X64_MODE(di)) {
/* we do not want the sign extension that read_immed() applied */
val2 &= (ptr_int_t)0x00000000ffffffff;
}
#endif
/* ok b/c only instr_info_t fields passed */
CLIENT_ASSERT(di->size_immed == OPSZ_NA && di->size_immed2 == OPSZ_NA,
"decode A operand error");
di->size_immed = resolve_variable_size(di, opsize, false);
ASSERT(di->size_immed == OPSZ_6);
di->size_immed2 = resolve_variable_size(di, opsize, false);
di->immed = val;
di->immed2 = val2;
}
return pc;
}
case TYPE_I: {
pc = read_immed(pc, di, opsize, &val);
break;
}
case TYPE_J: {
byte *end_pc;
pc = read_immed(pc, di, opsize, &val);
if (di->orig_pc != di->start_pc) {
CLIENT_ASSERT(di->start_pc != NULL,
"internal decode error: start pc not set");
end_pc = di->orig_pc + (pc - di->start_pc);
} else
end_pc = pc;
/* convert from relative offset to absolute target pc */
val = ((ptr_int_t)end_pc) + val;
if ((!X64_MODE(di) || proc_get_vendor() != VENDOR_INTEL) &&
TEST(PREFIX_DATA, di->prefixes)) {
/* need to clear upper 16 bits */
val &= (ptr_int_t)0x0000ffff;
} /* for x64 Intel, always 64-bit addr ("f64" in Intel table) */
break;
}
case TYPE_L: {
/* part of AVX: top 4 bits of 8-bit immed select xmm/ymm register */
pc = read_immed(pc, di, OPSZ_1, &val);
break;
}
case TYPE_O: {
/* no modrm byte, offset follows directly. this is address-sized,
* so 64-bit for x64, and addr prefix affects it. */
size = resolve_addr_size(di);
pc = read_immed(pc, di, size, &val);
if (TEST(PREFIX_ADDR, di->prefixes)) {
/* need to clear upper bits */
if (X64_MODE(di))
val &= (ptr_int_t)0xffffffff;
else
val &= (ptr_int_t)0x0000ffff;
}
#ifdef X64
if (!X64_MODE(di)) {
/* we do not want the sign extension that read_immed() applied */
val &= (ptr_int_t)0x00000000ffffffff;
}
#endif
break;
}
default: return pc;
}
if (di->size_immed == OPSZ_NA) {
di->size_immed = size;
di->immed = val;
} else {
/* ok b/c only instr_info_t fields passed */
CLIENT_ASSERT(di->size_immed2 == OPSZ_NA, "decode operand error");
di->size_immed2 = size;
di->immed2 = val;
}
return pc;
}
/* reads the modrm byte and any following sib and offset bytes */
static byte *
read_modrm(byte *pc, decode_info_t *di)
{
byte modrm = *pc;
pc++;
di->modrm = modrm;
di->mod = (byte)((modrm >> 6) & 0x3); /* top 2 bits */
di->reg = (byte)((modrm >> 3) & 0x7); /* middle 3 bits */
di->rm = (byte)(modrm & 0x7); /* bottom 3 bits */
/* addr16 displacement */
if (!X64_MODE(di) && TEST(PREFIX_ADDR, di->prefixes)) {
di->has_sib = false;
if ((di->mod == 0 && di->rm == 6) || di->mod == 2) {
/* 2-byte disp */
di->has_disp = true;
if (di->mod == 0 && di->rm == 6) {
/* treat absolute addr as unsigned */
di->disp = (int)*((ushort *)pc); /* zero-extend */
} else {
/* treat relative addr as signed */
di->disp = (int)*((short *)pc); /* sign-extend */
}
pc += 2;
} else if (di->mod == 1) {
/* 1-byte disp */
di->has_disp = true;
di->disp = (int)(char)*pc; /* sign-extend */
pc++;
} else {
di->has_disp = false;
}
} else {
/* 32-bit, which sometimes has a SIB */
if (di->rm == 4 && di->mod != 3) {
/* need SIB */
byte sib = *pc;
pc++;
di->has_sib = true;
di->scale = (byte)((sib >> 6) & 0x3); /* top 2 bits */
di->index = (byte)((sib >> 3) & 0x7); /* middle 3 bits */
di->base = (byte)(sib & 0x7); /* bottom 3 bits */
} else {
di->has_sib = false;
}
/* displacement */
if ((di->mod == 0 && di->rm == 5) ||
(di->has_sib && di->mod == 0 && di->base == 5) || di->mod == 2) {
/* 4-byte disp */
di->has_disp = true;
di->disp = *((int *)pc);
IF_X64(di->disp_abs = pc); /* used to set instr->rip_rel_pos */
pc += 4;
} else if (di->mod == 1) {
/* 1-byte disp */
di->has_disp = true;
di->disp = (int)(char)*pc; /* sign-extend */
pc++;
} else {
di->has_disp = false;
}
}
return pc;
}
/* Given the potential first vex byte at pc, reads any subsequent vex
* bytes (and any prefix bytes) and sets the appropriate prefix flags in di.
* Sets info to the entry for the first opcode byte, and pc to point past
* the first opcode byte.
* Also handles xop encodings, which are quite similar to vex.
*/
static byte *
read_vex(byte *pc, decode_info_t *di, byte instr_byte,
const instr_info_t **ret_info INOUT, bool *is_vex /*or xop*/)
{
int idx = 0;
const instr_info_t *info;
byte vex_last = 0, vex_pp;
ASSERT(ret_info != NULL && *ret_info != NULL && is_vex != NULL);
info = *ret_info;
if (info->type == VEX_PREFIX_EXT) {
/* If 32-bit mode and mod selects for memory, this is not vex */
if (X64_MODE(di) || TESTALL(MODRM_BYTE(3, 0, 0), *pc))
idx = 1;
else
idx = 0;
info = &vex_prefix_extensions[info->code][idx];
} else if (info->type == XOP_PREFIX_EXT) {
/* If m-mmm (what AMD calls "map_select") < 8, this is not vex */
if ((*pc & 0x1f) < 0x8)
idx = 0;
else
idx = 1;
info = &xop_prefix_extensions[info->code][idx];
} else
CLIENT_ASSERT(false, "internal vex decoding error");
if (idx == 0) {
/* not vex */
*ret_info = info;
*is_vex = false;
return pc;
}
*is_vex = true;
if (TESTANY(PREFIX_REX_ALL | PREFIX_LOCK, di->prefixes) || di->data_prefix ||
di->rep_prefix || di->repne_prefix) {
/* #UD if combined w/ VEX prefix */
*ret_info = &invalid_instr;
return pc;
}
/* read 2nd vex byte */
instr_byte = *pc;
pc++;
if (info->code == PREFIX_VEX_2B) {
CLIENT_ASSERT(info->type == PREFIX, "internal vex decoding error");
/* fields are: R, vvvv, L, PP. R is inverted. */
vex_last = instr_byte;
if (!TEST(0x80, vex_last))
di->prefixes |= PREFIX_REX_R;
/* 2-byte vex implies leading 0x0f */
*ret_info = &escape_instr;
/* rest are shared w/ 3-byte form's final byte */
} else if (info->code == PREFIX_VEX_3B || info->code == PREFIX_XOP) {
byte vex_mm;
CLIENT_ASSERT(info->type == PREFIX, "internal vex decoding error");
/* fields are: R, X, B, m-mmmm. R, X, and B are inverted. */
if (!TEST(0x80, instr_byte))
di->prefixes |= PREFIX_REX_R;
if (!TEST(0x40, instr_byte))
di->prefixes |= PREFIX_REX_X;
if (!TEST(0x20, instr_byte))
di->prefixes |= PREFIX_REX_B;
vex_mm = instr_byte & 0x1f;
/* our strategy is to decode through the regular tables w/ a vex-encoded
* flag, to match Intel manuals and vex implicit-prefix flags
*/
if (info->code == PREFIX_VEX_3B) {
if (vex_mm == 1) {
*ret_info = &escape_instr;
} else if (vex_mm == 2) {
*ret_info = &escape_38_instr;
} else if (vex_mm == 3) {
*ret_info = &escape_3a_instr;
} else {
/* #UD: reserved for future use */
*ret_info = &invalid_instr;
return pc;
}
} else {
/* xop */
if (vex_mm == 0x8) {
*ret_info = &xop_8_instr;
} else if (vex_mm == 0x9) {
*ret_info = &xop_9_instr;
} else if (vex_mm == 0xa) {
*ret_info = &xop_a_instr;
} else {
/* #UD: reserved for future use */
*ret_info = &invalid_instr;
return pc;
}
}
/* read 3rd vex byte */
vex_last = *pc;
pc++;
/* fields are: W, vvvv, L, PP */
/* Intel docs say vex.W1 behaves just like rex.w except in cases
* where rex.w is ignored, so no need for a PREFIX_VEX_W flag
*/
if (TEST(0x80, vex_last))
di->prefixes |= PREFIX_REX_W;
/* rest are shared w/ 2-byte form's final byte */
} else
CLIENT_ASSERT(false, "internal vex decoding error");
/* shared vex fields */
vex_pp = vex_last & 0x03;
di->vex_vvvv = (vex_last & 0x78) >> 3;
if (TEST(0x04, vex_last))
di->prefixes |= PREFIX_VEX_L;
if (vex_pp == 0x1)
di->data_prefix = true;
else if (vex_pp == 0x2)
di->rep_prefix = true;
else if (vex_pp == 0x3)
di->repne_prefix = true;
di->vex_encoded = true;
return pc;
}
/* Given the potential first evex byte at pc, reads any subsequent evex
* bytes (and any prefix bytes) and sets the appropriate prefix flags in di.
* Sets info to the entry for the first opcode byte, and pc to point past
* the first opcode byte.
*/
static byte *
read_evex(byte *pc, decode_info_t *di, byte instr_byte,
const instr_info_t **ret_info INOUT, bool *is_evex)
{
const instr_info_t *info;
byte prefix_byte = 0, evex_pp = 0;
ASSERT(ret_info != NULL && *ret_info != NULL && is_evex != NULL);
info = *ret_info;
CLIENT_ASSERT(info->type == EVEX_PREFIX_EXT, "internal evex decoding error");
/* If 32-bit mode and mod selects for memory, this is not evex */
if (X64_MODE(di) || TESTALL(MODRM_BYTE(3, 0, 0), *pc)) {
/* P[3:2] must be 0 and P[10] must be 1, otherwise #UD */
if (TEST(0xC, *pc) || !TEST(0x04, *(pc + 1))) {
*ret_info = &invalid_instr;
return pc;
}
*is_evex = true;
#if !defined(STANDALONE_DECODER)
char pc_addr[IF_X64_ELSE(20, 12)];
snprintf(pc_addr, BUFFER_SIZE_ELEMENTS(pc_addr), PFX, pc);
NULL_TERMINATE_BUFFER(pc_addr);
DO_ONCE(SYSLOG(SYSLOG_ERROR, AVX_512_SUPPORT_INCOMPLETE, 2,
get_application_name(), get_application_pid(), pc_addr));
#endif
info = &evex_prefix_extensions[0][1];
} else {
/* not evex */
*is_evex = false;
*ret_info = &evex_prefix_extensions[0][0];
return pc;
}
CLIENT_ASSERT(info->code == PREFIX_EVEX, "internal evex decoding error");
/* read 2nd evex byte */
instr_byte = *pc;
prefix_byte = instr_byte;
pc++;
if (TESTANY(PREFIX_REX_ALL | PREFIX_LOCK, di->prefixes) || di->data_prefix ||
di->rep_prefix || di->repne_prefix) {
/* #UD if combined w/ EVEX prefix */
*ret_info = &invalid_instr;
return pc;
}
CLIENT_ASSERT(info->type == PREFIX, "internal evex decoding error");
/* Fields are: R, X, B, R', 00, mm. R, X, B and R' are inverted. Intel's
* Software Developer's Manual Vol-2A 2.6 AVX-512 ENCODING fails to mention
* explicitly the fact that the bits are inverted in order to make the prefix
* distinct from the bound instruction in 32-bit mode. We experimentally
* confirmed.
*/
if (!TEST(0x80, prefix_byte))
di->prefixes |= PREFIX_REX_R;
if (!TEST(0x40, prefix_byte))
di->prefixes |= PREFIX_REX_X;
if (!TEST(0x20, prefix_byte))
di->prefixes |= PREFIX_REX_B;
if (!TEST(0x10, prefix_byte))
di->prefixes |= PREFIX_EVEX_RR;
byte evex_mm = instr_byte & 0x3;
if (evex_mm == 1) {
*ret_info = &escape_instr;
} else if (evex_mm == 2) {
*ret_info = &escape_38_instr;
} else if (evex_mm == 3) {
*ret_info = &escape_3a_instr;
} else {
/* #UD: reserved for future use */
*ret_info = &invalid_instr;
return pc;
}
/* read 3rd evex byte */
prefix_byte = *pc;
pc++;
/* fields are: W, vvvv, 1, PP */
if (TEST(0x80, prefix_byte)) {
di->prefixes |= PREFIX_REX_W;
}
evex_pp = prefix_byte & 0x03;
di->evex_vvvv = (prefix_byte & 0x78) >> 3;
if (evex_pp == 0x1)
di->data_prefix = true;
else if (evex_pp == 0x2)
di->rep_prefix = true;
else if (evex_pp == 0x3)
di->repne_prefix = true;
/* read 4th evex byte */
prefix_byte = *pc;
pc++;
/* fields are: z, L', L, b, V' and aaa */
if (TEST(0x80, prefix_byte))
di->prefixes |= PREFIX_EVEX_z;
if (TEST(0x40, prefix_byte))
di->prefixes |= PREFIX_EVEX_LL;
if (TEST(0x20, prefix_byte))
di->prefixes |= PREFIX_VEX_L;
if (TEST(0x10, prefix_byte))
di->prefixes |= PREFIX_EVEX_b;
if (!TEST(0x08, prefix_byte))
di->prefixes |= PREFIX_EVEX_VV;
di->evex_aaa = prefix_byte & 0x07;
di->evex_encoded = true;
return pc;
}
/* Given an instr_info_t PREFIX_EXT entry, reads the next entry based on the prefixes.
* Note that this function does not initialize the opcode field in \p di but is set in
* \p info->type.
*/
static inline const instr_info_t *
read_prefix_ext(const instr_info_t *info, decode_info_t *di)
{
/* discard old info, get new one */
int code = (int)info->code;
int idx = (di->rep_prefix ? 1 : (di->data_prefix ? 2 : (di->repne_prefix ? 3 : 0)));
if (di->vex_encoded)
idx += 4;
else if (di->evex_encoded)
idx += 8;
info = &prefix_extensions[code][idx];
if (info->type == INVALID && !DYNAMO_OPTION(decode_strict)) {
/* i#1118: some of these seem to not be invalid with
* prefixes that land in blank slots in the decode tables.
* Though it seems to only be btc, bsf, and bsr (the SSE*
* instrs really do seem invalid when given unlisted prefixes),
* we'd rather err on the side of treating as valid, which is
* after all what gdb and dumpbin list. Even if these
* fault when executed, we know the length, so there's no
* downside to listing as valid, for DR anyway.
* Users of drdecodelib may want to be more aggressive: hence the
* -decode_strict option.
*/
/* Take the base entry w/o prefixes and keep the prefixes */
if (di->evex_encoded) {
/* i#3713/i#1312: Raise an error for investigation, but don't assert b/c
* we need to support decoding non-code for drdecode, etc.
*/
SYSLOG_INTERNAL_ERROR_ONCE("Possible unsupported evex encoding.");
}
info = &prefix_extensions[code][0 + (di->vex_encoded ? 4 : 0)];
} else if (di->rep_prefix)
di->rep_prefix = false;
else if (di->repne_prefix)
di->repne_prefix = false;
if (di->data_prefix &&
/* Don't remove it if the entry doesn't list 0x66:
* e.g., OP_bsr (i#1118).
*/
(info->opcode >> 24) == DATA_PREFIX_OPCODE)
di->data_prefix = false;
if (info->type == REX_B_EXT) {
/* discard old info, get new one */
code = (int)info->code;
idx = (TEST(PREFIX_REX_B, di->prefixes) ? 1 : 0);
info = &rex_b_extensions[code][idx];
}
return info;
}
/* Disassembles the instruction at pc into the data structures ret_info
* and di. Does NOT set or read di->len.
* Returns a pointer to the pc of the next instruction.
* If just_opcode is true, does not decode the immeds and returns NULL
* (you must call decode_next_pc to get the next pc, but that's faster
* than decoding the immeds)
* Returns NULL on an invalid instruction
*/
static byte *
read_instruction(byte *pc, byte *orig_pc, const instr_info_t **ret_info,
decode_info_t *di, bool just_opcode _IF_DEBUG(bool report_invalid))
{
DEBUG_DECLARE(byte *post_suffix_pc = NULL;)
byte instr_byte;
const instr_info_t *info;
bool vex_noprefix = false;
bool evex_noprefix = false;
/* initialize di */
/* though we only need di->start_pc for full decode rip-rel (and
* there only post-read_instruction()) and decode_from_copy(), and
* di->orig_pc only for decode_from_copy(), we assume that
* high-perf decoding uses decode_cti() and live w/ the extra
* writes here for decode_opcode() and decode_eflags_usage().
*/
di->start_pc = pc;
di->orig_pc = orig_pc;
di->size_immed = OPSZ_NA;
di->size_immed2 = OPSZ_NA;
di->seg_override = REG_NULL;
di->data_prefix = false;
di->rep_prefix = false;
di->repne_prefix = false;
di->vex_encoded = false;
di->evex_encoded = false;
/* FIXME: set data and addr sizes to current mode
* for now I assume always 32-bit mode (or 64 for X64_MODE(di))!
*/
di->prefixes = 0;
do {
instr_byte = *pc;
pc++;
info = &first_byte[instr_byte];
if (info->type == X64_EXT) {
/* discard old info, get new one */
info = &x64_extensions[info->code][X64_MODE(di) ? 1 : 0];
} else if (info->type == VEX_PREFIX_EXT || info->type == XOP_PREFIX_EXT) {
bool is_vex = false; /* or xop */
pc = read_vex(pc, di, instr_byte, &info, &is_vex);
/* if read_vex changes info, leave this loop */
if (info->type != VEX_PREFIX_EXT && info->type != XOP_PREFIX_EXT)
break;
else {
if (is_vex)
vex_noprefix = true; /* staying in loop, but ensure no prefixes */
continue;
}
} else if (info->type == EVEX_PREFIX_EXT) {
bool is_evex = false;
pc = read_evex(pc, di, instr_byte, &info, &is_evex);
/* if read_evex changes info, leave this loop */
if (info->type != EVEX_PREFIX_EXT)
break;
else {
if (is_evex)
evex_noprefix = true; /* staying in loop, but ensure no prefixes */
continue;
}
}
if (info->type == PREFIX) {
if (vex_noprefix || evex_noprefix) {
/* VEX/EVEX prefix must be last */
info = &invalid_instr;
break;
}
if (TESTANY(PREFIX_REX_ALL, di->prefixes)) {
/* rex.* must come after all other prefixes (including those that are
* part of the opcode, xref PR 271878): so discard them if before
* matching the behavior of decode_sizeof(). This in effect nops
* improperly placed rex prefixes which (xref PR 241563 and Intel Manual
* 2A 2.2.1) is the correct thing to do. NOTE - windbg shows early bytes
* as ??, objdump as their prefix names, separate from the next instr.
*/
di->prefixes &= ~PREFIX_REX_ALL;
}
if (info->code == PREFIX_REP) {
/* see if used as part of opcode before considering prefix */
di->rep_prefix = true;
} else if (info->code == PREFIX_REPNE) {
/* see if used as part of opcode before considering prefix */
di->repne_prefix = true;
} else if (REG_START_SEGMENT <= info->code &&
info->code <= REG_STOP_SEGMENT) {
CLIENT_ASSERT_TRUNCATE(di->seg_override, ushort, info->code,
"decode error: invalid segment override");
di->seg_override = (reg_id_t)info->code;
} else if (info->code == PREFIX_DATA) {
/* see if used as part of opcode before considering prefix */
di->data_prefix = true;
} else if (TESTANY(PREFIX_REX_ALL | PREFIX_ADDR | PREFIX_LOCK, info->code)) {
di->prefixes |= info->code;
}
} else
break;
} while (true);
if (info->type == ESCAPE) {
/* discard first byte, move to second */
instr_byte = *pc;
pc++;
info = &second_byte[instr_byte];
}
if (info->type == ESCAPE_3BYTE_38 || info->type == ESCAPE_3BYTE_3a) {
/* discard second byte, move to third */
instr_byte = *pc;
pc++;
if (info->type == ESCAPE_3BYTE_38)
info = &third_byte_38[third_byte_38_index[instr_byte]];
else
info = &third_byte_3a[third_byte_3a_index[instr_byte]];
} else if (info->type == XOP_8_EXT || info->type == XOP_9_EXT ||
info->type == XOP_A_EXT) {
/* discard second byte, move to third */
int idx = 0;
instr_byte = *pc;
pc++;
if (info->type == XOP_8_EXT)
idx = xop_8_index[instr_byte];
else if (info->type == XOP_9_EXT)
idx = xop_9_index[instr_byte];
else if (info->type == XOP_A_EXT)
idx = xop_a_index[instr_byte];
else
CLIENT_ASSERT(false, "internal invalid XOP type");
info = &xop_extensions[idx];
}
/* all FLOAT_EXT and PREFIX_EXT (except nop & pause) and EXTENSION need modrm,
* get it now
*/
if ((info->flags & HAS_MODRM) != 0)
pc = read_modrm(pc, di);
if (info->type == FLOAT_EXT) {
if (di->modrm <= 0xbf) {
int offs = (instr_byte - 0xd8) * 8 + di->reg;
info = &float_low_modrm[offs];
} else {
int offs1 = (instr_byte - 0xd8);
int offs2 = di->modrm - 0xc0;
info = &float_high_modrm[offs1][offs2];
}
} else if (info->type == REP_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (di->rep_prefix ? 2 : 0);
info = &rep_extensions[code][idx];
if (di->rep_prefix)
di->rep_prefix = false;
} else if (info->type == REPNE_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (di->rep_prefix ? 2 : (di->repne_prefix ? 4 : 0));
info = &repne_extensions[code][idx];
di->rep_prefix = false;
di->repne_prefix = false;
} else if (info->type == EXTENSION) {
/* discard old info, get new one */
info = &base_extensions[info->code][di->reg];
/* absurd cases of using prefix on top of reg opcode extension
* (pslldq, psrldq) => PREFIX_EXT can happen after here,
* and MOD_EXT after that
*/
} else if (info->type == SUFFIX_EXT) {
/* Discard old info, get new one for complete opcode, which includes
* a suffix byte where an immed would be (yes, ugly!).
* We should have already read in the modrm (+ sib).
*/
CLIENT_ASSERT(TEST(HAS_MODRM, info->flags), "decode error on 3DNow instr");
info = &suffix_extensions[suffix_index[*pc]];
pc++;
DEBUG_DECLARE(post_suffix_pc = pc;)
} else if (info->type == VEX_L_EXT) {
/* TODO i#1312: We probably need to extend this table for EVEX. In this case,
* rename to e_vex_L_extensions or set up a new table?
*/
/* discard old info, get new one */
int code = (int)info->code;
int idx = (di->vex_encoded) ? (TEST(PREFIX_VEX_L, di->prefixes) ? 2 : 1) : 0;
info = &vex_L_extensions[code][idx];
} else if (info->type == VEX_W_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (TEST(PREFIX_REX_W, di->prefixes) ? 1 : 0);
info = &vex_W_extensions[code][idx];
} else if (info->type == EVEX_W_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (TEST(PREFIX_REX_W, di->prefixes) ? 1 : 0);
info = &evex_W_extensions[code][idx];
}
/* can occur AFTER above checks (EXTENSION, in particular) */
if (info->type == PREFIX_EXT) {
/* discard old info, get new one */
info = read_prefix_ext(info, di);
}
/* can occur AFTER above checks (PREFIX_EXT, in particular) */
if (info->type == MOD_EXT) {
info = &mod_extensions[info->code][(di->mod == 3) ? 1 : 0];
/* Yes, we have yet another layer, thanks to Intel's poor choice
* in opcodes -- why didn't they fill out the PREFIX_EXT space?
*/
if (info->type == RM_EXT) {
info = &rm_extensions[info->code][di->rm];
}
/* We have to support prefix before mod, and mod before prefix */
if (info->type == PREFIX_EXT) {
info = read_prefix_ext(info, di);
}
}
/* can occur AFTER above checks (MOD_EXT, in particular) */
if (info->type == E_VEX_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = 0;
if (di->vex_encoded)
idx = 1;
else if (di->evex_encoded)
idx = 2;
info = &e_vex_extensions[code][idx];
}
/* can occur AFTER above checks (EXTENSION, in particular) */
if (info->type == PREFIX_EXT) {
/* discard old info, get new one */
info = read_prefix_ext(info, di);
}
/* can occur AFTER above checks (MOD_EXT, in particular) */
if (info->type == REX_W_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (TEST(PREFIX_REX_W, di->prefixes) ? 1 : 0);
info = &rex_w_extensions[code][idx];
} else if (info->type == VEX_L_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (di->vex_encoded) ? (TEST(PREFIX_VEX_L, di->prefixes) ? 2 : 1) : 0;
info = &vex_L_extensions[code][idx];
} else if (info->type == VEX_W_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (TEST(PREFIX_REX_W, di->prefixes) ? 1 : 0);
info = &vex_W_extensions[code][idx];
} else if (info->type == EVEX_W_EXT) {
/* discard old info, get new one */
int code = (int)info->code;
int idx = (TEST(PREFIX_REX_W, di->prefixes) ? 1 : 0);
info = &evex_W_extensions[code][idx];
}
if (TEST(REQUIRES_PREFIX, info->flags)) {
byte required = (byte)(info->opcode >> 24);
bool *prefix_var = NULL;
if (required == 0) { /* cannot have a prefix */
if (prefix_var != NULL) {
/* invalid instr */
info = NULL;
}
} else {
CLIENT_ASSERT(info->opcode > 0xffffff, "decode error in SSSE3/SSE4 instr");
if (required == DATA_PREFIX_OPCODE)
prefix_var = &di->data_prefix;
else if (required == REPNE_PREFIX_OPCODE)
prefix_var = &di->repne_prefix;
else if (required == REP_PREFIX_OPCODE)
prefix_var = &di->rep_prefix;
else
CLIENT_ASSERT(false, "internal required-prefix error");
if (prefix_var == NULL || !*prefix_var) {
/* Invalid instr. TODO: have processor w/ SSE4, confirm that
* an exception really is raised.
*/
info = NULL;
} else
*prefix_var = false;
}
}
/* we go through regular tables for vex but only some are valid w/ vex */
if (info != NULL && di->vex_encoded) {
if (!TEST(REQUIRES_VEX, info->flags))
info = NULL; /* invalid encoding */
else if (TEST(REQUIRES_VEX_L_0, info->flags) && TEST(PREFIX_VEX_L, di->prefixes))
info = NULL; /* invalid encoding */
} else if (info != NULL && !di->vex_encoded && TEST(REQUIRES_VEX, info->flags)) {
info = NULL; /* invalid encoding */
} else if (info != NULL && di->evex_encoded) {
if (!TEST(REQUIRES_EVEX, info->flags))
info = NULL; /* invalid encoding */
else if (TEST(REQUIRES_VEX_L_0, info->flags) && TEST(PREFIX_VEX_L, di->prefixes))
info = NULL; /* invalid encoding */
else if (TEST(REQUIRES_EVEX_LL_0, info->flags) &&
TEST(PREFIX_EVEX_LL, di->prefixes))
info = NULL; /* invalid encoding */
} else if (info != NULL && !di->evex_encoded && TEST(REQUIRES_EVEX, info->flags))
info = NULL; /* invalid encoding */
/* XXX: not currently marking these cases as invalid instructions:
* - if no TYPE_H:
* "Note: In VEX-encoded versions, VEX.vvvv is reserved and must be 1111b otherwise
* instructions will #UD."
* - "an attempt to execute VTESTPS with VEX.W=1 will cause #UD."
* and similar for VEX.W.
*/
/* at this point should be an instruction, so type should be an OP_ constant */
if (info == NULL || info == &invalid_instr || info->type < OP_FIRST ||
info->type > OP_LAST || (X64_MODE(di) && TEST(X64_INVALID, info->flags)) ||
(!X64_MODE(di) && TEST(X86_INVALID, info->flags))) {
/* invalid instruction: up to caller to decide what to do with it */
/* FIXME case 10672: provide a runtime option to specify new
* instruction formats */
DODEBUG({
/* don't report when decoding DR addresses, as we sometimes try to
* decode backward (e.g., interrupted_inlined_syscall(): PR 605161)
* XXX: better to pass in a flag when decoding that we are
* being speculative!
*/
if (report_invalid && !is_dynamo_address(di->start_pc)) {
SYSLOG_INTERNAL_WARNING_ONCE("Invalid opcode encountered");
if (info != NULL && info->type == INVALID) {
LOG(THREAD_GET, LOG_ALL, 1, "Invalid opcode @" PFX ": 0x%x\n",
di->start_pc, info->opcode);
} else {
int i;
dcontext_t *dcontext = get_thread_private_dcontext();
IF_X64(bool old_mode = set_x86_mode(dcontext, di->x86_mode);)
int sz = decode_sizeof(dcontext, di->start_pc, NULL _IF_X64(NULL));
IF_X64(set_x86_mode(dcontext, old_mode));
LOG(THREAD_GET, LOG_ALL, 1,
"Error decoding " PFX " == ", di->start_pc);
for (i = 0; i < sz; i++) {
LOG(THREAD_GET, LOG_ALL, 1, "0x%x ", *(di->start_pc + i));
}
LOG(THREAD_GET, LOG_ALL, 1, "\n");
}
}
});
*ret_info = &invalid_instr;
return NULL;
}
#ifdef INTERNAL
DODEBUG({ /* rep & repne should have been completely handled by now */
/* processor will typically ignore extra prefixes, but we log this
* internally in case it's our decode messing up instead of weird app instrs
*/
bool spurious = report_invalid && (di->rep_prefix || di->repne_prefix);
if (spurious) {
if (di->rep_prefix &&
/* case 6861: AMD64 opt: "rep ret" used if br tgt or after cbr */
pc == di->start_pc + 2 && *(di->start_pc + 1) == RAW_OPCODE_ret)
spurious = false;
if (di->repne_prefix) {
/* i#1899: MPX puts repne prior to branches. We ignore here until
* we have full MPX decoding support (i#1312).
*/
/* XXX: We assume the x86 instr_is_* routines only need the opcode.
* That is not true for ARM.
*/
instr_t inst;
inst.opcode = info->type;
if (instr_is_cti(&inst))
spurious = false;
}
}
if (spurious) {
char bytes[17 * 3];
int i;
dcontext_t *dcontext = get_thread_private_dcontext();
IF_X64(bool old_mode = set_x86_mode(dcontext, di->x86_mode);)
int sz = decode_sizeof(dcontext, di->start_pc, NULL _IF_X64(NULL));
IF_X64(set_x86_mode(dcontext, old_mode));
CLIENT_ASSERT(sz <= 17, "decode rep/repne error: unsupported opcode?");
for (i = 0; i < sz; i++)
snprintf(&bytes[i * 3], 3, "%02x ", *(di->start_pc + i));
bytes[sz * 3 - 1] = '\0'; /* -1 to kill trailing space */
SYSLOG_INTERNAL_WARNING_ONCE(
"spurious rep/repne prefix @" PFX " (%s): ", di->start_pc, bytes);
}
});
#endif
/* if just want opcode, stop here! faster for caller to
* separately call decode_next_pc than for us to decode immeds!
*/
if (just_opcode) {
*ret_info = info;
return NULL;
}
if (di->data_prefix) {
/* prefix was not part of opcode, it's a real prefix */
/* From Intel manual:
* "For non-byte operations: if a 66H prefix is used with
* prefix (REX.W = 1), 66H is ignored."
* That means non-byte-specific operations, for which 66H is
* ignored as well, right?
* Xref PR 593593.
* Note that this means we could assert or remove some of
* the "rex.w trumps data prefix" logic elsewhere in this file.
*/
if (TEST(PREFIX_REX_W, di->prefixes)) {
LOG(THREAD_GET, LOG_ALL, 3, "Ignoring 0x66 in presence of rex.w @" PFX "\n",
di->start_pc);
} else {
di->prefixes |= PREFIX_DATA;
}
}
if ((di->repne_prefix || di->rep_prefix) &&
(TEST(PREFIX_LOCK, di->prefixes) ||
/* xrelease can go on non-0xa3 mov_st w/o lock prefix */
(di->repne_prefix && info->type == OP_mov_st &&
(info->opcode & 0xa30000) != 0xa30000))) {
/* we don't go so far as to ensure the mov_st is of the right type */
if (di->repne_prefix)
di->prefixes |= PREFIX_XACQUIRE;
if (di->rep_prefix)
di->prefixes |= PREFIX_XRELEASE;
}
/* read any trailing immediate bytes */
if (info->dst1_type != TYPE_NONE)
pc = read_operand(pc, di, info->dst1_type, info->dst1_size);
if (info->dst2_type != TYPE_NONE)
pc = read_operand(pc, di, info->dst2_type, info->dst2_size);
if (info->src1_type != TYPE_NONE)
pc = read_operand(pc, di, info->src1_type, info->src1_size);
if (info->src2_type != TYPE_NONE)
pc = read_operand(pc, di, info->src2_type, info->src2_size);
if (info->src3_type != TYPE_NONE)
pc = read_operand(pc, di, info->src3_type, info->src3_size);
if (info->type == SUFFIX_EXT) {
/* Shouldn't be any more bytes (immed bytes) read after the modrm+suffix! */
DODEBUG({ CLIENT_ASSERT(pc == post_suffix_pc, "decode error on 3DNow instr"); });
}
/* return values */
*ret_info = info;
return pc;
}
/****************************************************************************
* Full decoding
*/
/* Caller must check for rex.{r,b} extensions before calling this routine */
static reg_id_t
reg8_alternative(decode_info_t *di, reg_id_t reg, uint prefixes)
{
if (X64_MODE(di) && reg >= REG_START_x86_8 && reg <= REG_STOP_x86_8 &&
TESTANY(PREFIX_REX_ALL, prefixes)) {
/* for x64, if any rex prefix exists, we use SPL...SDL instead of
* AH..BH (this seems to be the only use of 0x40 == PREFIX_REX_GENERAL)
*/
return (reg - REG_START_x86_8 + REG_START_x64_8);
}
return reg;
}
/* which register within modrm, vex or evex we're decoding */
typedef enum {
DECODE_REG_REG,
DECODE_REG_BASE,
DECODE_REG_INDEX,
DECODE_REG_RM,
DECODE_REG_VEX,
DECODE_REG_EVEX,
DECODE_REG_OPMASK,
} decode_reg_t;
/* Pass in the raw opsize, NOT a size passed through resolve_variable_size(),
* to avoid allowing OPSZ_6_irex10_short4 w/ data16.
* To create a sub-sized register, caller must set size separately.
*/
static reg_id_t
decode_reg(decode_reg_t which_reg, decode_info_t *di, byte optype, opnd_size_t opsize)
{
bool extend = false;
bool avx512_extend = false;
byte reg = 0;
switch (which_reg) {
case DECODE_REG_REG:
reg = di->reg;
extend = X64_MODE(di) && TEST(PREFIX_REX_R, di->prefixes);
avx512_extend = TEST(PREFIX_EVEX_RR, di->prefixes);
break;
case DECODE_REG_BASE:
reg = di->base;
extend = X64_MODE(di) && TEST(PREFIX_REX_B, di->prefixes);
break;
case DECODE_REG_INDEX:
reg = di->index;
extend = X64_MODE(di) && TEST(PREFIX_REX_X, di->prefixes);
avx512_extend = TEST(PREFIX_EVEX_VV, di->prefixes);
break;
case DECODE_REG_RM:
reg = di->rm;
extend = X64_MODE(di) && TEST(PREFIX_REX_B, di->prefixes);
if (di->evex_encoded)
avx512_extend = TEST(PREFIX_REX_X, di->prefixes);
break;
case DECODE_REG_VEX:
/* Part of XOP/AVX: vex.vvvv selects general-purpose register.
* It has 4 bits so no separate prefix bit is needed to extend.
*/
reg = (~di->vex_vvvv) & 0xf; /* bit-inverted */
extend = false;
avx512_extend = false;
break;
case DECODE_REG_EVEX:
/* Part of AVX-512: evex.vvvv selects general-purpose register.
* It has 4 bits so no separate prefix bit is needed to extend.
* Intel's Software Developer's Manual Vol-2A 2.6 AVX-512 ENCODING fails to
* mention the fact that the bits are inverted in the EVEX prefix. Experimentally
* confirmed.
*/
reg = (~di->evex_vvvv) & 0xf; /* bit-inverted */
extend = false;
avx512_extend = TEST(PREFIX_EVEX_VV, di->prefixes); /* bit-inverted */
break;
case DECODE_REG_OPMASK:
/* Part of AVX-512: evex.aaa selects opmask register. */
reg = di->evex_aaa & 0x7;
break;
default: CLIENT_ASSERT(false, "internal unknown reg error");
}
switch (optype) {
case TYPE_P:
case TYPE_Q:
case TYPE_P_MODRM: return (REG_START_MMX + reg); /* no x64 extensions */
case TYPE_V:
case TYPE_W:
case TYPE_V_MODRM:
case TYPE_VSIB: {
reg_id_t extend_reg = extend ? reg + 8 : reg;
extend_reg = avx512_extend ? extend_reg + 16 : extend_reg;
bool operand_is_zmm = TEST(PREFIX_EVEX_LL, di->prefixes) &&
expand_subreg_size(opsize) != OPSZ_16 &&
expand_subreg_size(opsize) != OPSZ_32;
/* Not only do we use this for VEX .LIG and EVEX .LIG (where raw reg is
* either OPSZ_16 or OPSZ_16_vex32 or OPSZ_32 or OPSZ_vex32_evex64) but
* also for VSIB which currently does not get up to OPSZ_16 so we can
* use this negative check.
* XXX i#1312: vgather/vscatter VSIB addressing may be OPSZ_16?
* For EVEX .LIG, raw reg will be able to be OPSZ_64 or
* OPSZ_16_vex32_evex64.
* XXX i#1312: improve this code here, it is not very robust. For AVX-512, this
* relies on the fact that cases where EVEX.LL' == 1 and register is not zmm, the
* expand_subreg_size is OPSZ_16 or OPSZ_32. The VEX OPSZ_16 case is also fragile.
*/
bool operand_is_ymm = (TEST(PREFIX_EVEX_LL, di->prefixes) &&
expand_subreg_size(opsize) == OPSZ_32) ||
(TEST(PREFIX_VEX_L, di->prefixes) && expand_subreg_size(opsize) != OPSZ_16);
if (operand_is_ymm && operand_is_zmm) {
/* i#3713/i#1312: Raise an error for investigation, but don't assert b/c
* we need to support decoding non-code for drdecode, etc.
*/
SYSLOG_INTERNAL_ERROR_ONCE("Invalid VSIB register encoding encountered");
}
return (operand_is_zmm ? (DR_REG_START_ZMM + extend_reg)
: (operand_is_ymm ? (REG_START_YMM + extend_reg)
: (REG_START_XMM + extend_reg)));
}
case TYPE_S:
if (reg >= 6)
return REG_NULL;
return (REG_START_SEGMENT + reg);
case TYPE_C: return (extend ? (REG_START_CR + 8 + reg) : (REG_START_CR + reg));
case TYPE_D: return (extend ? (REG_START_DR + 8 + reg) : (REG_START_DR + reg));
case TYPE_K_REG:
case TYPE_K_MODRM:
case TYPE_K_MODRM_R:
case TYPE_K_VEX:
case TYPE_K_EVEX:
/* XXX i#3719: DECODE_REG_{,E}VEX above produce a number up to 15, but
* there are only 8 K registers! For now truncating at 7.
*/
return DR_REG_START_OPMASK + (reg & 7);
case TYPE_E:
case TYPE_G:
case TYPE_R:
case TYPE_B:
case TYPE_M:
case TYPE_INDIR_E:
case TYPE_FLOATMEM:
/* GPR: fall-through since variable subset of full register */
break;
default: CLIENT_ASSERT(false, "internal unknown reg error");
}
/* Do not allow a register for 'p' or 'a' types. FIXME: maybe *_far_ind_* should
* use TYPE_INDIR_M instead of TYPE_INDIR_E? What other things are going to turn
* into asserts or crashes instead of invalid instrs based on events as fragile
* as these decode routines moving sizes around?
*/
if (opsize != OPSZ_6_irex10_short4 && opsize != OPSZ_8_short4)
opsize = resolve_variable_size(di, opsize, true);
switch (opsize) {
case OPSZ_1:
if (extend)
return (REG_START_8 + 8 + reg);
else
return reg8_alternative(di, REG_START_8 + reg, di->prefixes);
case OPSZ_2: return (extend ? (REG_START_16 + 8 + reg) : (REG_START_16 + reg));
case OPSZ_4: return (extend ? (REG_START_32 + 8 + reg) : (REG_START_32 + reg));
case OPSZ_8: return (extend ? (REG_START_64 + 8 + reg) : (REG_START_64 + reg));
case OPSZ_6:
case OPSZ_6_irex10_short4:
case OPSZ_8_short4:
/* invalid: no register of size p */
return REG_NULL;
default:
/* ok to assert since params controlled by us */
CLIENT_ASSERT(false, "decode error: unknown register size");
return REG_NULL;
}
}
static bool
decode_modrm(decode_info_t *di, byte optype, opnd_size_t opsize, opnd_t *reg_opnd,
opnd_t *rm_opnd)
{
/* for x64, addr prefix affects only base/index and truncates final addr:
* modrm + sib table is the same
*/
bool addr16 = !X64_MODE(di) && TEST(PREFIX_ADDR, di->prefixes);
if (reg_opnd != NULL) {
reg_id_t reg = decode_reg(DECODE_REG_REG, di, optype, opsize);
if (reg == REG_NULL)
return false;
*reg_opnd = opnd_create_reg(reg);
opnd_set_size(reg_opnd, resolve_variable_size(di, opsize, true /*is reg*/));
}
if (rm_opnd != NULL) {
reg_id_t base_reg = REG_NULL;
int disp = 0;
reg_id_t index_reg = REG_NULL;
int scale = 0;
char memtype = (optype == TYPE_VSIB ? TYPE_VSIB : TYPE_M);
opnd_size_t memsize = resolve_addr_size(di);
bool encode_zero_disp, force_full_disp;
if (di->has_disp)
disp = di->disp;
else
disp = 0;
if (di->has_sib) {
CLIENT_ASSERT(!addr16, "decode error: x86 addr16 cannot have a SIB byte");
if (di->index == 4 &&
/* rex.x enables r12 as index */
(!X64_MODE(di) || !TEST(PREFIX_REX_X, di->prefixes)) &&
optype != TYPE_VSIB) {
/* no scale/index */
index_reg = REG_NULL;
} else {
index_reg = decode_reg(DECODE_REG_INDEX, di, memtype, memsize);
if (index_reg == REG_NULL) {
CLIENT_ASSERT(false, "decode error: !index: internal modrm error");
return false;
}
if (di->scale == 0)
scale = 1;
else if (di->scale == 1)
scale = 2;
else if (di->scale == 2)
scale = 4;
else if (di->scale == 3)
scale = 8;
}
if (di->base == 5 && di->mod == 0) {
/* no base */
base_reg = REG_NULL;
} else {
base_reg = decode_reg(DECODE_REG_BASE, di, TYPE_M, memsize);
if (base_reg == REG_NULL) {
CLIENT_ASSERT(false, "decode error: internal modrm decode error");
return false;
}
}
} else {
if (optype == TYPE_VSIB)
return false; /* invalid w/o vsib byte */
if ((!addr16 && di->mod == 0 && di->rm == 5) ||
(addr16 && di->mod == 0 && di->rm == 6)) {
/* just absolute displacement, or rip-relative for x64 */
#ifdef X64
if (X64_MODE(di)) {
/* rip-relative: convert from relative offset to absolute target pc */
byte *addr;
CLIENT_ASSERT(di->start_pc != NULL,
"internal decode error: start pc not set");
if (di->orig_pc != di->start_pc)
addr = di->orig_pc + di->len + di->disp;
else
addr = di->start_pc + di->len + di->disp;
if (TEST(PREFIX_ADDR, di->prefixes)) {
/* Need to clear upper 32 bits.
* Debuggers do not display this truncation, though
* both Intel and AMD manuals describe it.
* I did verify it w/ actual execution.
*/
ASSERT_NOT_TESTED();
addr = (byte *)((ptr_uint_t)addr & 0xffffffff);
}
*rm_opnd = opnd_create_far_rel_addr(
di->seg_override, (void *)addr,
resolve_variable_size(di, opsize, false));
return true;
} else
#endif
base_reg = REG_NULL;
index_reg = REG_NULL;
} else if (di->mod == 3) {
/* register */
reg_id_t rm_reg = decode_reg(DECODE_REG_RM, di, optype, opsize);
if (rm_reg == REG_NULL) /* no assert since happens, e.g., ff d9 */
return false;
else {
*rm_opnd = opnd_create_reg(rm_reg);
opnd_set_size(rm_opnd,
resolve_variable_size(di, opsize, true /*is reg*/));
return true;
}
} else {
/* non-sib reg-based memory address */
if (addr16) {
/* funny order requiring custom decode */
switch (di->rm) {
case 0:
base_reg = REG_BX;
index_reg = REG_SI;
scale = 1;
break;
case 1:
base_reg = REG_BX;
index_reg = REG_DI;
scale = 1;
break;
case 2:
base_reg = REG_BP;
index_reg = REG_SI;
scale = 1;
break;
case 3:
base_reg = REG_BP;
index_reg = REG_DI;
scale = 1;
break;
case 4: base_reg = REG_SI; break;
case 5: base_reg = REG_DI; break;
case 6:
base_reg = REG_BP;
CLIENT_ASSERT(di->mod != 0,
"decode error: %bp cannot have mod 0");
break;
case 7: base_reg = REG_BX; break;
default:
CLIENT_ASSERT(false, "decode error: unknown modrm rm");
break;
}
} else {
/* single base reg */
base_reg = decode_reg(DECODE_REG_RM, di, memtype, memsize);
if (base_reg == REG_NULL) {
CLIENT_ASSERT(false,
"decode error: !base: internal modrm decode error");
return false;
}
}
}
}
/* We go ahead and preserve the force bools if the original really had a 0
* disp; up to user to unset bools when changing disp value (FIXME: should
* we auto-unset on first mod?)
*/
encode_zero_disp = di->has_disp && disp == 0 &&
/* there is no bp base without a disp */
(!addr16 || base_reg != REG_BP);
/* With evex encoding, disp8 is subject to compression and a scale factor.
* Hence, displacments not divisible by the scale factor need to be encoded
* with full displacement, no need (and actually incorrect) to "force" it.
*/
bool needs_full_disp = false;
int compressed_disp_scale = 0;
if (di->evex_encoded) {
compressed_disp_scale = decode_get_compressed_disp_scale(di);
needs_full_disp = disp % compressed_disp_scale != 0;
}
force_full_disp = !needs_full_disp && di->has_disp && disp >= INT8_MIN &&
disp <= INT8_MAX && di->mod == 2;
if (di->seg_override != REG_NULL) {
*rm_opnd = opnd_create_far_base_disp_ex(
di->seg_override, base_reg, index_reg, scale, disp,
resolve_variable_size(di, opsize, false), encode_zero_disp,
force_full_disp, TEST(PREFIX_ADDR, di->prefixes));
} else {
/* Note that OP_{jmp,call}_far_ind does NOT have a far base disp
* operand: it is a regular base disp containing 6 bytes that
* specify a segment selector and address. The opcode must be
* examined to know how to interpret those 6 bytes.
*/
if (di->evex_encoded) {
if (di->mod == 1)
disp *= compressed_disp_scale;
}
*rm_opnd = opnd_create_base_disp_ex(base_reg, index_reg, scale, disp,
resolve_variable_size(di, opsize, false),
encode_zero_disp, force_full_disp,
TEST(PREFIX_ADDR, di->prefixes));
}
}
return true;
}
static ptr_int_t
get_immed(decode_info_t *di, opnd_size_t opsize)
{
ptr_int_t val = 0;
if (di->size_immed == OPSZ_NA) {
/* ok b/c only instr_info_t fields passed */
CLIENT_ASSERT(di->size_immed2 != OPSZ_NA, "decode immediate size error");
val = di->immed2;
di->size_immed2 = OPSZ_NA; /* mark as used up */
} else {
/* ok b/c only instr_info_t fields passed */
CLIENT_ASSERT(di->size_immed != OPSZ_NA, "decode immediate size error");
val = di->immed;
di->size_immed = OPSZ_NA; /* mark as used up */
}
return val;
}
/* Also takes in reg8 for TYPE_REG_EX mov_imm */
reg_id_t
resolve_var_reg(decode_info_t *di /*IN: x86_mode, prefixes*/, reg_id_t reg32, bool addr,
bool can_shrink _IF_X64(bool default_64) _IF_X64(bool can_grow)
_IF_X64(bool extendable))
{
#ifdef X64
if (extendable && X64_MODE(di) && di->prefixes != 0 /*optimization*/) {
/* Note that Intel's table 3-1 on +r possibilities is incorrect:
* it lists rex.r, while Table 2-4 lists rex.b which is correct.
*/
if (TEST(PREFIX_REX_B, di->prefixes))
reg32 = reg32 + 8;
else
reg32 = reg8_alternative(di, reg32, di->prefixes);
}
#endif
if (addr) {
#ifdef X64
if (X64_MODE(di)) {
CLIENT_ASSERT(default_64, "addr-based size must be default 64");
if (!can_shrink || !TEST(PREFIX_ADDR, di->prefixes))
return reg_32_to_64(reg32);
/* else leave 32 (it's addr32 not addr16) */
} else
#endif
if (can_shrink && TEST(PREFIX_ADDR, di->prefixes))
return reg_32_to_16(reg32);
} else {
#ifdef X64
/* rex.w trumps data prefix */
if (X64_MODE(di) &&
((can_grow && TEST(PREFIX_REX_W, di->prefixes)) ||
(default_64 && (!can_shrink || !TEST(PREFIX_DATA, di->prefixes)))))
return reg_32_to_64(reg32);
else
#endif
if (can_shrink && TEST(PREFIX_DATA, di->prefixes))
return reg_32_to_16(reg32);
}
return reg32;
}
static reg_id_t
ds_seg(decode_info_t *di)
{
if (di->seg_override != REG_NULL) {
#ifdef X64
/* Although the AMD docs say that es,cs,ss,ds prefixes are NOT treated as
* segment override prefixes and instead as NULL prefixes, Intel docs do not
* say that, and both gdb and windbg disassemble as though the prefixes are
* taking effect. We therefore do not suppress those prefixes.
*/
#endif
return di->seg_override;
}
return SEG_DS;
}
static bool
decode_operand(decode_info_t *di, byte optype, opnd_size_t opsize, opnd_t *opnd)
{
/* resolving here, for non-reg, makes for simpler code: though the
* most common types don't need this.
*/
opnd_size_t ressize = resolve_variable_size(di, opsize, false);
switch (optype) {
case TYPE_NONE: *opnd = opnd_create_null(); return true;
case TYPE_REG:
*opnd = opnd_create_reg(opsize);
/* here and below, for all TYPE_*REG*: no need to set size as it's a GPR */
return true;
case TYPE_XREG:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
false /*!shrinkable*/
_IF_X64(true /*d64*/)
_IF_X64(false /*!growable*/)
_IF_X64(false /*!extendable*/)));
return true;
case TYPE_VAR_REG:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
true /*shrinkable*/
_IF_X64(false /*d32*/)
_IF_X64(true /*growable*/)
_IF_X64(false /*!extendable*/)));
return true;
case TYPE_VARZ_REG:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
true /*shrinkable*/
_IF_X64(false /*d32*/)
_IF_X64(false /*!growable*/)
_IF_X64(false /*!extendable*/)));
return true;
case TYPE_VAR_XREG:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
true /*shrinkable*/
_IF_X64(true /*d64*/)
_IF_X64(false /*!growable*/)
_IF_X64(false /*!extendable*/)));
return true;
case TYPE_VAR_REGX:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
false /*!shrinkable*/
_IF_X64(false /*!d64*/)
_IF_X64(true /*growable*/)
_IF_X64(false /*!extendable*/)));
return true;
case TYPE_VAR_ADDR_XREG:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, true /*addr*/,
true /*shrinkable*/
_IF_X64(true /*d64*/)
_IF_X64(false /*!growable*/)
_IF_X64(false /*!extendable*/)));
return true;
case TYPE_REG_EX:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
false /*!shrink*/
_IF_X64(false /*d32*/)
_IF_X64(false /*!growable*/)
_IF_X64(true /*extendable*/)));
return true;
case TYPE_VAR_REG_EX:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
true /*shrinkable*/
_IF_X64(false /*d32*/)
_IF_X64(true /*growable*/)
_IF_X64(true /*extendable*/)));
return true;
case TYPE_VAR_XREG_EX:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
true /*shrinkable*/
_IF_X64(true /*d64*/)
_IF_X64(false /*!growable*/)
_IF_X64(true /*extendable*/)));
return true;
case TYPE_VAR_REGX_EX:
*opnd = opnd_create_reg(resolve_var_reg(di, opsize, false /*!addr*/,
false /*!shrink*/
_IF_X64(false /*d64*/)
_IF_X64(true /*growable*/)
_IF_X64(true /*extendable*/)));
return true;
case TYPE_FLOATMEM:
case TYPE_M:
case TYPE_VSIB:
/* ensure referencing memory */
if (di->mod >= 3)
return false;
/* fall through */
case TYPE_E:
case TYPE_Q:
case TYPE_W: return decode_modrm(di, optype, opsize, NULL, opnd);
case TYPE_R:
case TYPE_P_MODRM:
case TYPE_V_MODRM:
/* ensure referencing a register */
if (di->mod != 3)
return false;
return decode_modrm(di, optype, opsize, NULL, opnd);
case TYPE_G:
case TYPE_P:
case TYPE_V:
case TYPE_S:
case TYPE_C:
case TYPE_D: return decode_modrm(di, optype, opsize, opnd, NULL);
case TYPE_I:
*opnd = opnd_create_immed_int(get_immed(di, opsize), ressize);
return true;
case TYPE_1:
CLIENT_ASSERT(opsize == OPSZ_0, "internal decode inconsistency");
*opnd = opnd_create_immed_int(1, ressize);
return true;
case TYPE_FLOATCONST:
CLIENT_ASSERT(opsize == OPSZ_0, "internal decode inconsistency");
/* i#386: avoid floating-point instructions */
*opnd = opnd_create_immed_float_for_opcode(di->opcode);
return true;
case TYPE_J:
if (di->seg_override == SEG_JCC_NOT_TAKEN || di->seg_override == SEG_JCC_TAKEN) {
/* SEG_DS - taken, pt */
/* SEG_CS - not taken, pn */
/* starting from RH9 I see code using this */
LOG(THREAD_GET, LOG_EMIT, 5, "disassemble: branch hint %s:\n",
di->seg_override == SEG_JCC_TAKEN ? "pt" : "pn");
if (di->seg_override == SEG_JCC_NOT_TAKEN)
di->prefixes |= PREFIX_JCC_NOT_TAKEN;
else
di->prefixes |= PREFIX_JCC_TAKEN;
di->seg_override = REG_NULL;
STATS_INC(num_branch_hints);
}
/* just ignore other segment prefixes -- don't assert */
*opnd = opnd_create_pc((app_pc)get_immed(di, opsize));
return true;
case TYPE_A: {
/* ok since instr_info_t fields */
CLIENT_ASSERT(!X64_MODE(di), "x64 has no type A instructions");
CLIENT_ASSERT(opsize == OPSZ_6_irex10_short4, "decode A operand error");
/* just ignore segment prefixes -- don't assert */
if (TEST(PREFIX_DATA, di->prefixes)) {
/* 4-byte immed */
ptr_int_t val = get_immed(di, opsize);
*opnd = opnd_create_far_pc((ushort)(((ptr_int_t)val & 0xffff0000) >> 16),
(app_pc)((ptr_int_t)val & 0x0000ffff));
} else {
/* 6-byte immed */
/* ok since instr_info_t fields */
CLIENT_ASSERT(di->size_immed == OPSZ_6 && di->size_immed2 == OPSZ_6,
"decode A operand 6-byte immed error");
ASSERT(CHECK_TRUNCATE_TYPE_short(di->immed));
*opnd = opnd_create_far_pc((ushort)(short)di->immed, (app_pc)di->immed2);
di->size_immed = OPSZ_NA;
di->size_immed2 = OPSZ_NA;
}
return true;
}
case TYPE_O: {
/* no modrm byte, offset follows directly */
ptr_int_t immed = get_immed(di, resolve_addr_size(di));
*opnd = opnd_create_far_abs_addr(di->seg_override, (void *)immed, ressize);
return true;
}
case TYPE_X:
/* this means the memory address DS:(E)SI */
if (!X64_MODE(di) && TEST(PREFIX_ADDR, di->prefixes)) {
*opnd =
opnd_create_far_base_disp(ds_seg(di), REG_SI, REG_NULL, 0, 0, ressize);
} else if (!X64_MODE(di) || TEST(PREFIX_ADDR, di->prefixes)) {
*opnd =
opnd_create_far_base_disp(ds_seg(di), REG_ESI, REG_NULL, 0, 0, ressize);
} else {
*opnd =
opnd_create_far_base_disp(ds_seg(di), REG_RSI, REG_NULL, 0, 0, ressize);
}
return true;
case TYPE_Y:
/* this means the memory address ES:(E)DI */
if (!X64_MODE(di) && TEST(PREFIX_ADDR, di->prefixes))
*opnd = opnd_create_far_base_disp(SEG_ES, REG_DI, REG_NULL, 0, 0, ressize);
else if (!X64_MODE(di) || TEST(PREFIX_ADDR, di->prefixes))
*opnd = opnd_create_far_base_disp(SEG_ES, REG_EDI, REG_NULL, 0, 0, ressize);
else
*opnd = opnd_create_far_base_disp(SEG_ES, REG_RDI, REG_NULL, 0, 0, ressize);
return true;
case TYPE_XLAT:
/* this means the memory address DS:(E)BX+AL */
if (!X64_MODE(di) && TEST(PREFIX_ADDR, di->prefixes))
*opnd = opnd_create_far_base_disp(ds_seg(di), REG_BX, REG_AL, 1, 0, ressize);
else if (!X64_MODE(di) || TEST(PREFIX_ADDR, di->prefixes))
*opnd = opnd_create_far_base_disp(ds_seg(di), REG_EBX, REG_AL, 1, 0, ressize);
else
*opnd = opnd_create_far_base_disp(ds_seg(di), REG_RBX, REG_AL, 1, 0, ressize);
return true;
case TYPE_MASKMOVQ:
/* this means the memory address DS:(E)DI */
if (!X64_MODE(di) && TEST(PREFIX_ADDR, di->prefixes)) {
*opnd =
opnd_create_far_base_disp(ds_seg(di), REG_DI, REG_NULL, 0, 0, ressize);
} else if (!X64_MODE(di) || TEST(PREFIX_ADDR, di->prefixes)) {
*opnd =
opnd_create_far_base_disp(ds_seg(di), REG_EDI, REG_NULL, 0, 0, ressize);
} else {
*opnd =
opnd_create_far_base_disp(ds_seg(di), REG_RDI, REG_NULL, 0, 0, ressize);
}
return true;
case TYPE_INDIR_REG:
/* FIXME: how know data size? for now just use reg size: our only use
* of this does not have a varying hardcoded reg, fortunately. */
*opnd = opnd_create_base_disp(opsize, REG_NULL, 0, 0, reg_get_size(opsize));
return true;
case TYPE_INDIR_VAR_XREG: /* indirect reg varies by ss only, base is 4x8,
* opsize varies by data16 */
case TYPE_INDIR_VAR_REG: /* indirect reg varies by ss only, base is 4x8,
* opsize varies by rex and data16 */
case TYPE_INDIR_VAR_XIREG: /* indirect reg varies by ss only, base is 4x8,
* opsize varies by data16 except on 64-bit Intel */
case TYPE_INDIR_VAR_XREG_OFFS_1: /* TYPE_INDIR_VAR_XREG + an offset */
case TYPE_INDIR_VAR_XREG_OFFS_8: /* TYPE_INDIR_VAR_XREG + an offset + scale */
case TYPE_INDIR_VAR_XREG_OFFS_N: /* TYPE_INDIR_VAR_XREG + an offset + scale */
case TYPE_INDIR_VAR_XIREG_OFFS_1: /* TYPE_INDIR_VAR_XIREG + an offset + scale */
case TYPE_INDIR_VAR_REG_OFFS_2: /* TYPE_INDIR_VAR_REG + offset + scale */
case TYPE_INDIR_VAR_XREG_SIZEx8: /* TYPE_INDIR_VAR_XREG + scale */
case TYPE_INDIR_VAR_REG_SIZEx2: /* TYPE_INDIR_VAR_REG + scale */
case TYPE_INDIR_VAR_REG_SIZEx3x5: /* TYPE_INDIR_VAR_REG + scale */
{
reg_id_t reg = resolve_var_reg(di, opsize, true /*doesn't matter*/,
false /*!shrinkable*/
_IF_X64(true /*d64*/) _IF_X64(false /*!growable*/)
_IF_X64(false /*!extendable*/));
opnd_size_t sz =
resolve_variable_size(di, indir_var_reg_size(di, optype), false /*not reg*/);
/* NOTE - needs to match size in opnd_type_ok() and instr_create.h */
*opnd = opnd_create_base_disp(
reg, REG_NULL, 0, indir_var_reg_offs_factor(optype) * opnd_size_in_bytes(sz),
sz);
return true;
}
case TYPE_INDIR_E:
/* how best mark as indirect?
* in current usage decode_modrm will be treated as indirect, becoming
* a base_disp operand, vs. an immed, which becomes a pc operand
* besides, Ap is just as indirect as i_Ep!
*/
return decode_operand(di, TYPE_E, opsize, opnd);
case TYPE_L: {
CLIENT_ASSERT(!TEST(PREFIX_EVEX_LL, di->prefixes), "XXX i#1312: unsupported.");
/* part of AVX: top 4 bits of 8-bit immed select xmm/ymm register */
ptr_int_t immed = get_immed(di, OPSZ_1);
reg_id_t reg = (reg_id_t)(immed & 0xf0) >> 4;
*opnd = opnd_create_reg(((TEST(PREFIX_VEX_L, di->prefixes) &&
/* see .LIG notes above */
expand_subreg_size(opsize) != OPSZ_16)
? REG_START_YMM
: REG_START_XMM) +
reg);
opnd_set_size(opnd, resolve_variable_size(di, opsize, true /*is reg*/));
return true;
}
case TYPE_H: {
/* As part of AVX and AVX-512, vex.vvvv selects xmm/ymm/zmm register. Note that
* vex.vvvv and evex.vvvv are a union.
*/
reg_id_t reg = (~di->vex_vvvv) & 0xf; /* bit-inverted */
if (TEST(PREFIX_EVEX_VV, di->prefixes)) {
/* This assumes that the register ranges of DR_REG_XMM, DR_REG_YMM, and
* DR_REG_ZMM are contiguous.
*/
reg += 16;
}
if (TEST(PREFIX_EVEX_LL, di->prefixes)) {
reg += DR_REG_START_ZMM;
} else if (TEST(PREFIX_VEX_L, di->prefixes) &&
/* see .LIG notes above */
expand_subreg_size(opsize) != OPSZ_16) {
reg += DR_REG_START_YMM;
} else {
reg += DR_REG_START_XMM;
}
*opnd = opnd_create_reg(reg);
opnd_set_size(opnd, resolve_variable_size(di, opsize, true /*is reg*/));
return true;
}
case TYPE_B: {
/* Part of XOP/AVX/AVX-512: vex.vvvv or evex.vvvv selects general-purpose
* register.
*/
if (di->evex_encoded)
*opnd = opnd_create_reg(decode_reg(DECODE_REG_EVEX, di, optype, opsize));
else
*opnd = opnd_create_reg(decode_reg(DECODE_REG_VEX, di, optype, opsize));
/* no need to set size as it's a GPR */
return true;
}
case TYPE_K_MODRM: {
/* part of AVX-512: modrm.rm selects opmask register or mem addr */
if (di->mod != 3) {
return decode_modrm(di, optype, opsize, NULL, opnd);
}
/* fall through*/
}
case TYPE_K_MODRM_R: {
/* part of AVX-512: modrm.rm selects opmask register */
*opnd = opnd_create_reg(decode_reg(DECODE_REG_RM, di, optype, opsize));
return true;
}
case TYPE_K_REG: {
/* part of AVX-512: modrm.reg selects opmask register */
*opnd = opnd_create_reg(decode_reg(DECODE_REG_REG, di, optype, opsize));
return true;
}
case TYPE_K_VEX: {
/* part of AVX-512: vex.vvvv selects opmask register */
*opnd = opnd_create_reg(decode_reg(DECODE_REG_VEX, di, optype, opsize));
return true;
}
case TYPE_K_EVEX: {
/* part of AVX-512: evex.aaa selects opmask register */
*opnd = opnd_create_reg(decode_reg(DECODE_REG_OPMASK, di, optype, opsize));
return true;
}
default:
/* ok to assert, types coming only from instr_info_t */
CLIENT_ASSERT(false, "decode error: unknown operand type");
}
return false;
}
dr_pred_type_t
decode_predicate_from_instr_info(uint opcode, const instr_info_t *info)
{
if (TESTANY(HAS_PRED_CC | HAS_PRED_COMPLEX, info->flags)) {
if (TEST(HAS_PRED_CC, info->flags))
return DR_PRED_O + instr_cmovcc_to_jcc(opcode) - OP_jo;
else
return DR_PRED_COMPLEX;
}
return DR_PRED_NONE;
}
/* Helper function to determine the vector length based on EVEX.L, EVEX.L'. */
static opnd_size_t
decode_get_vector_length(bool vex_l, bool evex_ll)
{
if (!vex_l && !evex_ll)
return OPSZ_16;
else if (vex_l && !evex_ll)
return OPSZ_32;
else if (!vex_l && evex_ll)
return OPSZ_64;
else {
/* i#3713/i#1312: Raise an error for investigation while we're still solidifying
* our AVX-512 decoder, but don't assert b/c we need to support decoding non-code
* for drdecode, etc.
*/
SYSLOG_INTERNAL_ERROR_ONCE("Invalid AVX-512 vector length encountered.");
}
return OPSZ_NA;
}
int
decode_get_compressed_disp_scale(decode_info_t *di)
{
dr_tuple_type_t tuple_type = di->tuple_type;
bool broadcast = TEST(PREFIX_EVEX_b, di->prefixes);
opnd_size_t input_size = di->input_size;
if (input_size == OPSZ_NA) {
if (TEST(PREFIX_REX_W, di->prefixes))
input_size = OPSZ_8;
else
input_size = OPSZ_4;
}
opnd_size_t vl = decode_get_vector_length(TEST(di->prefixes, PREFIX_VEX_L),
TEST(di->prefixes, PREFIX_EVEX_LL));
if (vl == OPSZ_NA)
return -1;
switch (tuple_type) {
case DR_TUPLE_TYPE_FV:
CLIENT_ASSERT(input_size == OPSZ_4 || input_size == OPSZ_8,
"invalid input size.");
if (broadcast) {
switch (vl) {
case OPSZ_16: return input_size == OPSZ_4 ? 4 : 8;
case OPSZ_32: return input_size == OPSZ_4 ? 4 : 8;
case OPSZ_64: return input_size == OPSZ_4 ? 4 : 8;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
} else {
switch (vl) {
case OPSZ_16: return 16;
case OPSZ_32: return 32;
case OPSZ_64: return 64;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
}
break;
case DR_TUPLE_TYPE_HV:
CLIENT_ASSERT(input_size == OPSZ_4, "invalid input size.");
if (broadcast) {
switch (vl) {
case OPSZ_16: return 4;
case OPSZ_32: return 4;
case OPSZ_64: return 4;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
} else {
switch (vl) {
case OPSZ_16: return 8;
case OPSZ_32: return 16;
case OPSZ_64: return 32;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
}
break;
case DR_TUPLE_TYPE_FVM:
switch (vl) {
case OPSZ_16: return 16;
case OPSZ_32: return 32;
case OPSZ_64: return 64;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
break;
case DR_TUPLE_TYPE_T1S:
CLIENT_ASSERT(vl == OPSZ_16 || vl == OPSZ_32 || vl == OPSZ_64,
"invalid vector length.");
if (input_size == OPSZ_1) {
return 1;
} else if (input_size == OPSZ_2) {
return 2;
} else if (input_size == OPSZ_4) {
return 4;
} else if (input_size == OPSZ_8) {
return 8;
} else {
CLIENT_ASSERT(false, "invalid input size.");
}
break;
case DR_TUPLE_TYPE_T1F:
CLIENT_ASSERT(vl == OPSZ_16 || vl == OPSZ_32 || vl == OPSZ_64,
"invalid vector length.");
if (input_size == OPSZ_4) {
return 4;
} else if (input_size == OPSZ_8) {
return 8;
} else {
CLIENT_ASSERT(false, "invalid input size.");
}
break;
case DR_TUPLE_TYPE_T2:
if (input_size == OPSZ_4) {
CLIENT_ASSERT(vl == OPSZ_16 || vl == OPSZ_32 || vl == OPSZ_64,
"invalid vector length.");
return 8;
} else if (input_size == OPSZ_8) {
CLIENT_ASSERT(vl == OPSZ_32 || vl == OPSZ_64, "invalid vector length.");
return 16;
} else {
CLIENT_ASSERT(false, "invalid input size.");
}
break;
case DR_TUPLE_TYPE_T4:
if (input_size == OPSZ_4) {
CLIENT_ASSERT(vl == OPSZ_32 || vl == OPSZ_64, "invalid vector length.");
return 16;
} else if (input_size == OPSZ_8) {
CLIENT_ASSERT(vl == OPSZ_64, "invalid vector length.");
return 32;
} else {
CLIENT_ASSERT(false, "invalid input size.");
}
break;
case DR_TUPLE_TYPE_T8:
CLIENT_ASSERT(input_size == OPSZ_4, "invalid input size.");
CLIENT_ASSERT(vl == OPSZ_64, "invalid vector length.");
return 32;
case DR_TUPLE_TYPE_HVM:
switch (vl) {
case OPSZ_16: return 8;
case OPSZ_32: return 16;
case OPSZ_64: return 32;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
break;
case DR_TUPLE_TYPE_QVM:
switch (vl) {
case OPSZ_16: return 4;
case OPSZ_32: return 8;
case OPSZ_64: return 16;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
break;
case DR_TUPLE_TYPE_OVM:
switch (vl) {
case OPSZ_16: return 2;
case OPSZ_32: return 4;
case OPSZ_64: return 8;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
break;
case DR_TUPLE_TYPE_M128:
switch (vl) {
case OPSZ_16: return 16;
case OPSZ_32: return 16;
case OPSZ_64: return 16;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
break;
case DR_TUPLE_TYPE_DUP:
switch (vl) {
case OPSZ_16: return 8;
case OPSZ_32: return 32;
case OPSZ_64: return 64;
default: CLIENT_ASSERT(false, "invalid vector length.");
}
break;
case DR_TUPLE_TYPE_NONE: return 1;
default: CLIENT_ASSERT(false, "unknown tuple type."); return -1;
}
return -1;
}
void
decode_get_tuple_type_input_size(const instr_info_t *info, decode_info_t *di)
{
/* The upper DR_TUPLE_TYPE_BITS bits of the flags field are the evex tuple type. */
di->tuple_type = (dr_tuple_type_t)(info->flags >> DR_TUPLE_TYPE_BITPOS);
if (TEST(DR_EVEX_INPUT_OPSZ_1, info->flags))
di->input_size = OPSZ_1;
else if (TEST(DR_EVEX_INPUT_OPSZ_2, info->flags))
di->input_size = OPSZ_2;
else if (TEST(DR_EVEX_INPUT_OPSZ_4, info->flags))
di->input_size = OPSZ_4;
else if (TEST(DR_EVEX_INPUT_OPSZ_8, info->flags))
di->input_size = OPSZ_8;
else
di->input_size = OPSZ_NA;
}
/****************************************************************************
* Exported routines
*/
/* Decodes only enough of the instruction at address pc to determine
* its eflags usage, which is returned in usage as EFLAGS_ constants
* or'ed together.
* This corresponds to halfway between Level 1 and Level 2: a Level 1 decoding
* plus eflags information (usually only at Level 2).
* Returns the address of the next byte after the decoded instruction.
* Returns NULL on decoding an invalid instruction.
*
* N.B.: an instruction that has an "undefined" effect on eflags is considered
* to write to eflags. This is fine since programs shouldn't be reading
* eflags after an undefined modification to them, but a weird program that
* relies on some undefined eflag thing might behave differently under dynamo
* than not!
*/
byte *
decode_eflags_usage(dcontext_t *dcontext, byte *pc, uint *usage,
dr_opnd_query_flags_t flags)
{
const instr_info_t *info;
decode_info_t di;
IF_X64(di.x86_mode = get_x86_mode(dcontext));
/* don't decode immeds, instead use decode_next_pc, it's faster */
read_instruction(pc, pc, &info, &di, true /* just opcode */ _IF_DEBUG(true));
*usage = instr_eflags_conditionally(
info->eflags, decode_predicate_from_instr_info(info->type, info), flags);
pc = decode_next_pc(dcontext, pc);
/* failure handled fine -- we'll go ahead and return the NULL */
return pc;
}
/* Decodes the opcode and eflags usage of instruction at address pc
* into instr.
* This corresponds to a Level 2 decoding.
* Assumes that instr is already initialized, but uses the x86/x64 mode
* for the current thread rather than that set in instr.
* If caller is re-using same instr struct over multiple decodings,
* should call instr_reset or instr_reuse.
* Returns the address of the next byte after the decoded instruction.
* Returns NULL on decoding an invalid instruction.
*/
byte *
decode_opcode(dcontext_t *dcontext, byte *pc, instr_t *instr)
{
const instr_info_t *info;
decode_info_t di;
int sz;
#ifdef X64
/* PR 251479: we need to know about all rip-relative addresses.
* Since change/setting raw bits invalidates, we must set this
* on every return. */
uint rip_rel_pos;
#endif
IF_X64(di.x86_mode = instr_get_x86_mode(instr));
/* when pass true to read_instruction it doesn't decode immeds,
* so have to call decode_next_pc, but that ends up being faster
* than decoding immeds!
*/
read_instruction(pc, pc, &info, &di,
true /* just opcode */
_IF_DEBUG(!TEST(INSTR_IGNORE_INVALID, instr->flags)));
sz = decode_sizeof(dcontext, pc, NULL _IF_X64(&rip_rel_pos));
IF_X64(instr_set_x86_mode(instr, get_x86_mode(dcontext)));
instr_set_opcode(instr, info->type);
/* read_instruction sets opcode to OP_INVALID for illegal instr.
* decode_sizeof will return 0 for _some_ illegal instrs, so we
* check it first since it's faster than instr_valid, but we have to
* also check instr_valid to catch all illegal instrs.
*/
if (sz == 0 || !instr_valid(instr)) {
CLIENT_ASSERT(!instr_valid(instr), "decode_opcode: invalid instr");
return NULL;
}
instr->eflags = info->eflags;
instr_set_eflags_valid(instr, true);
/* operands are NOT set */
instr_set_operands_valid(instr, false);
/* raw bits are valid though and crucial for encoding */
instr_set_raw_bits(instr, pc, sz);
/* must set rip_rel_pos after setting raw bits */
IF_X64(instr_set_rip_rel_pos(instr, rip_rel_pos));
return pc + sz;
}
#if defined(DEBUG) && !defined(STANDALONE_DECODER)
/* PR 215143: we must resolve variable sizes at decode time */
static bool
check_is_variable_size(opnd_t op)
{
if (opnd_is_memory_reference(op) ||
/* reg_get_size() fails on fp registers since no OPSZ for them */
(opnd_is_reg(op) && !reg_is_fp(opnd_get_reg(op))))
return !is_variable_size(opnd_get_size(op));
/* else no legitimate size to check */
return true;
}
#endif
/* Decodes the instruction at address pc into instr, filling in the
* instruction's opcode, eflags usage, prefixes, and operands.
* This corresponds to a Level 3 decoding.
* Assumes that instr is already initialized, but uses the x86/x64 mode
* for the current thread rather than that set in instr.
* If caller is re-using same instr struct over multiple decodings,
* should call instr_reset or instr_reuse.
* Returns the address of the next byte after the decoded instruction.
* Returns NULL on decoding an invalid instruction.
*/
static byte *
decode_common(dcontext_t *dcontext, byte *pc, byte *orig_pc, instr_t *instr)
{
const instr_info_t *info;
decode_info_t di;
byte *next_pc;
int instr_num_dsts = 0, instr_num_srcs = 0;
opnd_t dsts[8];
opnd_t srcs[8];
CLIENT_ASSERT(instr->opcode == OP_INVALID || instr->opcode == OP_UNDECODED,
"decode: instr is already decoded, may need to call instr_reset()");
IF_X64(di.x86_mode = get_x86_mode(dcontext));
next_pc = read_instruction(pc, orig_pc, &info, &di,
false /* not just opcode,
decode operands too */
_IF_DEBUG(!TEST(INSTR_IGNORE_INVALID, instr->flags)));
instr_set_opcode(instr, info->type);
IF_X64(instr_set_x86_mode(instr, di.x86_mode));
/* failure up to this point handled fine -- we set opcode to OP_INVALID */
if (next_pc == NULL) {
LOG(THREAD, LOG_INTERP, 3, "decode: invalid instr at " PFX "\n", pc);
CLIENT_ASSERT(!instr_valid(instr), "decode: invalid instr");
return NULL;
}
instr->eflags = info->eflags;
instr_set_eflags_valid(instr, true);
/* since we don't use set_src/set_dst we must explicitly say they're valid */
instr_set_operands_valid(instr, true);
/* read_instruction doesn't set di.len since only needed for rip-relative opnds */
IF_X64(
CLIENT_ASSERT_TRUNCATE(di.len, int, next_pc - pc, "internal truncation error"));
di.len = (int)(next_pc - pc);
di.opcode = info->type; /* used for opnd_create_immed_float_for_opcode */
decode_get_tuple_type_input_size(info, &di);
instr->prefixes |= di.prefixes;
/* operands */
do {
if (info->dst1_type != TYPE_NONE) {
if (!decode_operand(&di, info->dst1_type, info->dst1_size,
&(dsts[instr_num_dsts++])))
goto decode_invalid;
ASSERT(check_is_variable_size(dsts[instr_num_dsts - 1]));
}
if (info->dst2_type != TYPE_NONE) {
if (!decode_operand(&di, info->dst2_type, info->dst2_size,
&(dsts[instr_num_dsts++])))
goto decode_invalid;
ASSERT(check_is_variable_size(dsts[instr_num_dsts - 1]));
}
if (info->src1_type != TYPE_NONE) {
if (!decode_operand(&di, info->src1_type, info->src1_size,
&(srcs[instr_num_srcs++])))
goto decode_invalid;
ASSERT(check_is_variable_size(srcs[instr_num_srcs - 1]));
}
if (info->src2_type != TYPE_NONE) {
if (!decode_operand(&di, info->src2_type, info->src2_size,
&(srcs[instr_num_srcs++])))
goto decode_invalid;
ASSERT(check_is_variable_size(srcs[instr_num_srcs - 1]));
}
if (info->src3_type != TYPE_NONE) {
if (!decode_operand(&di, info->src3_type, info->src3_size,
&(srcs[instr_num_srcs++])))
goto decode_invalid;
ASSERT(check_is_variable_size(srcs[instr_num_srcs - 1]));
}
/* extra operands:
* we take advantage of the fact that all instructions that need extra
* operands have only one encoding, so the code field points to instr_info_t
* structures containing the extra operands
*/
if ((info->flags & HAS_EXTRA_OPERANDS) != 0) {
if ((info->flags & EXTRAS_IN_CODE_FIELD) != 0)
info = (const instr_info_t *)(info->code);
else /* extra operands are in next entry */
info = info + 1;
} else
break;
} while (true);
/* some operands add to di.prefixes so we copy again */
instr->prefixes |= di.prefixes;
if (di.seg_override == SEG_FS)
instr->prefixes |= PREFIX_SEG_FS;
if (di.seg_override == SEG_GS)
instr->prefixes |= PREFIX_SEG_GS;
/* now copy operands into their real slots */
instr_set_num_opnds(dcontext, instr, instr_num_dsts, instr_num_srcs);
if (instr_num_dsts > 0) {
memcpy(instr->dsts, dsts, instr_num_dsts * sizeof(opnd_t));
}
if (instr_num_srcs > 0) {
/* remember that src0 is static */
instr->src0 = srcs[0];
if (instr_num_srcs > 1) {
memcpy(instr->srcs, &(srcs[1]), (instr_num_srcs - 1) * sizeof(opnd_t));
}
}
if (TESTANY(HAS_PRED_CC | HAS_PRED_COMPLEX, info->flags))
instr_set_predicate(instr, decode_predicate_from_instr_info(di.opcode, info));
/* check for invalid prefixes that depend on operand types */
if (TEST(PREFIX_LOCK, di.prefixes)) {
/* check for invalid opcode, list on p3-397 of IA-32 vol 2 */
switch (instr_get_opcode(instr)) {
case OP_add:
case OP_adc:
case OP_and:
case OP_btc:
case OP_btr:
case OP_bts:
case OP_cmpxchg:
case OP_cmpxchg8b:
case OP_dec:
case OP_inc:
case OP_neg:
case OP_not:
case OP_or:
case OP_sbb:
case OP_sub:
case OP_xor:
case OP_xadd:
case OP_xchg: {
/* still illegal unless dest is mem op rather than src */
CLIENT_ASSERT(instr->num_dsts > 0, "internal lock prefix check error");
if (!opnd_is_memory_reference(instr->dsts[0])) {
LOG(THREAD, LOG_INTERP, 3, "decode: invalid lock prefix at " PFX "\n",
pc);
goto decode_invalid;
}
break;
}
default: {
LOG(THREAD, LOG_INTERP, 3, "decode: invalid lock prefix at " PFX "\n", pc);
goto decode_invalid;
}
}
}
/* PREFIX_XRELEASE is allowed w/o LOCK on mov_st, but use of it or PREFIX_XACQUIRE
* in other situations does not result in #UD so we ignore.
*/
if (orig_pc != pc) {
/* We do not want to copy when encoding and condone an invalid
* relative target
*/
instr_set_raw_bits_valid(instr, false);
instr_set_translation(instr, orig_pc);
} else {
/* we set raw bits AFTER setting all srcs and dsts b/c setting
* a src or dst marks instr as having invalid raw bits
*/
IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_uint(next_pc - pc)));
instr_set_raw_bits(instr, pc, (uint)(next_pc - pc));
#ifdef X64
if (X64_MODE(&di) && TEST(HAS_MODRM, info->flags) && di.mod == 0 && di.rm == 5) {
CLIENT_ASSERT(di.disp_abs > di.start_pc, "decode: internal rip-rel error");
CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_int(di.disp_abs - di.start_pc),
"decode: internal rip-rel error");
/* must do this AFTER setting raw bits to avoid being invalidated */
instr_set_rip_rel_pos(instr, (int)(di.disp_abs - di.start_pc));
}
#endif
}
return next_pc;
decode_invalid:
instr_set_operands_valid(instr, false);
instr_set_opcode(instr, OP_INVALID);
return NULL;
}
byte *
decode(dcontext_t *dcontext, byte *pc, instr_t *instr)
{
return decode_common(dcontext, pc, pc, instr);
}
byte *
decode_from_copy(dcontext_t *dcontext, byte *copy_pc, byte *orig_pc, instr_t *instr)
{
return decode_common(dcontext, copy_pc, orig_pc, instr);
}
const instr_info_t *
get_next_instr_info(const instr_info_t *info)
{
return (const instr_info_t *)(info->code);
}
byte
decode_first_opcode_byte(int opcode)
{
const instr_info_t *info = op_instr[opcode];
return (byte)((info->opcode & 0x00ff0000) >> 16);
}
DR_API
const char *
decode_opcode_name(int opcode)
{
const instr_info_t *info = op_instr[opcode];
return info->name;
}
const instr_info_t *
opcode_to_encoding_info(uint opc, dr_isa_mode_t isa_mode)
{
return op_instr[opc];
}
app_pc
dr_app_pc_as_jump_target(dr_isa_mode_t isa_mode, app_pc pc)
{
return pc;
}
app_pc
dr_app_pc_as_load_target(dr_isa_mode_t isa_mode, app_pc pc)
{
return pc;
}
#ifdef DEBUG
void
decode_debug_checks_arch(void)
{
/* empty */
}
#endif
#ifdef DECODE_UNIT_TEST
# include "instr_create.h"
/* FIXME: Tried putting this inside a separate unit-decode.c file, but
* required creating a unit-decode_table.c file. Since the
* infrastructure is not fully set up, currently leaving this here
* FIXME: beef up to check if something went wrong
*/
static bool
unit_check_decode_ff_opcode()
{
static int do_once = 0;
instr_t instr;
byte modrm, sib;
byte raw_bytes[] = {
0xff, 0x0, 0x0, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
0xff, 0xab, 0xbc, 0xcd, 0xde, 0xef, 0xfa,
};
app_pc next_pc = NULL;
for (modrm = 0x0; modrm < 0xff; modrm++) {
raw_bytes[1] = modrm;
for (sib = 0x0; sib < 0xff; sib++) {
raw_bytes[2] = sib;
/* set up instr for decode_opcode */
instr_init(GLOBAL_DCONTEXT, &instr);
instr.bytes = raw_bytes;
instr.length = 15;
instr_set_raw_bits_valid(&instr, true);
instr_set_operands_valid(&instr, false);
next_pc = decode_opcode(GLOBAL_DCONTEXT, instr.bytes, &instr);
if (next_pc != NULL && instr.opcode != OP_INVALID &&
instr.opcode != OP_UNDECODED) {
print_file(STDERR, "## %02x %02x %02x len=%d\n", instr.bytes[0],
instr.bytes[1], instr.bytes[2], instr.length);
}
}
}
return 0;
}
/* Standalone building is still broken so I tested this by calling
* from a real DR build.
*/
# define CHECK_ENCODE_OPCODE(dcontext, instr, pc, opc, ...) \
instr = INSTR_CREATE_##opc(dcontext, ##__VA_ARGS__); \
instr_encode(dcontext, instr, pc); \
instr_reset(dcontext, instr); \
decode(dcontext, pc, instr); \
/* FIXME: use EXPECT */ \
CLIENT_ASSERT(instr_get_opcode(instr) == OP_##opc, "unit test"); \
instr_destroy(dcontext, instr);
/* FIXME: case 8212: add checks for every single instr type */
static bool
unit_check_sse3()
{
dcontext_t *dcontext = get_thread_private_dcontext();
byte buf[32];
instr_t *instr;
CHECK_ENCODE_OPCODE(dcontext, instr, buf, mwait);
CHECK_ENCODE_OPCODE(dcontext, instr, buf, monitor);
CHECK_ENCODE_OPCODE(dcontext, instr, buf, haddpd, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, haddps, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, hsubpd, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, hsubps, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, addsubpd, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, addsubps, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, lddqu, opnd_create_reg(REG_XMM7),
opnd_create_base_disp(REG_NULL, REG_NULL, 0, 0, OPSZ_16));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, movsldup, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, movshdup, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
CHECK_ENCODE_OPCODE(dcontext, instr, buf, movddup, opnd_create_reg(REG_XMM7),
opnd_create_reg(REG_XMM2));
/* not sse3 but I fixed it at same time so here to test */
CHECK_ENCODE_OPCODE(dcontext, instr, buf, cmpxchg8b,
opnd_create_base_disp(REG_NULL, REG_NULL, 0, 0, OPSZ_8));
return true;
}
int
main()
{
bool res;
standalone_init();
res = unit_check_sse3();
res = unit_check_decode_ff_opcode() && res;
return res;
}
#endif /* DECODE_UNIT_TEST */
| 1 | 17,567 | This snprintf, etc. needs to all be inside the DO_ONCE: all this overhead happening on every single decode is likely a huge performance hit. | DynamoRIO-dynamorio | c |
@@ -50,6 +50,7 @@ Cluster Options:
--routes <rurl-1, rurl-2> Routes to solicit and connect
--cluster <cluster-url> Cluster URL for solicited routes
--no_advertise <bool> Advertise known cluster IPs to clients
+ --conn_retries <number> For implicit routes, number of connect retries
Common Options: | 1 | // Copyright 2012-2016 Apcera Inc. All rights reserved.
package main
import (
"flag"
"fmt"
"net"
"net/url"
"os"
"github.com/nats-io/gnatsd/auth"
"github.com/nats-io/gnatsd/logger"
"github.com/nats-io/gnatsd/server"
)
var usageStr = `
Usage: gnatsd [options]
Server Options:
-a, --addr <host> Bind to host address (default: 0.0.0.0)
-p, --port <port> Use port for clients (default: 4222)
-P, --pid <file> File to store PID
-m, --http_port <port> Use port for http monitoring
-ms,--https_port <port> Use port for https monitoring
-c, --config <file> Configuration file
Logging Options:
-l, --log <file> File to redirect log output
-T, --logtime Timestamp log entries (default: true)
-s, --syslog Enable syslog as log method
-r, --remote_syslog <addr> Syslog server addr (udp://localhost:514)
-D, --debug Enable debugging output
-V, --trace Trace the raw protocol
-DV Debug and trace
Authorization Options:
--user <user> User required for connections
--pass <password> Password required for connections
--auth <token> Authorization token required for connections
TLS Options:
--tls Enable TLS, do not verify clients (default: false)
--tlscert <file> Server certificate file
--tlskey <file> Private key for server certificate
--tlsverify Enable TLS, verify client certificates
--tlscacert <file> Client certificate CA for verification
Cluster Options:
--routes <rurl-1, rurl-2> Routes to solicit and connect
--cluster <cluster-url> Cluster URL for solicited routes
--no_advertise <bool> Advertise known cluster IPs to clients
Common Options:
-h, --help Show this message
-v, --version Show version
--help_tls TLS help
`
// usage will print out the flag options for the server.
func usage() {
fmt.Printf("%s\n", usageStr)
os.Exit(0)
}
func main() {
// Server Options
opts := server.Options{}
var showVersion bool
var debugAndTrace bool
var configFile string
var showTLSHelp bool
// Parse flags
flag.IntVar(&opts.Port, "port", 0, "Port to listen on.")
flag.IntVar(&opts.Port, "p", 0, "Port to listen on.")
flag.StringVar(&opts.Host, "addr", "", "Network host to listen on.")
flag.StringVar(&opts.Host, "a", "", "Network host to listen on.")
flag.StringVar(&opts.Host, "net", "", "Network host to listen on.")
flag.BoolVar(&opts.Debug, "D", false, "Enable Debug logging.")
flag.BoolVar(&opts.Debug, "debug", false, "Enable Debug logging.")
flag.BoolVar(&opts.Trace, "V", false, "Enable Trace logging.")
flag.BoolVar(&opts.Trace, "trace", false, "Enable Trace logging.")
flag.BoolVar(&debugAndTrace, "DV", false, "Enable Debug and Trace logging.")
flag.BoolVar(&opts.Logtime, "T", true, "Timestamp log entries.")
flag.BoolVar(&opts.Logtime, "logtime", true, "Timestamp log entries.")
flag.StringVar(&opts.Username, "user", "", "Username required for connection.")
flag.StringVar(&opts.Password, "pass", "", "Password required for connection.")
flag.StringVar(&opts.Authorization, "auth", "", "Authorization token required for connection.")
flag.IntVar(&opts.HTTPPort, "m", 0, "HTTP Port for /varz, /connz endpoints.")
flag.IntVar(&opts.HTTPPort, "http_port", 0, "HTTP Port for /varz, /connz endpoints.")
flag.IntVar(&opts.HTTPSPort, "ms", 0, "HTTPS Port for /varz, /connz endpoints.")
flag.IntVar(&opts.HTTPSPort, "https_port", 0, "HTTPS Port for /varz, /connz endpoints.")
flag.StringVar(&configFile, "c", "", "Configuration file.")
flag.StringVar(&configFile, "config", "", "Configuration file.")
flag.StringVar(&opts.PidFile, "P", "", "File to store process pid.")
flag.StringVar(&opts.PidFile, "pid", "", "File to store process pid.")
flag.StringVar(&opts.LogFile, "l", "", "File to store logging output.")
flag.StringVar(&opts.LogFile, "log", "", "File to store logging output.")
flag.BoolVar(&opts.Syslog, "s", false, "Enable syslog as log method.")
flag.BoolVar(&opts.Syslog, "syslog", false, "Enable syslog as log method..")
flag.StringVar(&opts.RemoteSyslog, "r", "", "Syslog server addr (udp://localhost:514).")
flag.StringVar(&opts.RemoteSyslog, "remote_syslog", "", "Syslog server addr (udp://localhost:514).")
flag.BoolVar(&showVersion, "version", false, "Print version information.")
flag.BoolVar(&showVersion, "v", false, "Print version information.")
flag.IntVar(&opts.ProfPort, "profile", 0, "Profiling HTTP port")
flag.StringVar(&opts.RoutesStr, "routes", "", "Routes to actively solicit a connection.")
flag.StringVar(&opts.Cluster.ListenStr, "cluster", "", "Cluster url from which members can solicit routes.")
flag.StringVar(&opts.Cluster.ListenStr, "cluster_listen", "", "Cluster url from which members can solicit routes.")
flag.BoolVar(&opts.Cluster.NoAdvertise, "no_advertise", false, "Advertise known cluster IPs to clients.")
flag.BoolVar(&showTLSHelp, "help_tls", false, "TLS help.")
flag.BoolVar(&opts.TLS, "tls", false, "Enable TLS.")
flag.BoolVar(&opts.TLSVerify, "tlsverify", false, "Enable TLS with client verification.")
flag.StringVar(&opts.TLSCert, "tlscert", "", "Server certificate file.")
flag.StringVar(&opts.TLSKey, "tlskey", "", "Private key for server certificate.")
flag.StringVar(&opts.TLSCaCert, "tlscacert", "", "Client certificate CA for verification.")
flag.Usage = usage
flag.Parse()
// Show version and exit
if showVersion {
server.PrintServerAndExit()
}
if showTLSHelp {
server.PrintTLSHelpAndDie()
}
// One flag can set multiple options.
if debugAndTrace {
opts.Trace, opts.Debug = true, true
}
// Process args looking for non-flag options,
// 'version' and 'help' only for now
showVersion, showHelp, err := server.ProcessCommandLineArgs(flag.CommandLine)
if err != nil {
server.PrintAndDie(err.Error() + usageStr)
} else if showVersion {
server.PrintServerAndExit()
} else if showHelp {
usage()
}
// Parse config if given
if configFile != "" {
fileOpts, err := server.ProcessConfigFile(configFile)
if err != nil {
server.PrintAndDie(err.Error())
}
opts = *server.MergeOptions(fileOpts, &opts)
}
// Remove any host/ip that points to itself in Route
newroutes, err := server.RemoveSelfReference(opts.Cluster.Port, opts.Routes)
if err != nil {
server.PrintAndDie(err.Error())
}
opts.Routes = newroutes
// Configure TLS based on any present flags
configureTLS(&opts)
// Configure cluster opts if explicitly set via flags.
err = configureClusterOpts(&opts)
if err != nil {
server.PrintAndDie(err.Error())
}
// Create the server with appropriate options.
s := server.New(&opts)
// Configure the authentication mechanism
configureAuth(s, &opts)
// Configure the logger based on the flags
configureLogger(s, &opts)
// Start things up. Block here until done.
s.Start()
}
func configureAuth(s *server.Server, opts *server.Options) {
// Client
// Check for multiple users first
if opts.Users != nil {
auth := auth.NewMultiUser(opts.Users)
s.SetClientAuthMethod(auth)
} else if opts.Username != "" {
auth := &auth.Plain{
Username: opts.Username,
Password: opts.Password,
}
s.SetClientAuthMethod(auth)
} else if opts.Authorization != "" {
auth := &auth.Token{
Token: opts.Authorization,
}
s.SetClientAuthMethod(auth)
}
// Routes
if opts.Cluster.Username != "" {
auth := &auth.Plain{
Username: opts.Cluster.Username,
Password: opts.Cluster.Password,
}
s.SetRouteAuthMethod(auth)
}
}
func configureLogger(s *server.Server, opts *server.Options) {
var log server.Logger
if opts.LogFile != "" {
log = logger.NewFileLogger(opts.LogFile, opts.Logtime, opts.Debug, opts.Trace, true)
} else if opts.RemoteSyslog != "" {
log = logger.NewRemoteSysLogger(opts.RemoteSyslog, opts.Debug, opts.Trace)
} else if opts.Syslog {
log = logger.NewSysLogger(opts.Debug, opts.Trace)
} else {
colors := true
// Check to see if stderr is being redirected and if so turn off color
// Also turn off colors if we're running on Windows where os.Stderr.Stat() returns an invalid handle-error
stat, err := os.Stderr.Stat()
if err != nil || (stat.Mode()&os.ModeCharDevice) == 0 {
colors = false
}
log = logger.NewStdLogger(opts.Logtime, opts.Debug, opts.Trace, colors, true)
}
s.SetLogger(log, opts.Debug, opts.Trace)
}
func configureTLS(opts *server.Options) {
// If no trigger flags, ignore the others
if !opts.TLS && !opts.TLSVerify {
return
}
if opts.TLSCert == "" {
server.PrintAndDie("TLS Server certificate must be present and valid.")
}
if opts.TLSKey == "" {
server.PrintAndDie("TLS Server private key must be present and valid.")
}
tc := server.TLSConfigOpts{}
tc.CertFile = opts.TLSCert
tc.KeyFile = opts.TLSKey
tc.CaFile = opts.TLSCaCert
if opts.TLSVerify {
tc.Verify = true
}
var err error
if opts.TLSConfig, err = server.GenTLSConfig(&tc); err != nil {
server.PrintAndDie(err.Error())
}
}
func configureClusterOpts(opts *server.Options) error {
// If we don't have cluster defined in the configuration
// file and no cluster listen string override, but we do
// have a routes override, we need to report misconfiguration.
if opts.Cluster.ListenStr == "" && opts.Cluster.Host == "" &&
opts.Cluster.Port == 0 {
if opts.RoutesStr != "" {
server.PrintAndDie("Solicited routes require cluster capabilities, e.g. --cluster.")
}
return nil
}
// If cluster flag override, process it
if opts.Cluster.ListenStr != "" {
clusterURL, err := url.Parse(opts.Cluster.ListenStr)
h, p, err := net.SplitHostPort(clusterURL.Host)
if err != nil {
return err
}
opts.Cluster.Host = h
_, err = fmt.Sscan(p, &opts.Cluster.Port)
if err != nil {
return err
}
if clusterURL.User != nil {
pass, hasPassword := clusterURL.User.Password()
if !hasPassword {
return fmt.Errorf("Expected cluster password to be set.")
}
opts.Cluster.Password = pass
user := clusterURL.User.Username()
opts.Cluster.Username = user
} else {
// Since we override from flag and there is no user/pwd, make
// sure we clear what we may have gotten from config file.
opts.Cluster.Username = ""
opts.Cluster.Password = ""
}
}
// If we have routes but no config file, fill in here.
if opts.RoutesStr != "" && opts.Routes == nil {
opts.Routes = server.RoutesFromStr(opts.RoutesStr)
}
return nil
}
| 1 | 6,757 | would call it connect_retries | nats-io-nats-server | go |
@@ -3717,3 +3717,15 @@ class DataFrameTest(ReusedSQLTestCase, SQLTestUtils):
for p_items, k_items in zip(pdf.iteritems(), kdf.iteritems()):
self.assert_eq(repr(p_items), repr(k_items))
+
+ def test_tail(self):
+ if LooseVersion(pyspark.__version__) >= LooseVersion("3.0"):
+ pdf = pd.DataFrame(range(1000))
+ kdf = ks.from_pandas(pdf)
+
+ self.assert_eq(repr(pdf.tail()), repr(kdf.tail()))
+ self.assert_eq(repr(pdf.tail(10)), repr(kdf.tail(10)))
+ self.assert_eq(repr(pdf.tail(-990)), repr(kdf.tail(-990)))
+ self.assert_eq(repr(pdf.tail(0)), repr(kdf.tail(0)))
+ with self.assertRaisesRegex(TypeError, "bad operand type for unary -: 'str'"):
+ kdf.tail("10") | 1 | #
# Copyright (C) 2019 Databricks, 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.
#
from datetime import datetime
from distutils.version import LooseVersion
import inspect
import sys
import unittest
from io import StringIO
import numpy as np
import pandas as pd
import pyspark
from pyspark import StorageLevel
from pyspark.ml.linalg import SparseVector
from databricks import koalas as ks
from databricks.koalas.config import option_context
from databricks.koalas.testing.utils import ReusedSQLTestCase, SQLTestUtils
from databricks.koalas.exceptions import PandasNotImplementedError
from databricks.koalas.missing.frame import _MissingPandasLikeDataFrame
from databricks.koalas.frame import CachedDataFrame
class DataFrameTest(ReusedSQLTestCase, SQLTestUtils):
@property
def pdf(self):
return pd.DataFrame(
{"a": [1, 2, 3, 4, 5, 6, 7, 8, 9], "b": [4, 5, 6, 3, 2, 1, 0, 0, 0],},
index=np.random.rand(9),
)
@property
def kdf(self):
return ks.from_pandas(self.pdf)
@property
def df_pair(self):
pdf = self.pdf
kdf = ks.from_pandas(pdf)
return pdf, kdf
def test_dataframe(self):
pdf, kdf = self.df_pair
expected = pd.Series(
[2, 3, 4, 5, 6, 7, 8, 9, 10], index=pdf.index, name="(a + 1)"
) # TODO: name='a'
self.assert_eq(kdf["a"] + 1, expected)
self.assert_eq(kdf.columns, pd.Index(["a", "b"]))
self.assert_eq(kdf[kdf["b"] > 2], pdf[pdf["b"] > 2])
self.assert_eq(kdf[["a", "b"]], pdf[["a", "b"]])
self.assert_eq(kdf.a, pdf.a)
self.assert_eq(kdf.b.mean(), pdf.b.mean())
self.assert_eq(kdf.b.var(), pdf.b.var())
self.assert_eq(kdf.b.std(), pdf.b.std())
pdf, kdf = self.df_pair
self.assert_eq(kdf[["a", "b"]], pdf[["a", "b"]])
self.assertEqual(kdf.a.notnull().alias("x").name, "x")
# check ks.DataFrame(ks.Series)
pser = pd.Series([1, 2, 3], name="x", index=np.random.rand(3))
kser = ks.from_pandas(pser)
self.assert_eq(pd.DataFrame(pser), ks.DataFrame(kser))
def test_inplace(self):
pdf, kdf = self.df_pair
pser = pdf.a
kser = kdf.a
pdf["a"] = pdf["a"] + 10
kdf["a"] = kdf["a"] + 10
self.assert_eq(kdf, pdf)
self.assert_eq(kser, pser)
def test_dataframe_multiindex_columns(self):
pdf = pd.DataFrame(
{
("x", "a", "1"): [1, 2, 3],
("x", "b", "2"): [4, 5, 6],
("y.z", "c.d", "3"): [7, 8, 9],
("x", "b", "4"): [10, 11, 12],
},
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
self.assert_eq(kdf["x"], pdf["x"])
self.assert_eq(kdf["y.z"], pdf["y.z"])
self.assert_eq(kdf["x"]["b"], pdf["x"]["b"])
self.assert_eq(kdf["x"]["b"]["2"], pdf["x"]["b"]["2"])
self.assert_eq(kdf.x, pdf.x)
self.assert_eq(kdf.x.b, pdf.x.b)
self.assert_eq(kdf.x.b["2"], pdf.x.b["2"])
self.assertRaises(KeyError, lambda: kdf["z"])
self.assertRaises(AttributeError, lambda: kdf.z)
self.assert_eq(kdf[("x",)], pdf[("x",)])
self.assert_eq(kdf[("x", "a")], pdf[("x", "a")])
self.assert_eq(kdf[("x", "a", "1")], pdf[("x", "a", "1")])
def test_dataframe_column_level_name(self):
column = pd.Index(["A", "B", "C"], name="X")
pdf = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=column, index=np.random.rand(2))
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
self.assert_eq(kdf.columns.names, pdf.columns.names)
self.assert_eq(kdf.to_pandas().columns.names, pdf.columns.names)
def test_dataframe_multiindex_names_level(self):
columns = pd.MultiIndex.from_tuples(
[("X", "A", "Z"), ("X", "B", "Z"), ("Y", "C", "Z"), ("Y", "D", "Z")],
names=["lvl_1", "lvl_2", "lv_3"],
)
pdf = pd.DataFrame(
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]],
columns=columns,
index=np.random.rand(5),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.columns.names, pdf.columns.names)
self.assert_eq(kdf.to_pandas().columns.names, pdf.columns.names)
kdf1 = ks.from_pandas(pdf)
self.assert_eq(kdf1.columns.names, pdf.columns.names)
with self.assertRaisesRegex(
ValueError, "Column_index_names should " "be list-like or None for a MultiIndex"
):
ks.DataFrame(kdf1._internal.copy(column_label_names="level"))
self.assert_eq(kdf["X"], pdf["X"])
self.assert_eq(kdf["X"].columns.names, pdf["X"].columns.names)
self.assert_eq(kdf["X"].to_pandas().columns.names, pdf["X"].columns.names)
self.assert_eq(kdf["X"]["A"], pdf["X"]["A"])
self.assert_eq(kdf["X"]["A"].columns.names, pdf["X"]["A"].columns.names)
self.assert_eq(kdf["X"]["A"].to_pandas().columns.names, pdf["X"]["A"].columns.names)
self.assert_eq(kdf[("X", "A")], pdf[("X", "A")])
self.assert_eq(kdf[("X", "A")].columns.names, pdf[("X", "A")].columns.names)
self.assert_eq(kdf[("X", "A")].to_pandas().columns.names, pdf[("X", "A")].columns.names)
self.assert_eq(kdf[("X", "A", "Z")], pdf[("X", "A", "Z")])
def test_iterrows(self):
pdf = pd.DataFrame(
{
("x", "a", "1"): [1, 2, 3],
("x", "b", "2"): [4, 5, 6],
("y.z", "c.d", "3"): [7, 8, 9],
("x", "b", "4"): [10, 11, 12],
},
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
for (pdf_k, pdf_v), (kdf_k, kdf_v) in zip(pdf.iterrows(), kdf.iterrows()):
self.assert_eq(pdf_k, kdf_k)
self.assert_eq(pdf_v, kdf_v)
def test_reset_index(self):
pdf = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=np.random.rand(3))
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.reset_index(), pdf.reset_index())
self.assert_eq(kdf.reset_index(drop=True), pdf.reset_index(drop=True))
pdf.index.name = "a"
kdf.index.name = "a"
with self.assertRaisesRegex(ValueError, "cannot insert a, already exists"):
kdf.reset_index()
self.assert_eq(kdf.reset_index(drop=True), pdf.reset_index(drop=True))
# inplace
pser = pdf.a
kser = kdf.a
pdf.reset_index(drop=True, inplace=True)
kdf.reset_index(drop=True, inplace=True)
self.assert_eq(kdf, pdf)
self.assert_eq(kser, pser)
def test_reset_index_with_default_index_types(self):
pdf = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=np.random.rand(3))
kdf = ks.from_pandas(pdf)
with ks.option_context("compute.default_index_type", "sequence"):
self.assert_eq(kdf.reset_index(), pdf.reset_index())
with ks.option_context("compute.default_index_type", "distributed-sequence"):
# the order might be changed.
self.assert_eq(kdf.reset_index().sort_index(), pdf.reset_index())
with ks.option_context("compute.default_index_type", "distributed"):
# the index is different.
self.assert_eq(kdf.reset_index().to_pandas().reset_index(drop=True), pdf.reset_index())
def test_reset_index_with_multiindex_columns(self):
index = pd.MultiIndex.from_tuples(
[("bird", "falcon"), ("bird", "parrot"), ("mammal", "lion"), ("mammal", "monkey")],
names=["class", "name"],
)
columns = pd.MultiIndex.from_tuples([("speed", "max"), ("species", "type")])
pdf = pd.DataFrame(
[(389.0, "fly"), (24.0, "fly"), (80.5, "run"), (np.nan, "jump")],
index=index,
columns=columns,
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
self.assert_eq(kdf.reset_index(), pdf.reset_index())
self.assert_eq(kdf.reset_index(level="class"), pdf.reset_index(level="class"))
self.assert_eq(
kdf.reset_index(level="class", col_level=1), pdf.reset_index(level="class", col_level=1)
)
self.assert_eq(
kdf.reset_index(level="class", col_level=1, col_fill="species"),
pdf.reset_index(level="class", col_level=1, col_fill="species"),
)
self.assert_eq(
kdf.reset_index(level="class", col_level=1, col_fill="genus"),
pdf.reset_index(level="class", col_level=1, col_fill="genus"),
)
with self.assertRaisesRegex(IndexError, "Index has only 2 levels, not 3"):
kdf.reset_index(col_level=2)
pdf.index.names = [("x", "class"), ("y", "name")]
kdf.index.names = [("x", "class"), ("y", "name")]
self.assert_eq(kdf.reset_index(), pdf.reset_index())
with self.assertRaisesRegex(ValueError, "Item must have length equal to number of levels."):
kdf.reset_index(col_level=1)
def test_multiindex_column_access(self):
columns = pd.MultiIndex.from_tuples(
[
("a", "", "", "b"),
("c", "", "d", ""),
("e", "", "f", ""),
("e", "g", "", ""),
("", "", "", "h"),
("i", "", "", ""),
]
)
pdf = pd.DataFrame(
[
(1, "a", "x", 10, 100, 1000),
(2, "b", "y", 20, 200, 2000),
(3, "c", "z", 30, 300, 3000),
],
columns=columns,
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
self.assert_eq(kdf["a"], pdf["a"])
self.assert_eq(kdf["a"]["b"], pdf["a"]["b"])
self.assert_eq(kdf["c"], pdf["c"])
self.assert_eq(kdf["c"]["d"], pdf["c"]["d"])
self.assert_eq(kdf["e"], pdf["e"])
self.assert_eq(kdf["e"][""]["f"], pdf["e"][""]["f"])
self.assert_eq(kdf["e"]["g"], pdf["e"]["g"])
self.assert_eq(kdf[""], pdf[""])
self.assert_eq(kdf[""]["h"], pdf[""]["h"])
self.assert_eq(kdf["i"], pdf["i"])
self.assert_eq(kdf[["a", "e"]], pdf[["a", "e"]])
self.assert_eq(kdf[["e", "a"]], pdf[["e", "a"]])
self.assert_eq(kdf[("a",)], pdf[("a",)])
self.assert_eq(kdf[("e", "g")], pdf[("e", "g")])
self.assert_eq(kdf[("i",)], pdf[("i",)])
self.assertRaises(KeyError, lambda: kdf[("a", "b")])
def test_repr_cache_invalidation(self):
# If there is any cache, inplace operations should invalidate it.
df = ks.range(10)
df.__repr__()
df["a"] = df["id"]
self.assertEqual(df.__repr__(), df.to_pandas().__repr__())
def test_repr_html_cache_invalidation(self):
# If there is any cache, inplace operations should invalidate it.
df = ks.range(10)
df._repr_html_()
df["a"] = df["id"]
self.assertEqual(df._repr_html_(), df.to_pandas()._repr_html_())
def test_empty_dataframe(self):
pdf = pd.DataFrame({"a": pd.Series([], dtype="i1"), "b": pd.Series([], dtype="str")})
self.assertRaises(ValueError, lambda: ks.from_pandas(pdf))
with self.sql_conf({"spark.sql.execution.arrow.enabled": False}):
self.assertRaises(ValueError, lambda: ks.from_pandas(pdf))
def test_all_null_dataframe(self):
pdf = pd.DataFrame(
{
"a": pd.Series([None, None, None], dtype="float64"),
"b": pd.Series([None, None, None], dtype="str"),
},
index=np.random.rand(3),
)
self.assertRaises(ValueError, lambda: ks.from_pandas(pdf))
with self.sql_conf({"spark.sql.execution.arrow.enabled": False}):
self.assertRaises(ValueError, lambda: ks.from_pandas(pdf))
def test_nullable_object(self):
pdf = pd.DataFrame(
{
"a": list("abc") + [np.nan],
"b": list(range(1, 4)) + [np.nan],
"c": list(np.arange(3, 6).astype("i1")) + [np.nan],
"d": list(np.arange(4.0, 7.0, dtype="float64")) + [np.nan],
"e": [True, False, True, np.nan],
"f": list(pd.date_range("20130101", periods=3)) + [np.nan],
},
index=np.random.rand(4),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
with self.sql_conf({"spark.sql.execution.arrow.enabled": False}):
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
def test_assign(self):
pdf, kdf = self.df_pair
kdf["w"] = 1.0
pdf["w"] = 1.0
self.assert_eq(kdf, pdf)
kdf = kdf.assign(a=kdf["a"] * 2)
pdf = pdf.assign(a=pdf["a"] * 2)
self.assert_eq(kdf, pdf)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "w")])
pdf.columns = columns
kdf.columns = columns
kdf[("a", "c")] = "def"
pdf[("a", "c")] = "def"
self.assert_eq(kdf, pdf)
kdf = kdf.assign(Z="ZZ")
pdf = pdf.assign(Z="ZZ")
self.assert_eq(kdf, pdf)
kdf["x"] = "ghi"
pdf["x"] = "ghi"
self.assert_eq(kdf, pdf)
def test_head_tail(self):
pdf, kdf = self.df_pair
self.assert_eq(kdf.head(2), pdf.head(2))
self.assert_eq(kdf.head(3), pdf.head(3))
self.assert_eq(kdf.head(0), pdf.head(0))
self.assert_eq(kdf.head(-3), pdf.head(-3))
self.assert_eq(kdf.head(-10), pdf.head(-10))
def test_attributes(self):
kdf = self.kdf
self.assertIn("a", dir(kdf))
self.assertNotIn("foo", dir(kdf))
self.assertRaises(AttributeError, lambda: kdf.foo)
kdf = ks.DataFrame({"a b c": [1, 2, 3]})
self.assertNotIn("a b c", dir(kdf))
kdf = ks.DataFrame({"a": [1, 2], 5: [1, 2]})
self.assertIn("a", dir(kdf))
self.assertNotIn(5, dir(kdf))
def test_column_names(self):
kdf = self.kdf
self.assert_eq(kdf.columns, pd.Index(["a", "b"]))
self.assert_eq(kdf[["b", "a"]].columns, pd.Index(["b", "a"]))
self.assertEqual(kdf["a"].name, "a")
self.assertEqual((kdf["a"] + 1).name, "a")
self.assertEqual((kdf["a"] + kdf["b"]).name, "a") # TODO: None
def test_rename_columns(self):
pdf = pd.DataFrame(
{"a": [1, 2, 3, 4, 5, 6, 7], "b": [7, 6, 5, 4, 3, 2, 1]}, index=np.random.rand(7)
)
kdf = ks.from_pandas(pdf)
kdf.columns = ["x", "y"]
pdf.columns = ["x", "y"]
self.assert_eq(kdf.columns, pd.Index(["x", "y"]))
self.assert_eq(kdf, pdf)
self.assert_eq(kdf._internal.data_spark_column_names, ["x", "y"])
self.assert_eq(kdf.to_spark().columns, ["x", "y"])
self.assert_eq(kdf.to_spark(index_col="index").columns, ["index", "x", "y"])
columns = pdf.columns
columns.name = "lvl_1"
kdf.columns = columns
self.assert_eq(kdf.columns.names, ["lvl_1"])
self.assert_eq(kdf, pdf)
msg = "Length mismatch: Expected axis has 2 elements, new values have 4 elements"
with self.assertRaisesRegex(ValueError, msg):
kdf.columns = [1, 2, 3, 4]
# Multi-index columns
pdf = pd.DataFrame(
{("A", "0"): [1, 2, 2, 3], ("B", "1"): [1, 2, 3, 4]}, index=np.random.rand(4)
)
kdf = ks.from_pandas(pdf)
columns = pdf.columns
self.assert_eq(kdf.columns, columns)
self.assert_eq(kdf, pdf)
pdf.columns = ["x", "y"]
kdf.columns = ["x", "y"]
self.assert_eq(kdf.columns, pd.Index(["x", "y"]))
self.assert_eq(kdf, pdf)
self.assert_eq(kdf._internal.data_spark_column_names, ["x", "y"])
self.assert_eq(kdf.to_spark().columns, ["x", "y"])
self.assert_eq(kdf.to_spark(index_col="index").columns, ["index", "x", "y"])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.columns, columns)
self.assert_eq(kdf, pdf)
self.assert_eq(kdf._internal.data_spark_column_names, ["(A, 0)", "(B, 1)"])
self.assert_eq(kdf.to_spark().columns, ["(A, 0)", "(B, 1)"])
self.assert_eq(kdf.to_spark(index_col="index").columns, ["index", "(A, 0)", "(B, 1)"])
columns.names = ["lvl_1", "lvl_2"]
kdf.columns = columns
self.assert_eq(kdf.columns.names, ["lvl_1", "lvl_2"])
self.assert_eq(kdf, pdf)
self.assert_eq(kdf._internal.data_spark_column_names, ["(A, 0)", "(B, 1)"])
self.assert_eq(kdf.to_spark().columns, ["(A, 0)", "(B, 1)"])
self.assert_eq(kdf.to_spark(index_col="index").columns, ["index", "(A, 0)", "(B, 1)"])
def test_rename_dataframe(self):
pdf1 = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
kdf1 = ks.from_pandas(pdf1)
self.assert_eq(
kdf1.rename(columns={"A": "a", "B": "b"}), pdf1.rename(columns={"A": "a", "B": "b"})
)
result_kdf = kdf1.rename(index={1: 10, 2: 20})
result_pdf = pdf1.rename(index={1: 10, 2: 20})
self.assert_eq(result_kdf, result_pdf)
# inplace
pser = result_pdf.A
kser = result_kdf.A
result_kdf.rename(index={10: 100, 20: 200}, inplace=True)
result_pdf.rename(index={10: 100, 20: 200}, inplace=True)
self.assert_eq(result_kdf, result_pdf)
self.assert_eq(kser, pser)
def str_lower(s) -> str:
return str.lower(s)
self.assert_eq(
kdf1.rename(str_lower, axis="columns"), pdf1.rename(str_lower, axis="columns")
)
def mul10(x) -> int:
return x * 10
self.assert_eq(kdf1.rename(mul10, axis="index"), pdf1.rename(mul10, axis="index"))
self.assert_eq(
kdf1.rename(columns=str_lower, index={1: 10, 2: 20}),
pdf1.rename(columns=str_lower, index={1: 10, 2: 20}),
)
idx = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C"), ("Y", "D")])
pdf2 = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=idx)
kdf2 = ks.from_pandas(pdf2)
self.assert_eq(kdf2.rename(columns=str_lower), pdf2.rename(columns=str_lower))
self.assert_eq(
kdf2.rename(columns=str_lower, level=0), pdf2.rename(columns=str_lower, level=0)
)
self.assert_eq(
kdf2.rename(columns=str_lower, level=1), pdf2.rename(columns=str_lower, level=1)
)
pdf3 = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], index=idx, columns=list("ab"))
kdf3 = ks.from_pandas(pdf3)
self.assert_eq(kdf3.rename(index=str_lower), pdf3.rename(index=str_lower))
self.assert_eq(kdf3.rename(index=str_lower, level=0), pdf3.rename(index=str_lower, level=0))
self.assert_eq(kdf3.rename(index=str_lower, level=1), pdf3.rename(index=str_lower, level=1))
pdf4 = pdf2 + 1
kdf4 = kdf2 + 1
self.assert_eq(kdf4.rename(columns=str_lower), pdf4.rename(columns=str_lower))
pdf5 = pdf3 + 1
kdf5 = kdf3 + 1
self.assert_eq(kdf5.rename(index=str_lower), pdf5.rename(index=str_lower))
def test_dot_in_column_name(self):
self.assert_eq(
ks.DataFrame(ks.range(1)._internal.spark_frame.selectExpr("1 as `a.b`"))["a.b"],
ks.Series([1]),
)
def test_drop(self):
pdf = pd.DataFrame({"x": [1, 2], "y": [3, 4], "z": [5, 6]}, index=np.random.rand(2))
kdf = ks.from_pandas(pdf)
# Assert 'labels' or 'columns' parameter is set
expected_error_message = "Need to specify at least one of 'labels' or 'columns'"
with self.assertRaisesRegex(ValueError, expected_error_message):
kdf.drop()
# Assert axis cannot be 0
with self.assertRaisesRegex(NotImplementedError, "Drop currently only works for axis=1"):
kdf.drop("x", axis=0)
# Assert using a str for 'labels' works
self.assert_eq(kdf.drop("x", axis=1), pdf.drop("x", axis=1))
# Assert axis is 1 by default
self.assert_eq(kdf.drop("x"), pdf.drop("x", axis=1))
# Assert using a list for 'labels' works
self.assert_eq(kdf.drop(["y", "z"], axis=1), pdf.drop(["y", "z"], axis=1))
# Assert using 'columns' instead of 'labels' produces the same results
self.assert_eq(kdf.drop(columns="x"), pdf.drop(columns="x"))
self.assert_eq(kdf.drop(columns=["y", "z"]), pdf.drop(columns=["y", "z"]))
# Assert 'labels' being used when both 'labels' and 'columns' are specified
# TODO: should throw an error?
expected_output = pd.DataFrame({"y": [3, 4], "z": [5, 6]}, index=kdf.index.to_pandas())
self.assert_eq(kdf.drop(labels=["x"], columns=["y"]), expected_output)
columns = pd.MultiIndex.from_tuples([("a", "x"), ("a", "y"), ("b", "z")])
pdf.columns = columns
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.drop(columns="a"), pdf.drop(columns="a"))
self.assert_eq(kdf.drop(columns=("a", "x")), pdf.drop(columns=("a", "x")))
self.assert_eq(kdf.drop(columns=[("a", "x"), "b"]), pdf.drop(columns=[("a", "x"), "b"]))
self.assertRaises(KeyError, lambda: kdf.drop(columns="c"))
self.assertRaises(KeyError, lambda: kdf.drop(columns=("a", "z")))
def test_dropna(self):
pdf = pd.DataFrame(
{
"x": [np.nan, 2, 3, 4, np.nan, 6],
"y": [1, 2, np.nan, 4, np.nan, np.nan],
"z": [1, 2, 3, 4, np.nan, np.nan],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.dropna(), pdf.dropna())
self.assert_eq(kdf.dropna(how="all"), pdf.dropna(how="all"))
self.assert_eq(kdf.dropna(subset=["x"]), pdf.dropna(subset=["x"]))
self.assert_eq(kdf.dropna(subset="x"), pdf.dropna(subset=["x"]))
self.assert_eq(kdf.dropna(subset=["y", "z"]), pdf.dropna(subset=["y", "z"]))
self.assert_eq(
kdf.dropna(subset=["y", "z"], how="all"), pdf.dropna(subset=["y", "z"], how="all")
)
self.assert_eq(kdf.dropna(thresh=2), pdf.dropna(thresh=2))
self.assert_eq(
kdf.dropna(thresh=1, subset=["y", "z"]), pdf.dropna(thresh=1, subset=["y", "z"])
)
pdf2 = pdf.copy()
kdf2 = kdf.copy()
pser = pdf2.x
kser = kdf2.x
pdf2.dropna(inplace=True)
kdf2.dropna(inplace=True)
self.assert_eq(kdf2, pdf2)
self.assert_eq(kser, pser, almost=True)
msg = "dropna currently only works for axis=0 or axis='index'"
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.dropna(axis=1)
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.dropna(axis="columns")
with self.assertRaisesRegex(ValueError, "No axis named foo"):
kdf.dropna(axis="foo")
self.assertRaises(KeyError, lambda: kdf.dropna(subset="1"))
with self.assertRaisesRegex(ValueError, "invalid how option: 1"):
kdf.dropna(how=1)
with self.assertRaisesRegex(TypeError, "must specify how or thresh"):
kdf.dropna(how=None)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("a", "x"), ("a", "y"), ("b", "z")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.dropna(), pdf.dropna())
self.assert_eq(kdf.dropna(how="all"), pdf.dropna(how="all"))
self.assert_eq(kdf.dropna(subset=[("a", "x")]), pdf.dropna(subset=[("a", "x")]))
self.assert_eq(kdf.dropna(subset=("a", "x")), pdf.dropna(subset=[("a", "x")]))
self.assert_eq(
kdf.dropna(subset=[("a", "y"), ("b", "z")]), pdf.dropna(subset=[("a", "y"), ("b", "z")])
)
self.assert_eq(
kdf.dropna(subset=[("a", "y"), ("b", "z")], how="all"),
pdf.dropna(subset=[("a", "y"), ("b", "z")], how="all"),
)
self.assert_eq(kdf.dropna(thresh=2), pdf.dropna(thresh=2))
self.assert_eq(
kdf.dropna(thresh=1, subset=[("a", "y"), ("b", "z")]),
pdf.dropna(thresh=1, subset=[("a", "y"), ("b", "z")]),
)
def test_dtype(self):
pdf = pd.DataFrame(
{
"a": list("abc"),
"b": list(range(1, 4)),
"c": np.arange(3, 6).astype("i1"),
"d": np.arange(4.0, 7.0, dtype="float64"),
"e": [True, False, True],
"f": pd.date_range("20130101", periods=3),
},
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
self.assertTrue((kdf.dtypes == pdf.dtypes).all())
# multi-index columns
columns = pd.MultiIndex.from_tuples(zip(list("xxxyyz"), list("abcdef")))
pdf.columns = columns
kdf.columns = columns
self.assertTrue((kdf.dtypes == pdf.dtypes).all())
def test_fillna(self):
pdf = pd.DataFrame(
{
"x": [np.nan, 2, 3, 4, np.nan, 6],
"y": [1, 2, np.nan, 4, np.nan, np.nan],
"z": [1, 2, 3, 4, np.nan, np.nan],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
self.assert_eq(kdf.fillna(-1), pdf.fillna(-1))
self.assert_eq(
kdf.fillna({"x": -1, "y": -2, "z": -5}), pdf.fillna({"x": -1, "y": -2, "z": -5})
)
self.assert_eq(pdf.fillna(method="ffill"), kdf.fillna(method="ffill"))
self.assert_eq(pdf.fillna(method="ffill", limit=2), kdf.fillna(method="ffill", limit=2))
self.assert_eq(pdf.fillna(method="bfill"), kdf.fillna(method="bfill"))
self.assert_eq(pdf.fillna(method="bfill", limit=2), kdf.fillna(method="bfill", limit=2))
pdf = pdf.set_index(["x", "y"])
kdf = ks.from_pandas(pdf)
# check multi index
self.assert_eq(kdf.fillna(-1), pdf.fillna(-1))
self.assert_eq(pdf.fillna(method="bfill"), kdf.fillna(method="bfill"))
self.assert_eq(pdf.fillna(method="ffill"), kdf.fillna(method="ffill"))
pser = pdf.z
kser = kdf.z
pdf.fillna({"x": -1, "y": -2, "z": -5}, inplace=True)
kdf.fillna({"x": -1, "y": -2, "z": -5}, inplace=True)
self.assert_eq(kdf, pdf)
self.assert_eq(kser, pser, almost=True)
s_nan = pd.Series([-1, -2, -5], index=["x", "y", "z"], dtype=int)
self.assert_eq(kdf.fillna(s_nan), pdf.fillna(s_nan))
with self.assertRaisesRegex(NotImplementedError, "fillna currently only"):
kdf.fillna(-1, axis=1)
with self.assertRaisesRegex(NotImplementedError, "fillna currently only"):
kdf.fillna(-1, axis="columns")
with self.assertRaisesRegex(ValueError, "limit parameter for value is not support now"):
kdf.fillna(-1, limit=1)
with self.assertRaisesRegex(TypeError, "Unsupported.*DataFrame"):
kdf.fillna(pd.DataFrame({"x": [-1], "y": [-1], "z": [-1]}))
with self.assertRaisesRegex(TypeError, "Unsupported.*numpy.int64"):
kdf.fillna({"x": np.int64(-6), "y": np.int64(-4), "z": -5})
with self.assertRaisesRegex(ValueError, "Expecting 'pad', 'ffill', 'backfill' or 'bfill'."):
kdf.fillna(method="xxx")
with self.assertRaisesRegex(
ValueError, "Must specify a fillna 'value' or 'method' parameter."
):
kdf.fillna()
# multi-index columns
pdf = pd.DataFrame(
{
("x", "a"): [np.nan, 2, 3, 4, np.nan, 6],
("x", "b"): [1, 2, np.nan, 4, np.nan, np.nan],
("y", "c"): [1, 2, 3, 4, np.nan, np.nan],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.fillna(-1), pdf.fillna(-1))
self.assert_eq(
kdf.fillna({("x", "a"): -1, ("x", "b"): -2, ("y", "c"): -5}),
pdf.fillna({("x", "a"): -1, ("x", "b"): -2, ("y", "c"): -5}),
)
self.assert_eq(pdf.fillna(method="ffill"), kdf.fillna(method="ffill"))
self.assert_eq(pdf.fillna(method="ffill", limit=2), kdf.fillna(method="ffill", limit=2))
self.assert_eq(pdf.fillna(method="bfill"), kdf.fillna(method="bfill"))
self.assert_eq(pdf.fillna(method="bfill", limit=2), kdf.fillna(method="bfill", limit=2))
self.assert_eq(kdf.fillna({"x": -1}), pdf.fillna({"x": -1}))
if sys.version_info >= (3, 6):
# flaky in Python 3.5.
self.assert_eq(
kdf.fillna({"x": -1, ("x", "b"): -2}), pdf.fillna({"x": -1, ("x", "b"): -2})
)
self.assert_eq(
kdf.fillna({("x", "b"): -2, "x": -1}), pdf.fillna({("x", "b"): -2, "x": -1})
)
# check multi index
pdf = pdf.set_index([("x", "a"), ("x", "b")])
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.fillna(-1), pdf.fillna(-1))
self.assert_eq(
kdf.fillna({("x", "a"): -1, ("x", "b"): -2, ("y", "c"): -5}),
pdf.fillna({("x", "a"): -1, ("x", "b"): -2, ("y", "c"): -5}),
)
def test_isnull(self):
pdf = pd.DataFrame(
{"x": [1, 2, 3, 4, None, 6], "y": list("abdabd")}, index=np.random.rand(6)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.notnull(), pdf.notnull())
self.assert_eq(kdf.isnull(), pdf.isnull())
def test_to_datetime(self):
pdf = pd.DataFrame(
{"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}, index=np.random.rand(2)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(pd.to_datetime(pdf), ks.to_datetime(kdf))
def test_nunique(self):
pdf = pd.DataFrame({"A": [1, 2, 3], "B": [np.nan, 3, np.nan]}, index=np.random.rand(3))
kdf = ks.from_pandas(pdf)
# Assert NaNs are dropped by default
nunique_result = kdf.nunique()
self.assert_eq(nunique_result, pd.Series([3, 1], index=["A", "B"], name="0"))
self.assert_eq(nunique_result, pdf.nunique())
# Assert including NaN values
nunique_result = kdf.nunique(dropna=False)
self.assert_eq(nunique_result, pd.Series([3, 2], index=["A", "B"], name="0"))
self.assert_eq(nunique_result, pdf.nunique(dropna=False))
# Assert approximate counts
self.assert_eq(
ks.DataFrame({"A": range(100)}).nunique(approx=True),
pd.Series([103], index=["A"], name="0"),
)
self.assert_eq(
ks.DataFrame({"A": range(100)}).nunique(approx=True, rsd=0.01),
pd.Series([100], index=["A"], name="0"),
)
# Assert unsupported axis value yet
msg = 'axis should be either 0 or "index" currently.'
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.nunique(axis=1)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("X", "A"), ("Y", "B")], names=["1", "2"])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.nunique(), pdf.nunique())
self.assert_eq(kdf.nunique(dropna=False), pdf.nunique(dropna=False))
def test_sort_values(self):
pdf = pd.DataFrame(
{"a": [1, 2, 3, 4, 5, None, 7], "b": [7, 6, 5, 4, 3, 2, 1]}, index=np.random.rand(7)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.sort_values("b"), pdf.sort_values("b"))
self.assert_eq(kdf.sort_values(["b", "a"]), pdf.sort_values(["b", "a"]))
self.assert_eq(
kdf.sort_values(["b", "a"], ascending=[False, True]),
pdf.sort_values(["b", "a"], ascending=[False, True]),
)
self.assertRaises(ValueError, lambda: kdf.sort_values(["b", "a"], ascending=[False]))
self.assert_eq(
kdf.sort_values(["b", "a"], na_position="first"),
pdf.sort_values(["b", "a"], na_position="first"),
)
self.assertRaises(ValueError, lambda: kdf.sort_values(["b", "a"], na_position="invalid"))
pserA = pdf.a
kserA = kdf.a
self.assert_eq(kdf.sort_values("b", inplace=True), pdf.sort_values("b", inplace=True))
self.assert_eq(kdf, pdf)
self.assert_eq(kserA, pserA, almost=True)
columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B")])
kdf.columns = columns
self.assertRaisesRegex(
ValueError,
"For a multi-index, the label must be a tuple with elements",
lambda: kdf.sort_values(["X"]),
)
def test_sort_index(self):
pdf = pd.DataFrame(
{"A": [2, 1, np.nan], "B": [np.nan, 0, np.nan]}, index=["b", "a", np.nan]
)
kdf = ks.from_pandas(pdf)
# Assert invalid parameters
self.assertRaises(NotImplementedError, lambda: kdf.sort_index(axis=1))
self.assertRaises(NotImplementedError, lambda: kdf.sort_index(kind="mergesort"))
self.assertRaises(ValueError, lambda: kdf.sort_index(na_position="invalid"))
# Assert default behavior without parameters
self.assert_eq(kdf.sort_index(), pdf.sort_index())
# Assert sorting descending
self.assert_eq(kdf.sort_index(ascending=False), pdf.sort_index(ascending=False))
# Assert sorting NA indices first
self.assert_eq(kdf.sort_index(na_position="first"), pdf.sort_index(na_position="first"))
# Assert sorting inplace
pserA = pdf.A
kserA = kdf.A
self.assertEqual(kdf.sort_index(inplace=True), pdf.sort_index(inplace=True))
self.assert_eq(kdf, pdf)
self.assert_eq(kserA, pserA, almost=True)
# Assert multi-indices
pdf = pd.DataFrame(
{"A": range(4), "B": range(4)[::-1]}, index=[["b", "b", "a", "a"], [1, 0, 1, 0]]
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.sort_index(), pdf.sort_index())
self.assert_eq(kdf.sort_index(level=[1, 0]), pdf.sort_index(level=[1, 0]))
self.assert_eq(kdf.reset_index().sort_index(), pdf.reset_index().sort_index())
# Assert with multi-index columns
columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.sort_index(), pdf.sort_index())
def test_nlargest(self):
pdf = pd.DataFrame(
{"a": [1, 2, 3, 4, 5, None, 7], "b": [7, 6, 5, 4, 3, 2, 1]}, index=np.random.rand(7)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.nlargest(n=5, columns="a"), pdf.nlargest(5, columns="a"))
self.assert_eq(kdf.nlargest(n=5, columns=["a", "b"]), pdf.nlargest(5, columns=["a", "b"]))
def test_nsmallest(self):
pdf = pd.DataFrame(
{"a": [1, 2, 3, 4, 5, None, 7], "b": [7, 6, 5, 4, 3, 2, 1]}, index=np.random.rand(7)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.nsmallest(n=5, columns="a"), pdf.nsmallest(5, columns="a"))
self.assert_eq(kdf.nsmallest(n=5, columns=["a", "b"]), pdf.nsmallest(5, columns=["a", "b"]))
def test_xs(self):
d = {
"num_legs": [4, 4, 2, 2],
"num_wings": [0, 0, 2, 2],
"class": ["mammal", "mammal", "mammal", "bird"],
"animal": ["cat", "dog", "bat", "penguin"],
"locomotion": ["walks", "walks", "flies", "walks"],
}
kdf = ks.DataFrame(data=d)
kdf = kdf.set_index(["class", "animal", "locomotion"])
pdf = kdf.to_pandas()
self.assert_eq(kdf.xs(("mammal", "dog", "walks")), pdf.xs(("mammal", "dog", "walks")))
msg = "'key' should be string or tuple that contains strings"
with self.assertRaisesRegex(ValueError, msg):
kdf.xs(1)
msg = (
"'key' should have index names as only strings "
"or a tuple that contain index names as only strings"
)
with self.assertRaisesRegex(ValueError, msg):
kdf.xs(("mammal", 1))
msg = 'axis should be either 0 or "index" currently.'
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.xs("num_wings", axis=1)
msg = r"'Key length \(4\) exceeds index depth \(3\)'"
with self.assertRaisesRegex(KeyError, msg):
kdf.xs(("mammal", "dog", "walks", "foo"))
def test_missing(self):
kdf = self.kdf
missing_functions = inspect.getmembers(_MissingPandasLikeDataFrame, inspect.isfunction)
unsupported_functions = [
name for (name, type_) in missing_functions if type_.__name__ == "unsupported_function"
]
for name in unsupported_functions:
with self.assertRaisesRegex(
PandasNotImplementedError,
"method.*DataFrame.*{}.*not implemented( yet\\.|\\. .+)".format(name),
):
getattr(kdf, name)()
deprecated_functions = [
name for (name, type_) in missing_functions if type_.__name__ == "deprecated_function"
]
for name in deprecated_functions:
with self.assertRaisesRegex(
PandasNotImplementedError, "method.*DataFrame.*{}.*is deprecated".format(name)
):
getattr(kdf, name)()
missing_properties = inspect.getmembers(
_MissingPandasLikeDataFrame, lambda o: isinstance(o, property)
)
unsupported_properties = [
name
for (name, type_) in missing_properties
if type_.fget.__name__ == "unsupported_property"
]
for name in unsupported_properties:
with self.assertRaisesRegex(
PandasNotImplementedError,
"property.*DataFrame.*{}.*not implemented( yet\\.|\\. .+)".format(name),
):
getattr(kdf, name)
deprecated_properties = [
name
for (name, type_) in missing_properties
if type_.fget.__name__ == "deprecated_property"
]
for name in deprecated_properties:
with self.assertRaisesRegex(
PandasNotImplementedError, "property.*DataFrame.*{}.*is deprecated".format(name)
):
getattr(kdf, name)
def test_to_numpy(self):
pdf = pd.DataFrame(
{
"a": [4, 2, 3, 4, 8, 6],
"b": [1, 2, 9, 4, 2, 4],
"c": ["one", "three", "six", "seven", "one", "5"],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
np.testing.assert_equal(kdf.to_numpy(), pdf.values)
def test_to_pandas(self):
pdf, kdf = self.df_pair
self.assert_eq(kdf.toPandas(), pdf)
self.assert_eq(kdf.to_pandas(), pdf)
def test_isin(self):
pdf = pd.DataFrame(
{
"a": [4, 2, 3, 4, 8, 6],
"b": [1, 2, 9, 4, 2, 4],
"c": ["one", "three", "six", "seven", "one", "5"],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.isin([4, "six"]), pdf.isin([4, "six"]))
self.assert_eq(
kdf.isin({"a": [2, 8], "c": ["three", "one"]}),
pdf.isin({"a": [2, 8], "c": ["three", "one"]}),
)
msg = "'DataFrame' object has no attribute {'e'}"
with self.assertRaisesRegex(AttributeError, msg):
kdf.isin({"e": [5, 7], "a": [1, 6]})
msg = "DataFrame and Series are not supported"
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.isin(pdf)
msg = "Values should be iterable, Series, DataFrame or dict."
with self.assertRaisesRegex(TypeError, msg):
kdf.isin(1)
def test_merge(self):
left_pdf = pd.DataFrame(
{
"lkey": ["foo", "bar", "baz", "foo", "bar", "l"],
"value": [1, 2, 3, 5, 6, 7],
"x": list("abcdef"),
},
columns=["lkey", "value", "x"],
)
right_pdf = pd.DataFrame(
{
"rkey": ["baz", "foo", "bar", "baz", "foo", "r"],
"value": [4, 5, 6, 7, 8, 9],
"y": list("efghij"),
},
columns=["rkey", "value", "y"],
)
right_ps = pd.Series(list("defghi"), name="x", index=[5, 6, 7, 8, 9, 10])
left_kdf = ks.from_pandas(left_pdf)
right_kdf = ks.from_pandas(right_pdf)
right_kser = ks.from_pandas(right_ps)
def check(op, right_kdf=right_kdf, right_pdf=right_pdf):
k_res = op(left_kdf, right_kdf)
k_res = k_res.to_pandas()
k_res = k_res.sort_values(by=list(k_res.columns))
k_res = k_res.reset_index(drop=True)
p_res = op(left_pdf, right_pdf)
p_res = p_res.sort_values(by=list(p_res.columns))
p_res = p_res.reset_index(drop=True)
self.assert_eq(k_res, p_res)
check(lambda left, right: left.merge(right))
check(lambda left, right: left.merge(right, on="value"))
check(lambda left, right: left.merge(right, left_on="lkey", right_on="rkey"))
check(lambda left, right: left.set_index("lkey").merge(right.set_index("rkey")))
check(
lambda left, right: left.set_index("lkey").merge(
right, left_index=True, right_on="rkey"
)
)
check(
lambda left, right: left.merge(
right.set_index("rkey"), left_on="lkey", right_index=True
)
)
check(
lambda left, right: left.set_index("lkey").merge(
right.set_index("rkey"), left_index=True, right_index=True
)
)
# MultiIndex
check(
lambda left, right: left.merge(
right, left_on=["lkey", "value"], right_on=["rkey", "value"]
)
)
check(
lambda left, right: left.set_index(["lkey", "value"]).merge(
right, left_index=True, right_on=["rkey", "value"]
)
)
check(
lambda left, right: left.merge(
right.set_index(["rkey", "value"]), left_on=["lkey", "value"], right_index=True
)
)
# TODO: when both left_index=True and right_index=True with multi-index
# check(lambda left, right: left.set_index(['lkey', 'value']).merge(
# right.set_index(['rkey', 'value']), left_index=True, right_index=True))
# join types
for how in ["inner", "left", "right", "outer"]:
check(lambda left, right: left.merge(right, on="value", how=how))
check(lambda left, right: left.merge(right, left_on="lkey", right_on="rkey", how=how))
# suffix
check(
lambda left, right: left.merge(
right, left_on="lkey", right_on="rkey", suffixes=["_left", "_right"]
)
)
# Test Series on the right
# pd.DataFrame.merge with Series is implemented since version 0.24.0
if LooseVersion(pd.__version__) >= LooseVersion("0.24.0"):
check(lambda left, right: left.merge(right), right_kser, right_ps)
check(
lambda left, right: left.merge(right, left_on="x", right_on="x"),
right_kser,
right_ps,
)
check(
lambda left, right: left.set_index("x").merge(right, left_index=True, right_on="x"),
right_kser,
right_ps,
)
# Test join types with Series
for how in ["inner", "left", "right", "outer"]:
check(lambda left, right: left.merge(right, how=how), right_kser, right_ps)
check(
lambda left, right: left.merge(right, left_on="x", right_on="x", how=how),
right_kser,
right_ps,
)
# suffix with Series
check(
lambda left, right: left.merge(
right,
suffixes=["_left", "_right"],
how="outer",
left_index=True,
right_index=True,
),
right_kser,
right_ps,
)
# multi-index columns
left_columns = pd.MultiIndex.from_tuples([("a", "lkey"), ("a", "value"), ("b", "x")])
left_pdf.columns = left_columns
left_kdf.columns = left_columns
right_columns = pd.MultiIndex.from_tuples([("a", "rkey"), ("a", "value"), ("c", "y")])
right_pdf.columns = right_columns
right_kdf.columns = right_columns
check(lambda left, right: left.merge(right))
check(lambda left, right: left.merge(right, on=[("a", "value")]))
check(
lambda left, right: (
left.set_index(("a", "lkey")).merge(right.set_index(("a", "rkey")))
)
)
check(
lambda left, right: (
left.set_index(("a", "lkey")).merge(
right.set_index(("a", "rkey")), left_index=True, right_index=True
)
)
)
# TODO: when both left_index=True and right_index=True with multi-index columns
# check(lambda left, right: left.merge(right,
# left_on=[('a', 'lkey')], right_on=[('a', 'rkey')]))
# check(lambda left, right: (left.set_index(('a', 'lkey'))
# .merge(right, left_index=True, right_on=[('a', 'rkey')])))
def test_merge_retains_indices(self):
left_pdf = pd.DataFrame({"A": [0, 1]})
right_pdf = pd.DataFrame({"B": [1, 2]}, index=[1, 2])
left_kdf = ks.from_pandas(left_pdf)
right_kdf = ks.from_pandas(right_pdf)
self.assert_eq(
left_kdf.merge(right_kdf, left_index=True, right_index=True),
left_pdf.merge(right_pdf, left_index=True, right_index=True),
)
self.assert_eq(
left_kdf.merge(right_kdf, left_on="A", right_index=True),
left_pdf.merge(right_pdf, left_on="A", right_index=True),
)
self.assert_eq(
left_kdf.merge(right_kdf, left_index=True, right_on="B"),
left_pdf.merge(right_pdf, left_index=True, right_on="B"),
)
self.assert_eq(
left_kdf.merge(right_kdf, left_on="A", right_on="B"),
left_pdf.merge(right_pdf, left_on="A", right_on="B"),
)
def test_merge_how_parameter(self):
left_pdf = pd.DataFrame({"A": [1, 2]})
right_pdf = pd.DataFrame({"B": ["x", "y"]}, index=[1, 2])
left_kdf = ks.from_pandas(left_pdf)
right_kdf = ks.from_pandas(right_pdf)
kdf = left_kdf.merge(right_kdf, left_index=True, right_index=True)
pdf = left_pdf.merge(right_pdf, left_index=True, right_index=True)
self.assert_eq(
kdf.sort_values(by=list(kdf.columns)).reset_index(drop=True),
pdf.sort_values(by=list(pdf.columns)).reset_index(drop=True),
)
kdf = left_kdf.merge(right_kdf, left_index=True, right_index=True, how="left")
pdf = left_pdf.merge(right_pdf, left_index=True, right_index=True, how="left")
self.assert_eq(
kdf.sort_values(by=list(kdf.columns)).reset_index(drop=True),
pdf.sort_values(by=list(pdf.columns)).reset_index(drop=True),
)
kdf = left_kdf.merge(right_kdf, left_index=True, right_index=True, how="right")
pdf = left_pdf.merge(right_pdf, left_index=True, right_index=True, how="right")
self.assert_eq(
kdf.sort_values(by=list(kdf.columns)).reset_index(drop=True),
pdf.sort_values(by=list(pdf.columns)).reset_index(drop=True),
)
kdf = left_kdf.merge(right_kdf, left_index=True, right_index=True, how="outer")
pdf = left_pdf.merge(right_pdf, left_index=True, right_index=True, how="outer")
self.assert_eq(
kdf.sort_values(by=list(kdf.columns)).reset_index(drop=True),
pdf.sort_values(by=list(pdf.columns)).reset_index(drop=True),
)
def test_merge_raises(self):
left = ks.DataFrame(
{"value": [1, 2, 3, 5, 6], "x": list("abcde")},
columns=["value", "x"],
index=["foo", "bar", "baz", "foo", "bar"],
)
right = ks.DataFrame(
{"value": [4, 5, 6, 7, 8], "y": list("fghij")},
columns=["value", "y"],
index=["baz", "foo", "bar", "baz", "foo"],
)
with self.assertRaisesRegex(ValueError, "No common columns to perform merge on"):
left[["x"]].merge(right[["y"]])
with self.assertRaisesRegex(ValueError, "not a combination of both"):
left.merge(right, on="value", left_on="x")
with self.assertRaisesRegex(ValueError, "Must pass right_on or right_index=True"):
left.merge(right, left_on="x")
with self.assertRaisesRegex(ValueError, "Must pass right_on or right_index=True"):
left.merge(right, left_index=True)
with self.assertRaisesRegex(ValueError, "Must pass left_on or left_index=True"):
left.merge(right, right_on="y")
with self.assertRaisesRegex(ValueError, "Must pass left_on or left_index=True"):
left.merge(right, right_index=True)
with self.assertRaisesRegex(
ValueError, "len\\(left_keys\\) must equal len\\(right_keys\\)"
):
left.merge(right, left_on="value", right_on=["value", "y"])
with self.assertRaisesRegex(
ValueError, "len\\(left_keys\\) must equal len\\(right_keys\\)"
):
left.merge(right, left_on=["value", "x"], right_on="value")
with self.assertRaisesRegex(ValueError, "['inner', 'left', 'right', 'full', 'outer']"):
left.merge(right, left_index=True, right_index=True, how="foo")
with self.assertRaisesRegex(KeyError, "id"):
left.merge(right, on="id")
def test_append(self):
pdf = pd.DataFrame([[1, 2], [3, 4]], columns=list("AB"))
kdf = ks.from_pandas(pdf)
other_pdf = pd.DataFrame([[3, 4], [5, 6]], columns=list("BC"), index=[2, 3])
other_kdf = ks.from_pandas(other_pdf)
self.assert_eq(kdf.append(kdf), pdf.append(pdf))
self.assert_eq(kdf.append(kdf, ignore_index=True), pdf.append(pdf, ignore_index=True))
# Assert DataFrames with non-matching columns
self.assert_eq(kdf.append(other_kdf), pdf.append(other_pdf))
# Assert appending a Series fails
msg = "DataFrames.append() does not support appending Series to DataFrames"
with self.assertRaises(ValueError, msg=msg):
kdf.append(kdf["A"])
# Assert using the sort parameter raises an exception
msg = "The 'sort' parameter is currently not supported"
with self.assertRaises(NotImplementedError, msg=msg):
kdf.append(kdf, sort=True)
# Assert using 'verify_integrity' only raises an exception for overlapping indices
self.assert_eq(
kdf.append(other_kdf, verify_integrity=True),
pdf.append(other_pdf, verify_integrity=True),
)
msg = "Indices have overlapping values"
with self.assertRaises(ValueError, msg=msg):
kdf.append(kdf, verify_integrity=True)
# Skip integrity verification when ignore_index=True
self.assert_eq(
kdf.append(kdf, ignore_index=True, verify_integrity=True),
pdf.append(pdf, ignore_index=True, verify_integrity=True),
)
# Assert appending multi-index DataFrames
multi_index_pdf = pd.DataFrame([[1, 2], [3, 4]], columns=list("AB"), index=[[2, 3], [4, 5]])
multi_index_kdf = ks.from_pandas(multi_index_pdf)
other_multi_index_pdf = pd.DataFrame(
[[5, 6], [7, 8]], columns=list("AB"), index=[[2, 3], [6, 7]]
)
other_multi_index_kdf = ks.from_pandas(other_multi_index_pdf)
self.assert_eq(
multi_index_kdf.append(multi_index_kdf), multi_index_pdf.append(multi_index_pdf)
)
# Assert DataFrames with non-matching columns
self.assert_eq(
multi_index_kdf.append(other_multi_index_kdf),
multi_index_pdf.append(other_multi_index_pdf),
)
# Assert using 'verify_integrity' only raises an exception for overlapping indices
self.assert_eq(
multi_index_kdf.append(other_multi_index_kdf, verify_integrity=True),
multi_index_pdf.append(other_multi_index_pdf, verify_integrity=True),
)
with self.assertRaises(ValueError, msg=msg):
multi_index_kdf.append(multi_index_kdf, verify_integrity=True)
# Skip integrity verification when ignore_index=True
self.assert_eq(
multi_index_kdf.append(multi_index_kdf, ignore_index=True, verify_integrity=True),
multi_index_pdf.append(multi_index_pdf, ignore_index=True, verify_integrity=True),
)
# Assert trying to append DataFrames with different index levels
msg = "Both DataFrames have to have the same number of index levels"
with self.assertRaises(ValueError, msg=msg):
kdf.append(multi_index_kdf)
# Skip index level check when ignore_index=True
self.assert_eq(
kdf.append(multi_index_kdf, ignore_index=True),
pdf.append(multi_index_pdf, ignore_index=True),
)
columns = pd.MultiIndex.from_tuples([("A", "X"), ("A", "Y")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.append(kdf), pdf.append(pdf))
def test_clip(self):
pdf = pd.DataFrame(
{"A": [0, 2, 4], "B": [4, 2, 0], "X": [-1, 10, 0]}, index=np.random.rand(3)
)
kdf = ks.from_pandas(pdf)
# Assert list-like values are not accepted for 'lower' and 'upper'
msg = "List-like value are not supported for 'lower' and 'upper' at the moment"
with self.assertRaises(ValueError, msg=msg):
kdf.clip(lower=[1])
with self.assertRaises(ValueError, msg=msg):
kdf.clip(upper=[1])
# Assert no lower or upper
self.assert_eq(kdf.clip(), pdf.clip())
# Assert lower only
self.assert_eq(kdf.clip(1), pdf.clip(1))
# Assert upper only
self.assert_eq(kdf.clip(upper=3), pdf.clip(upper=3))
# Assert lower and upper
self.assert_eq(kdf.clip(1, 3), pdf.clip(1, 3))
pdf["clip"] = pdf.A.clip(lower=1, upper=3)
kdf["clip"] = kdf.A.clip(lower=1, upper=3)
self.assert_eq(kdf, pdf)
# Assert behavior on string values
str_kdf = ks.DataFrame({"A": ["a", "b", "c"]}, index=np.random.rand(3))
self.assert_eq(str_kdf.clip(1, 3), str_kdf)
def test_binary_operators(self):
pdf = pd.DataFrame(
{"A": [0, 2, 4], "B": [4, 2, 0], "X": [-1, 10, 0]}, index=np.random.rand(3)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf + kdf.copy(), pdf + pdf.copy())
self.assertRaisesRegex(
ValueError,
"it comes from a different dataframe",
lambda: ks.range(10).add(ks.range(10)),
)
self.assertRaisesRegex(
ValueError,
"add with a sequence is currently not supported",
lambda: ks.range(10).add(ks.range(10).id),
)
def test_sample(self):
pdf = pd.DataFrame({"A": [0, 2, 4]})
kdf = ks.from_pandas(pdf)
# Make sure the tests run, but we can't check the result because they are non-deterministic.
kdf.sample(frac=0.1)
kdf.sample(frac=0.2, replace=True)
kdf.sample(frac=0.2, random_state=5)
kdf["A"].sample(frac=0.2)
kdf["A"].sample(frac=0.2, replace=True)
kdf["A"].sample(frac=0.2, random_state=5)
with self.assertRaises(ValueError):
kdf.sample()
with self.assertRaises(NotImplementedError):
kdf.sample(n=1)
def test_add_prefix(self):
pdf = pd.DataFrame({"A": [1, 2, 3, 4], "B": [3, 4, 5, 6]}, index=np.random.rand(4))
kdf = ks.from_pandas(pdf)
self.assert_eq(pdf.add_prefix("col_"), kdf.add_prefix("col_"))
columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(pdf.add_prefix("col_"), kdf.add_prefix("col_"))
def test_add_suffix(self):
pdf = pd.DataFrame({"A": [1, 2, 3, 4], "B": [3, 4, 5, 6]}, index=np.random.rand(4))
kdf = ks.from_pandas(pdf)
self.assert_eq(pdf.add_suffix("first_series"), kdf.add_suffix("first_series"))
columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(pdf.add_suffix("first_series"), kdf.add_suffix("first_series"))
def test_join(self):
# check basic function
pdf1 = pd.DataFrame(
{"key": ["K0", "K1", "K2", "K3"], "A": ["A0", "A1", "A2", "A3"]}, columns=["key", "A"]
)
pdf2 = pd.DataFrame(
{"key": ["K0", "K1", "K2"], "B": ["B0", "B1", "B2"]}, columns=["key", "B"]
)
kdf1 = ks.DataFrame(
{"key": ["K0", "K1", "K2", "K3"], "A": ["A0", "A1", "A2", "A3"]}, columns=["key", "A"]
)
kdf2 = ks.DataFrame(
{"key": ["K0", "K1", "K2"], "B": ["B0", "B1", "B2"]}, columns=["key", "B"]
)
ks1 = ks.Series(["A1", "A5"], index=[1, 2], name="A")
join_pdf = pdf1.join(pdf2, lsuffix="_left", rsuffix="_right")
join_pdf.sort_values(by=list(join_pdf.columns), inplace=True)
join_kdf = kdf1.join(kdf2, lsuffix="_left", rsuffix="_right")
join_kdf.sort_values(by=list(join_kdf.columns), inplace=True)
self.assert_eq(join_pdf, join_kdf)
# join with duplicated columns in Series
with self.assertRaisesRegex(ValueError, "columns overlap but no suffix specified"):
kdf1.join(ks1, how="outer")
# join with duplicated columns in DataFrame
with self.assertRaisesRegex(ValueError, "columns overlap but no suffix specified"):
kdf1.join(kdf2, how="outer")
# check `on` parameter
join_pdf = pdf1.join(pdf2.set_index("key"), on="key", lsuffix="_left", rsuffix="_right")
join_pdf.sort_values(by=list(join_pdf.columns), inplace=True)
join_kdf = kdf1.join(kdf2.set_index("key"), on="key", lsuffix="_left", rsuffix="_right")
join_kdf.sort_values(by=list(join_kdf.columns), inplace=True)
self.assert_eq(join_pdf.reset_index(drop=True), join_kdf.reset_index(drop=True))
# multi-index columns
columns1 = pd.MultiIndex.from_tuples([("x", "key"), ("Y", "A")])
columns2 = pd.MultiIndex.from_tuples([("x", "key"), ("Y", "B")])
pdf1.columns = columns1
pdf2.columns = columns2
kdf1.columns = columns1
kdf2.columns = columns2
join_pdf = pdf1.join(pdf2, lsuffix="_left", rsuffix="_right")
join_pdf.sort_values(by=list(join_pdf.columns), inplace=True)
join_kdf = kdf1.join(kdf2, lsuffix="_left", rsuffix="_right")
join_kdf.sort_values(by=list(join_kdf.columns), inplace=True)
self.assert_eq(join_pdf, join_kdf)
# check `on` parameter
join_pdf = pdf1.join(
pdf2.set_index(("x", "key")), on=[("x", "key")], lsuffix="_left", rsuffix="_right"
)
join_pdf.sort_values(by=list(join_pdf.columns), inplace=True)
join_kdf = kdf1.join(
kdf2.set_index(("x", "key")), on=[("x", "key")], lsuffix="_left", rsuffix="_right"
)
join_kdf.sort_values(by=list(join_kdf.columns), inplace=True)
self.assert_eq(join_pdf.reset_index(drop=True), join_kdf.reset_index(drop=True))
def test_replace(self):
pdf = pd.DataFrame(
{
"name": ["Ironman", "Captain America", "Thor", "Hulk"],
"weapon": ["Mark-45", "Shield", "Mjolnir", "Smash"],
},
index=np.random.rand(4),
)
kdf = ks.from_pandas(pdf)
with self.assertRaisesRegex(
NotImplementedError, "replace currently works only for method='pad"
):
kdf.replace(method="bfill")
with self.assertRaisesRegex(
NotImplementedError, "replace currently works only when limit=None"
):
kdf.replace(limit=10)
with self.assertRaisesRegex(
NotImplementedError, "replace currently doesn't supports regex"
):
kdf.replace(regex="")
with self.assertRaisesRegex(TypeError, "Unsupported type <class 'tuple'>"):
kdf.replace(value=(1, 2, 3))
with self.assertRaisesRegex(TypeError, "Unsupported type <class 'tuple'>"):
kdf.replace(to_replace=(1, 2, 3))
with self.assertRaisesRegex(ValueError, "Length of to_replace and value must be same"):
kdf.replace(to_replace=["Ironman"], value=["Spiderman", "Doctor Strange"])
self.assert_eq(kdf.replace("Ironman", "Spiderman"), pdf.replace("Ironman", "Spiderman"))
self.assert_eq(
kdf.replace(["Ironman", "Captain America"], ["Rescue", "Hawkeye"]),
pdf.replace(["Ironman", "Captain America"], ["Rescue", "Hawkeye"]),
)
# inplace
pser = pdf.name
kser = kdf.name
pdf.replace("Ironman", "Spiderman", inplace=True)
kdf.replace("Ironman", "Spiderman", inplace=True)
self.assert_eq(kdf, pdf)
self.assert_eq(kser, pser)
pdf = pd.DataFrame(
{"A": [0, 1, 2, 3, 4], "B": [5, 6, 7, 8, 9], "C": ["a", "b", "c", "d", "e"]},
index=np.random.rand(5),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.replace([0, 1, 2, 3, 5, 6], 4), pdf.replace([0, 1, 2, 3, 5, 6], 4))
self.assert_eq(
kdf.replace([0, 1, 2, 3, 5, 6], [6, 5, 4, 3, 2, 1]),
pdf.replace([0, 1, 2, 3, 5, 6], [6, 5, 4, 3, 2, 1]),
)
self.assert_eq(kdf.replace({0: 10, 1: 100, 7: 200}), pdf.replace({0: 10, 1: 100, 7: 200}))
self.assert_eq(kdf.replace({"A": 0, "B": 5}, 100), pdf.replace({"A": 0, "B": 5}, 100))
self.assert_eq(kdf.replace({"A": {0: 100, 4: 400}}), pdf.replace({"A": {0: 100, 4: 400}}))
self.assert_eq(kdf.replace({"X": {0: 100, 4: 400}}), pdf.replace({"X": {0: 100, 4: 400}}))
# multi-index columns
columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.replace([0, 1, 2, 3, 5, 6], 4), pdf.replace([0, 1, 2, 3, 5, 6], 4))
self.assert_eq(
kdf.replace([0, 1, 2, 3, 5, 6], [6, 5, 4, 3, 2, 1]),
pdf.replace([0, 1, 2, 3, 5, 6], [6, 5, 4, 3, 2, 1]),
)
self.assert_eq(kdf.replace({0: 10, 1: 100, 7: 200}), pdf.replace({0: 10, 1: 100, 7: 200}))
self.assert_eq(
kdf.replace({("X", "A"): 0, ("X", "B"): 5}, 100),
pdf.replace({("X", "A"): 0, ("X", "B"): 5}, 100),
)
self.assert_eq(
kdf.replace({("X", "A"): {0: 100, 4: 400}}), pdf.replace({("X", "A"): {0: 100, 4: 400}})
)
self.assert_eq(
kdf.replace({("X", "B"): {0: 100, 4: 400}}), pdf.replace({("X", "B"): {0: 100, 4: 400}})
)
def test_update(self):
# check base function
def get_data(left_columns=None, right_columns=None):
left_pdf = pd.DataFrame(
{"A": ["1", "2", "3", "4"], "B": ["100", "200", np.nan, np.nan]}, columns=["A", "B"]
)
right_pdf = pd.DataFrame(
{"B": ["x", np.nan, "y", np.nan], "C": ["100", "200", "300", "400"]},
columns=["B", "C"],
)
left_kdf = ks.DataFrame(
{"A": ["1", "2", "3", "4"], "B": ["100", "200", None, None]}, columns=["A", "B"]
)
right_kdf = ks.DataFrame(
{"B": ["x", None, "y", None], "C": ["100", "200", "300", "400"]}, columns=["B", "C"]
)
if left_columns is not None:
left_pdf.columns = left_columns
left_kdf.columns = left_columns
if right_columns is not None:
right_pdf.columns = right_columns
right_kdf.columns = right_columns
return left_kdf, left_pdf, right_kdf, right_pdf
left_kdf, left_pdf, right_kdf, right_pdf = get_data()
pser = left_pdf.B
kser = left_kdf.B
left_pdf.update(right_pdf)
left_kdf.update(right_kdf)
self.assert_eq(left_pdf.sort_values(by=["A", "B"]), left_kdf.sort_values(by=["A", "B"]))
self.assert_eq(kser.sort_index(), pser.sort_index(), almost=True)
left_kdf, left_pdf, right_kdf, right_pdf = get_data()
left_pdf.update(right_pdf, overwrite=False)
left_kdf.update(right_kdf, overwrite=False)
self.assert_eq(left_pdf.sort_values(by=["A", "B"]), left_kdf.sort_values(by=["A", "B"]))
with self.assertRaises(NotImplementedError):
left_kdf.update(right_kdf, join="right")
# multi-index columns
left_columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B")])
right_columns = pd.MultiIndex.from_tuples([("X", "B"), ("Y", "C")])
left_kdf, left_pdf, right_kdf, right_pdf = get_data(
left_columns=left_columns, right_columns=right_columns
)
left_pdf.update(right_pdf)
left_kdf.update(right_kdf)
self.assert_eq(
left_pdf.sort_values(by=[("X", "A"), ("X", "B")]),
left_kdf.sort_values(by=[("X", "A"), ("X", "B")]),
)
left_kdf, left_pdf, right_kdf, right_pdf = get_data(
left_columns=left_columns, right_columns=right_columns
)
left_pdf.update(right_pdf, overwrite=False)
left_kdf.update(right_kdf, overwrite=False)
self.assert_eq(
left_pdf.sort_values(by=[("X", "A"), ("X", "B")]),
left_kdf.sort_values(by=[("X", "A"), ("X", "B")]),
)
right_columns = pd.MultiIndex.from_tuples([("Y", "B"), ("Y", "C")])
left_kdf, left_pdf, right_kdf, right_pdf = get_data(
left_columns=left_columns, right_columns=right_columns
)
left_pdf.update(right_pdf)
left_kdf.update(right_kdf)
self.assert_eq(
left_pdf.sort_values(by=[("X", "A"), ("X", "B")]),
left_kdf.sort_values(by=[("X", "A"), ("X", "B")]),
)
def test_pivot_table_dtypes(self):
pdf = pd.DataFrame(
{
"a": [4, 2, 3, 4, 8, 6],
"b": [1, 2, 2, 4, 2, 4],
"e": [1, 2, 2, 4, 2, 4],
"c": [1, 2, 9, 4, 7, 4],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
# Skip columns comparison by reset_index
res_df = kdf.pivot_table(
index=["c"], columns="a", values=["b"], aggfunc={"b": "mean"}
).dtypes.reset_index(drop=True)
exp_df = pdf.pivot_table(
index=["c"], columns="a", values=["b"], aggfunc={"b": "mean"}
).dtypes.reset_index(drop=True)
self.assert_eq(res_df, exp_df)
# Results don't have the same column's name
# Todo: self.assert_eq(kdf.pivot_table(columns="a", values="b").dtypes,
# pdf.pivot_table(columns="a", values="b").dtypes)
# Todo: self.assert_eq(kdf.pivot_table(index=['c'], columns="a", values="b").dtypes,
# pdf.pivot_table(index=['c'], columns="a", values="b").dtypes)
# Todo: self.assert_eq(kdf.pivot_table(index=['e', 'c'], columns="a", values="b").dtypes,
# pdf.pivot_table(index=['e', 'c'], columns="a", values="b").dtypes)
# Todo: self.assert_eq(kdf.pivot_table(index=['e', 'c'],
# columns="a", values="b", fill_value=999).dtypes, pdf.pivot_table(index=['e', 'c'],
# columns="a", values="b", fill_value=999).dtypes)
def test_pivot_table(self):
pdf = pd.DataFrame(
{
"a": [4, 2, 3, 4, 8, 6],
"b": [1, 2, 2, 4, 2, 4],
"e": [10, 20, 20, 40, 20, 40],
"c": [1, 2, 9, 4, 7, 4],
"d": [-1, -2, -3, -4, -5, -6],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
# Checking if both DataFrames have the same results
self.assert_eq(
kdf.pivot_table(columns="a", values="b").sort_index(),
pdf.pivot_table(columns="a", values="b").sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(index=["c"], columns="a", values="b").sort_index(),
pdf.pivot_table(index=["c"], columns="a", values="b").sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(index=["c"], columns="a", values="b", aggfunc="sum").sort_index(),
pdf.pivot_table(index=["c"], columns="a", values="b", aggfunc="sum").sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(index=["c"], columns="a", values=["b"], aggfunc="sum").sort_index(),
pdf.pivot_table(index=["c"], columns="a", values=["b"], aggfunc="sum").sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(
index=["c"], columns="a", values=["b", "e"], aggfunc="sum"
).sort_index(),
pdf.pivot_table(
index=["c"], columns="a", values=["b", "e"], aggfunc="sum"
).sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(
index=["c"], columns="a", values=["b", "e", "d"], aggfunc="sum"
).sort_index(),
pdf.pivot_table(
index=["c"], columns="a", values=["b", "e", "d"], aggfunc="sum"
).sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(
index=["c"], columns="a", values=["b", "e"], aggfunc={"b": "mean", "e": "sum"}
).sort_index(),
pdf.pivot_table(
index=["c"], columns="a", values=["b", "e"], aggfunc={"b": "mean", "e": "sum"}
).sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(index=["e", "c"], columns="a", values="b").sort_index(),
pdf.pivot_table(index=["e", "c"], columns="a", values="b").sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(index=["e", "c"], columns="a", values="b", fill_value=999).sort_index(),
pdf.pivot_table(index=["e", "c"], columns="a", values="b", fill_value=999).sort_index(),
almost=True,
)
# multi-index columns
columns = pd.MultiIndex.from_tuples(
[("x", "a"), ("x", "b"), ("y", "e"), ("z", "c"), ("w", "d")]
)
pdf.columns = columns
kdf.columns = columns
self.assert_eq(
kdf.pivot_table(columns=("x", "a"), values=("x", "b")).sort_index(),
pdf.pivot_table(columns=[("x", "a")], values=[("x", "b")]).sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(
index=[("z", "c")], columns=("x", "a"), values=[("x", "b")]
).sort_index(),
pdf.pivot_table(
index=[("z", "c")], columns=[("x", "a")], values=[("x", "b")]
).sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(
index=[("z", "c")], columns=("x", "a"), values=[("x", "b"), ("y", "e")]
).sort_index(),
pdf.pivot_table(
index=[("z", "c")], columns=[("x", "a")], values=[("x", "b"), ("y", "e")]
).sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(
index=[("z", "c")], columns=("x", "a"), values=[("x", "b"), ("y", "e"), ("w", "d")]
).sort_index(),
pdf.pivot_table(
index=[("z", "c")],
columns=[("x", "a")],
values=[("x", "b"), ("y", "e"), ("w", "d")],
).sort_index(),
almost=True,
)
self.assert_eq(
kdf.pivot_table(
index=[("z", "c")],
columns=("x", "a"),
values=[("x", "b"), ("y", "e")],
aggfunc={("x", "b"): "mean", ("y", "e"): "sum"},
).sort_index(),
pdf.pivot_table(
index=[("z", "c")],
columns=[("x", "a")],
values=[("x", "b"), ("y", "e")],
aggfunc={("x", "b"): "mean", ("y", "e"): "sum"},
).sort_index(),
almost=True,
)
def test_pivot_table_and_index(self):
# https://github.com/databricks/koalas/issues/805
pdf = pd.DataFrame(
{
"A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
"C": [
"small",
"large",
"large",
"small",
"small",
"large",
"small",
"small",
"large",
],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
},
columns=["A", "B", "C", "D", "E"],
index=np.random.rand(9),
)
kdf = ks.from_pandas(pdf)
ptable = pdf.pivot_table(
values="D", index=["A", "B"], columns="C", aggfunc="sum", fill_value=0
).sort_index()
ktable = kdf.pivot_table(
values="D", index=["A", "B"], columns="C", aggfunc="sum", fill_value=0
).sort_index()
self.assert_eq(ktable, ptable)
self.assert_eq(ktable.index, ptable.index)
self.assert_eq(repr(ktable.index), repr(ptable.index))
@unittest.skipIf(
LooseVersion(pyspark.__version__) < LooseVersion("2.4"),
"stack won't work property with PySpark<2.4",
)
def test_stack(self):
pdf_single_level_cols = pd.DataFrame(
[[0, 1], [2, 3]], index=["cat", "dog"], columns=["weight", "height"]
)
kdf_single_level_cols = ks.from_pandas(pdf_single_level_cols)
self.assert_eq(
kdf_single_level_cols.stack().sort_index(), pdf_single_level_cols.stack().sort_index()
)
multicol1 = pd.MultiIndex.from_tuples(
[("weight", "kg"), ("weight", "pounds")], names=["x", "y"]
)
pdf_multi_level_cols1 = pd.DataFrame(
[[1, 2], [2, 4]], index=["cat", "dog"], columns=multicol1
)
kdf_multi_level_cols1 = ks.from_pandas(pdf_multi_level_cols1)
self.assert_eq(
kdf_multi_level_cols1.stack().sort_index(), pdf_multi_level_cols1.stack().sort_index()
)
multicol2 = pd.MultiIndex.from_tuples([("weight", "kg"), ("height", "m")])
pdf_multi_level_cols2 = pd.DataFrame(
[[1.0, 2.0], [3.0, 4.0]], index=["cat", "dog"], columns=multicol2
)
kdf_multi_level_cols2 = ks.from_pandas(pdf_multi_level_cols2)
self.assert_eq(
kdf_multi_level_cols2.stack().sort_index(), pdf_multi_level_cols2.stack().sort_index()
)
pdf = pd.DataFrame(
{
("y", "c"): [True, True],
("x", "b"): [False, False],
("x", "c"): [True, False],
("y", "a"): [False, True],
}
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.stack().sort_index(), pdf.stack().sort_index(), almost=True)
self.assert_eq(kdf[[]].stack().sort_index(), pdf[[]].stack().sort_index(), almost=True)
def test_unstack(self):
pdf = pd.DataFrame(
np.random.randn(3, 3),
index=pd.MultiIndex.from_tuples([("rg1", "x"), ("rg1", "y"), ("rg2", "z")]),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.unstack().sort_index(), pdf.unstack().sort_index(), almost=True)
def test_pivot_errors(self):
kdf = ks.range(10)
with self.assertRaisesRegex(ValueError, "columns should be set"):
kdf.pivot(index="id")
with self.assertRaisesRegex(ValueError, "values should be set"):
kdf.pivot(index="id", columns="id")
def test_pivot_table_errors(self):
pdf = pd.DataFrame(
{
"a": [4, 2, 3, 4, 8, 6],
"b": [1, 2, 2, 4, 2, 4],
"e": [1, 2, 2, 4, 2, 4],
"c": [1, 2, 9, 4, 7, 4],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
msg = "values should be string or list of one column."
with self.assertRaisesRegex(ValueError, msg):
kdf.pivot_table(index=["c"], columns="a", values=5)
msg = "index should be a None or a list of columns."
with self.assertRaisesRegex(ValueError, msg):
kdf.pivot_table(index="c", columns="a", values="b")
msg = "pivot_table doesn't support aggfunc as dict and without index."
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.pivot_table(columns="a", values=["b", "e"], aggfunc={"b": "mean", "e": "sum"})
msg = "columns should be string."
with self.assertRaisesRegex(ValueError, msg):
kdf.pivot_table(columns=["a"], values=["b"], aggfunc={"b": "mean", "e": "sum"})
msg = "Columns in aggfunc must be the same as values."
with self.assertRaisesRegex(ValueError, msg):
kdf.pivot_table(
index=["e", "c"], columns="a", values="b", aggfunc={"b": "mean", "e": "sum"}
)
msg = "values can't be a list without index."
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.pivot_table(columns="a", values=["b", "e"])
msg = "Wrong columns A."
with self.assertRaisesRegex(ValueError, msg):
kdf.pivot_table(
index=["c"], columns="A", values=["b", "e"], aggfunc={"b": "mean", "e": "sum"}
)
kdf = ks.DataFrame(
{
"A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
"C": [
"small",
"large",
"large",
"small",
"small",
"large",
"small",
"small",
"large",
],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
},
columns=["A", "B", "C", "D", "E"],
index=np.random.rand(9),
)
msg = "values should be a numeric type."
with self.assertRaisesRegex(TypeError, msg):
kdf.pivot_table(
index=["C"], columns="A", values=["B", "E"], aggfunc={"B": "mean", "E": "sum"}
)
msg = "values should be a numeric type."
with self.assertRaisesRegex(TypeError, msg):
kdf.pivot_table(index=["C"], columns="A", values="B", aggfunc={"B": "mean"})
def test_transpose(self):
# TODO: what if with random index?
pdf1 = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}, columns=["col1", "col2"])
kdf1 = ks.from_pandas(pdf1)
pdf2 = pd.DataFrame(
data={"score": [9, 8], "kids": [0, 0], "age": [12, 22]},
columns=["score", "kids", "age"],
)
kdf2 = ks.from_pandas(pdf2)
self.assertEqual(repr(pdf1.transpose().sort_index()), repr(kdf1.transpose().sort_index()))
self.assert_eq(repr(pdf2.transpose().sort_index()), repr(kdf2.transpose().sort_index()))
with option_context("compute.max_rows", None):
self.assertEqual(
repr(pdf1.transpose().sort_index()), repr(kdf1.transpose().sort_index())
)
self.assert_eq(repr(pdf2.transpose().sort_index()), repr(kdf2.transpose().sort_index()))
pdf3 = pd.DataFrame(
{
("cg1", "a"): [1, 2, 3],
("cg1", "b"): [4, 5, 6],
("cg2", "c"): [7, 8, 9],
("cg3", "d"): [9, 9, 9],
},
index=pd.MultiIndex.from_tuples([("rg1", "x"), ("rg1", "y"), ("rg2", "z")]),
)
kdf3 = ks.from_pandas(pdf3)
self.assertEqual(repr(pdf3.transpose().sort_index()), repr(kdf3.transpose().sort_index()))
with option_context("compute.max_rows", None):
self.assertEqual(
repr(pdf3.transpose().sort_index()), repr(kdf3.transpose().sort_index())
)
def _test_cummin(self, pdf, kdf):
self.assert_eq(pdf.cummin(), kdf.cummin())
self.assert_eq(pdf.cummin(skipna=False), kdf.cummin(skipna=False))
self.assert_eq(pdf.cummin().sum(), kdf.cummin().sum())
def test_cummin(self):
pdf = pd.DataFrame(
[[2.0, 1.0], [5, None], [1.0, 0.0], [2.0, 4.0], [4.0, 9.0]],
columns=list("AB"),
index=np.random.rand(5),
)
kdf = ks.from_pandas(pdf)
self._test_cummin(pdf, kdf)
def test_cummin_multiindex_columns(self):
arrays = [np.array(["A", "A", "B", "B"]), np.array(["one", "two", "one", "two"])]
pdf = pd.DataFrame(np.random.randn(3, 4), index=["A", "C", "B"], columns=arrays)
pdf.at["C", ("A", "two")] = None
kdf = ks.from_pandas(pdf)
self._test_cummin(pdf, kdf)
def _test_cummax(self, pdf, kdf):
self.assert_eq(pdf.cummax(), kdf.cummax())
self.assert_eq(pdf.cummax(skipna=False), kdf.cummax(skipna=False))
self.assert_eq(pdf.cummax().sum(), kdf.cummax().sum())
def test_cummax(self):
pdf = pd.DataFrame(
[[2.0, 1.0], [5, None], [1.0, 0.0], [2.0, 4.0], [4.0, 9.0]],
columns=list("AB"),
index=np.random.rand(5),
)
kdf = ks.from_pandas(pdf)
self._test_cummax(pdf, kdf)
def test_cummax_multiindex_columns(self):
arrays = [np.array(["A", "A", "B", "B"]), np.array(["one", "two", "one", "two"])]
pdf = pd.DataFrame(np.random.randn(3, 4), index=["A", "C", "B"], columns=arrays)
pdf.at["C", ("A", "two")] = None
kdf = ks.from_pandas(pdf)
self._test_cummax(pdf, kdf)
def _test_cumsum(self, pdf, kdf):
self.assert_eq(pdf.cumsum(), kdf.cumsum())
self.assert_eq(pdf.cumsum(skipna=False), kdf.cumsum(skipna=False))
self.assert_eq(pdf.cumsum().sum(), kdf.cumsum().sum())
def test_cumsum(self):
pdf = pd.DataFrame(
[[2.0, 1.0], [5, None], [1.0, 0.0], [2.0, 4.0], [4.0, 9.0]],
columns=list("AB"),
index=np.random.rand(5),
)
kdf = ks.from_pandas(pdf)
self._test_cumsum(pdf, kdf)
def test_cumsum_multiindex_columns(self):
arrays = [np.array(["A", "A", "B", "B"]), np.array(["one", "two", "one", "two"])]
pdf = pd.DataFrame(np.random.randn(3, 4), index=["A", "C", "B"], columns=arrays)
pdf.at["C", ("A", "two")] = None
kdf = ks.from_pandas(pdf)
self._test_cumsum(pdf, kdf)
def _test_cumprod(self, pdf, kdf):
self.assert_eq(pdf.cumprod(), kdf.cumprod(), almost=True)
self.assert_eq(pdf.cumprod(skipna=False), kdf.cumprod(skipna=False), almost=True)
self.assert_eq(pdf.cumprod().sum(), kdf.cumprod().sum(), almost=True)
def test_cumprod(self):
pdf = pd.DataFrame(
[[2.0, 1.0], [5, None], [1.0, 1.0], [2.0, 4.0], [4.0, 9.0]],
columns=list("AB"),
index=np.random.rand(5),
)
kdf = ks.from_pandas(pdf)
self._test_cumprod(pdf, kdf)
def test_cumprod_multiindex_columns(self):
arrays = [np.array(["A", "A", "B", "B"]), np.array(["one", "two", "one", "two"])]
pdf = pd.DataFrame(np.random.rand(3, 4), index=["A", "C", "B"], columns=arrays)
pdf.at["C", ("A", "two")] = None
kdf = ks.from_pandas(pdf)
self._test_cumprod(pdf, kdf)
def test_drop_duplicates(self):
pdf = pd.DataFrame(
{"a": [1, 2, 2, 2, 3], "b": ["a", "a", "a", "c", "d"]}, index=np.random.rand(5)
)
kdf = ks.from_pandas(pdf)
# inplace is False
for keep in ["first", "last", False]:
with self.subTest(keep=keep):
self.assert_eq(
pdf.drop_duplicates(keep=keep).sort_index(),
kdf.drop_duplicates(keep=keep).sort_index(),
)
self.assert_eq(
pdf.drop_duplicates("a", keep=keep).sort_index(),
kdf.drop_duplicates("a", keep=keep).sort_index(),
)
self.assert_eq(
pdf.drop_duplicates(["a", "b"], keep=keep).sort_index(),
kdf.drop_duplicates(["a", "b"], keep=keep).sort_index(),
)
self.assert_eq(
pdf.set_index("a", append=True).drop_duplicates(keep=keep).sort_index(),
kdf.set_index("a", append=True).drop_duplicates(keep=keep).sort_index(),
)
self.assert_eq(
pdf.set_index("a", append=True).drop_duplicates("b", keep=keep).sort_index(),
kdf.set_index("a", append=True).drop_duplicates("b", keep=keep).sort_index(),
)
columns = pd.MultiIndex.from_tuples([("x", "a"), ("y", "b")])
pdf.columns = columns
kdf.columns = columns
# inplace is False
for keep in ["first", "last", False]:
with self.subTest("multi-index columns", keep=keep):
self.assert_eq(
pdf.drop_duplicates(keep=keep).sort_index(),
kdf.drop_duplicates(keep=keep).sort_index(),
)
self.assert_eq(
pdf.drop_duplicates(("x", "a"), keep=keep).sort_index(),
kdf.drop_duplicates(("x", "a"), keep=keep).sort_index(),
)
self.assert_eq(
pdf.drop_duplicates([("x", "a"), ("y", "b")], keep=keep).sort_index(),
kdf.drop_duplicates([("x", "a"), ("y", "b")], keep=keep).sort_index(),
)
# inplace is True
subset_list = [None, "a", ["a", "b"]]
for subset in subset_list:
pdf = pd.DataFrame(
{"a": [1, 2, 2, 2, 3], "b": ["a", "a", "a", "c", "d"]}, index=np.random.rand(5)
)
kdf = ks.from_pandas(pdf)
pser = pdf.a
kser = kdf.a
pdf.drop_duplicates(subset=subset, inplace=True)
kdf.drop_duplicates(subset=subset, inplace=True)
self.assert_eq(kdf.sort_index(), pdf.sort_index())
self.assert_eq(kser.sort_index(), pser.sort_index())
# multi-index columns, inplace is True
subset_list = [None, ("x", "a"), [("x", "a"), ("y", "b")]]
for subset in subset_list:
pdf = pd.DataFrame(
{"a": [1, 2, 2, 2, 3], "b": ["a", "a", "a", "c", "d"]}, index=np.random.rand(5)
)
kdf = ks.from_pandas(pdf)
columns = pd.MultiIndex.from_tuples([("x", "a"), ("y", "b")])
pdf.columns = columns
kdf.columns = columns
pser = pdf[("x", "a")]
kser = kdf[("x", "a")]
pdf.drop_duplicates(subset=subset, inplace=True)
kdf.drop_duplicates(subset=subset, inplace=True)
self.assert_eq(kdf.sort_index(), pdf.sort_index())
self.assert_eq(kser.sort_index(), pser.sort_index())
def test_reindex(self):
index = ["A", "B", "C", "D", "E"]
pdf = pd.DataFrame({"numbers": [1.0, 2.0, 3.0, 4.0, 5.0]}, index=index)
kdf = ks.DataFrame({"numbers": [1.0, 2.0, 3.0, 4.0, 5.0]}, index=index)
self.assert_eq(
pdf.reindex(["A", "B", "C"], columns=["numbers", "2", "3"]).sort_index(),
kdf.reindex(["A", "B", "C"], columns=["numbers", "2", "3"]).sort_index(),
)
self.assert_eq(
pdf.reindex(["A", "B", "C"], index=["numbers", "2", "3"]).sort_index(),
kdf.reindex(["A", "B", "C"], index=["numbers", "2", "3"]).sort_index(),
)
self.assert_eq(
pdf.reindex(index=["A", "B"]).sort_index(), kdf.reindex(index=["A", "B"]).sort_index()
)
self.assert_eq(
pdf.reindex(index=["A", "B", "2", "3"]).sort_index(),
kdf.reindex(index=["A", "B", "2", "3"]).sort_index(),
)
self.assert_eq(
pdf.reindex(columns=["numbers"]).sort_index(),
kdf.reindex(columns=["numbers"]).sort_index(),
)
self.assert_eq(
pdf.reindex(columns=["numbers", "2", "3"]).sort_index(),
kdf.reindex(columns=["numbers", "2", "3"]).sort_index(),
)
self.assertRaises(TypeError, lambda: kdf.reindex(columns=["numbers", "2", "3"], axis=1))
self.assertRaises(TypeError, lambda: kdf.reindex(columns=["numbers", "2", "3"], axis=2))
self.assertRaises(TypeError, lambda: kdf.reindex(index=["A", "B", "C"], axis=1))
self.assertRaises(TypeError, lambda: kdf.reindex(index=123))
columns = pd.MultiIndex.from_tuples([("X", "numbers")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(
pdf.reindex(columns=[("X", "numbers"), ("Y", "2"), ("Y", "3")]).sort_index(),
kdf.reindex(columns=[("X", "numbers"), ("Y", "2"), ("Y", "3")]).sort_index(),
)
self.assertRaises(TypeError, lambda: kdf.reindex(columns=["X"]))
self.assertRaises(ValueError, lambda: kdf.reindex(columns=[("X",)]))
def test_melt(self):
pdf = pd.DataFrame(
{"A": [1, 3, 5], "B": [2, 4, 6], "C": [7, 8, 9]}, index=np.random.rand(3)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(
kdf.melt().sort_values(["variable", "value"]).reset_index(drop=True),
pdf.melt().sort_values(["variable", "value"]),
)
self.assert_eq(
kdf.melt(id_vars="A").sort_values(["variable", "value"]).reset_index(drop=True),
pdf.melt(id_vars="A").sort_values(["variable", "value"]),
)
self.assert_eq(
kdf.melt(id_vars=["A", "B"]).sort_values(["variable", "value"]).reset_index(drop=True),
pdf.melt(id_vars=["A", "B"]).sort_values(["variable", "value"]),
)
self.assert_eq(
kdf.melt(id_vars=("A", "B")).sort_values(["variable", "value"]).reset_index(drop=True),
pdf.melt(id_vars=("A", "B")).sort_values(["variable", "value"]),
)
self.assert_eq(
kdf.melt(id_vars=["A"], value_vars=["C"])
.sort_values(["variable", "value"])
.reset_index(drop=True),
pdf.melt(id_vars=["A"], value_vars=["C"]).sort_values(["variable", "value"]),
)
self.assert_eq(
kdf.melt(id_vars=["A"], value_vars=["B"], var_name="myVarname", value_name="myValname")
.sort_values(["myVarname", "myValname"])
.reset_index(drop=True),
pdf.melt(
id_vars=["A"], value_vars=["B"], var_name="myVarname", value_name="myValname"
).sort_values(["myVarname", "myValname"]),
)
self.assert_eq(
kdf.melt(value_vars=("A", "B"))
.sort_values(["variable", "value"])
.reset_index(drop=True),
pdf.melt(value_vars=("A", "B")).sort_values(["variable", "value"]),
)
self.assertRaises(KeyError, lambda: kdf.melt(id_vars="Z"))
self.assertRaises(KeyError, lambda: kdf.melt(value_vars="Z"))
# multi-index columns
columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(
kdf.melt().sort_values(["variable_0", "variable_1", "value"]).reset_index(drop=True),
pdf.melt().sort_values(["variable_0", "variable_1", "value"]),
)
self.assert_eq(
kdf.melt(id_vars=[("X", "A")])
.sort_values(["variable_0", "variable_1", "value"])
.reset_index(drop=True),
pdf.melt(id_vars=[("X", "A")]).sort_values(["variable_0", "variable_1", "value"]),
almost=True,
)
self.assert_eq(
kdf.melt(id_vars=[("X", "A")], value_vars=[("Y", "C")])
.sort_values(["variable_0", "variable_1", "value"])
.reset_index(drop=True),
pdf.melt(id_vars=[("X", "A")], value_vars=[("Y", "C")]).sort_values(
["variable_0", "variable_1", "value"]
),
almost=True,
)
self.assert_eq(
kdf.melt(
id_vars=[("X", "A")],
value_vars=[("X", "B")],
var_name=["myV1", "myV2"],
value_name="myValname",
)
.sort_values(["myV1", "myV2", "myValname"])
.reset_index(drop=True),
pdf.melt(
id_vars=[("X", "A")],
value_vars=[("X", "B")],
var_name=["myV1", "myV2"],
value_name="myValname",
).sort_values(["myV1", "myV2", "myValname"]),
almost=True,
)
columns.names = ["v0", "v1"]
pdf.columns = columns
kdf.columns = columns
self.assert_eq(
kdf.melt().sort_values(["v0", "v1", "value"]).reset_index(drop=True),
pdf.melt().sort_values(["v0", "v1", "value"]),
)
self.assertRaises(ValueError, lambda: kdf.melt(id_vars=("X", "A")))
self.assertRaises(ValueError, lambda: kdf.melt(value_vars=("X", "A")))
self.assertRaises(KeyError, lambda: kdf.melt(id_vars=[("Y", "A")]))
self.assertRaises(KeyError, lambda: kdf.melt(value_vars=[("Y", "A")]))
def test_all(self):
pdf = pd.DataFrame(
{
"col1": [False, False, False],
"col2": [True, False, False],
"col3": [0, 0, 1],
"col4": [0, 1, 2],
"col5": [False, False, None],
"col6": [True, False, None],
},
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.all(), pdf.all())
columns = pd.MultiIndex.from_tuples(
[
("a", "col1"),
("a", "col2"),
("a", "col3"),
("b", "col4"),
("b", "col5"),
("c", "col6"),
]
)
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.all(), pdf.all())
columns.names = ["X", "Y"]
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.all(), pdf.all())
with self.assertRaisesRegex(
NotImplementedError, 'axis should be either 0 or "index" currently.'
):
kdf.all(axis=1)
def test_any(self):
pdf = pd.DataFrame(
{
"col1": [False, False, False],
"col2": [True, False, False],
"col3": [0, 0, 1],
"col4": [0, 1, 2],
"col5": [False, False, None],
"col6": [True, False, None],
},
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.any(), pdf.any())
columns = pd.MultiIndex.from_tuples(
[
("a", "col1"),
("a", "col2"),
("a", "col3"),
("b", "col4"),
("b", "col5"),
("c", "col6"),
]
)
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.any(), pdf.any())
columns.names = ["X", "Y"]
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.any(), pdf.any())
with self.assertRaisesRegex(
NotImplementedError, 'axis should be either 0 or "index" currently.'
):
kdf.any(axis=1)
def test_rank(self):
pdf = pd.DataFrame(
data={"col1": [1, 2, 3, 1], "col2": [3, 4, 3, 1]},
columns=["col1", "col2"],
index=np.random.rand(4),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(pdf.rank().sort_index(), kdf.rank().sort_index())
self.assert_eq(
pdf.rank(ascending=False).sort_index(), kdf.rank(ascending=False).sort_index()
)
self.assert_eq(pdf.rank(method="min").sort_index(), kdf.rank(method="min").sort_index())
self.assert_eq(pdf.rank(method="max").sort_index(), kdf.rank(method="max").sort_index())
self.assert_eq(pdf.rank(method="first").sort_index(), kdf.rank(method="first").sort_index())
self.assert_eq(pdf.rank(method="dense").sort_index(), kdf.rank(method="dense").sort_index())
msg = "method must be one of 'average', 'min', 'max', 'first', 'dense'"
with self.assertRaisesRegex(ValueError, msg):
kdf.rank(method="nothing")
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "col1"), ("y", "col2")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(pdf.rank().sort_index(), kdf.rank().sort_index())
def test_round(self):
pdf = pd.DataFrame(
{
"A": [0.028208, 0.038683, 0.877076],
"B": [0.992815, 0.645646, 0.149370],
"C": [0.173891, 0.577595, 0.491027],
},
columns=["A", "B", "C"],
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
pser = pd.Series([1, 0, 2], index=["A", "B", "C"])
kser = ks.Series([1, 0, 2], index=["A", "B", "C"])
self.assert_eq(pdf.round(2), kdf.round(2))
self.assert_eq(pdf.round({"A": 1, "C": 2}), kdf.round({"A": 1, "C": 2}))
self.assert_eq(pdf.round({"A": 1, "D": 2}), kdf.round({"A": 1, "D": 2}))
self.assert_eq(pdf.round(pser), kdf.round(kser))
msg = "decimals must be an integer, a dict-like or a Series"
with self.assertRaisesRegex(ValueError, msg):
kdf.round(1.5)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C")])
pdf.columns = columns
kdf.columns = columns
pser = pd.Series([1, 0, 2], index=columns)
kser = ks.Series([1, 0, 2], index=columns)
self.assert_eq(pdf.round(2), kdf.round(2))
self.assert_eq(
pdf.round({("X", "A"): 1, ("Y", "C"): 2}), kdf.round({("X", "A"): 1, ("Y", "C"): 2})
)
self.assert_eq(pdf.round({("X", "A"): 1, "Y": 2}), kdf.round({("X", "A"): 1, "Y": 2}))
self.assert_eq(pdf.round(pser), kdf.round(kser))
def test_shift(self):
pdf = pd.DataFrame(
{
"Col1": [10, 20, 15, 30, 45],
"Col2": [13, 23, 18, 33, 48],
"Col3": [17, 27, 22, 37, 52],
},
index=np.random.rand(5),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(pdf.shift(3), kdf.shift(3))
# Need the expected result since pandas 0.23 does not support `fill_value` argument.
pdf1 = pd.DataFrame(
{"Col1": [0, 0, 0, 10, 20], "Col2": [0, 0, 0, 13, 23], "Col3": [0, 0, 0, 17, 27]},
index=pdf.index,
)
self.assert_eq(pdf1, kdf.shift(periods=3, fill_value=0))
msg = "should be an int"
with self.assertRaisesRegex(ValueError, msg):
kdf.shift(1.5)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "Col1"), ("x", "Col2"), ("y", "Col3")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(pdf.shift(3), kdf.shift(3))
def test_diff(self):
pdf = pd.DataFrame(
{"a": [1, 2, 3, 4, 5, 6], "b": [1, 1, 2, 3, 5, 8], "c": [1, 4, 9, 16, 25, 36]},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(pdf.diff(), kdf.diff())
msg = "should be an int"
with self.assertRaisesRegex(ValueError, msg):
kdf.diff(1.5)
msg = 'axis should be either 0 or "index" currently.'
with self.assertRaisesRegex(NotImplementedError, msg):
kdf.diff(axis=1)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "Col1"), ("x", "Col2"), ("y", "Col3")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(pdf.diff(), kdf.diff())
def test_duplicated(self):
pdf = pd.DataFrame(
{"a": [1, 1, 2, 3], "b": [1, 1, 1, 4], "c": [1, 1, 1, 5]}, index=np.random.rand(4)
)
kdf = ks.from_pandas(pdf)
self.assert_eq(pdf.duplicated().sort_index(), kdf.duplicated().sort_index())
self.assert_eq(
pdf.duplicated(keep="last").sort_index(), kdf.duplicated(keep="last").sort_index(),
)
self.assert_eq(
pdf.duplicated(keep=False).sort_index(), kdf.duplicated(keep=False).sort_index(),
)
self.assert_eq(
pdf.duplicated(subset=["b"]).sort_index(), kdf.duplicated(subset=["b"]).sort_index(),
)
with self.assertRaisesRegex(ValueError, "'keep' only supports 'first', 'last' and False"):
kdf.duplicated(keep="false")
with self.assertRaisesRegex(KeyError, "'d'"):
kdf.duplicated(subset=["d"])
pdf.index.name = "x"
kdf.index.name = "x"
self.assert_eq(pdf.duplicated().sort_index(), kdf.duplicated().sort_index())
# multi-index
self.assert_eq(
pdf.set_index("a", append=True).duplicated().sort_index(),
kdf.set_index("a", append=True).duplicated().sort_index(),
)
self.assert_eq(
pdf.set_index("a", append=True).duplicated(keep=False).sort_index(),
kdf.set_index("a", append=True).duplicated(keep=False).sort_index(),
)
self.assert_eq(
pdf.set_index("a", append=True).duplicated(subset=["b"]).sort_index(),
kdf.set_index("a", append=True).duplicated(subset=["b"]).sort_index(),
)
# mutli-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(
pd.Series(pdf.duplicated(), name="x").sort_index(), kdf.duplicated().sort_index()
)
self.assert_eq(
pd.Series(pdf.duplicated(subset=[("x", "b")]), name="x").sort_index(),
kdf.duplicated(subset=[("x", "b")]).sort_index(),
)
def test_ffill(self):
pdf = pd.DataFrame(
{
"x": [np.nan, 2, 3, 4, np.nan, 6],
"y": [1, 2, np.nan, 4, np.nan, np.nan],
"z": [1, 2, 3, 4, np.nan, np.nan],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.ffill(), pdf.ffill())
self.assert_eq(kdf.ffill(limit=1), pdf.ffill(limit=1))
def test_bfill(self):
pdf = pd.DataFrame(
{
"x": [np.nan, 2, 3, 4, np.nan, 6],
"y": [1, 2, np.nan, 4, np.nan, np.nan],
"z": [1, 2, 3, 4, np.nan, np.nan],
},
index=np.random.rand(6),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.bfill(), pdf.bfill())
self.assert_eq(kdf.bfill(limit=1), pdf.bfill(limit=1))
def test_filter(self):
pdf = pd.DataFrame(
{
"aa": ["aa", "bd", "bc", "ab", "ce"],
"ba": [1, 2, 3, 4, 5],
"cb": [1.0, 2.0, 3.0, 4.0, 5.0],
"db": [1.0, np.nan, 3.0, np.nan, 5.0],
}
)
pdf = pdf.set_index("aa")
kdf = ks.from_pandas(pdf)
self.assert_eq(
kdf.filter(items=["ab", "aa"], axis=0).sort_index(),
pdf.filter(items=["ab", "aa"], axis=0).sort_index(),
)
self.assert_eq(
kdf.filter(items=["ba", "db"], axis=1).sort_index(),
pdf.filter(items=["ba", "db"], axis=1).sort_index(),
)
self.assert_eq(kdf.filter(like="b", axis="index"), pdf.filter(like="b", axis="index"))
self.assert_eq(kdf.filter(like="c", axis="columns"), pdf.filter(like="c", axis="columns"))
self.assert_eq(kdf.filter(regex="b.*", axis="index"), pdf.filter(regex="b.*", axis="index"))
self.assert_eq(
kdf.filter(regex="b.*", axis="columns"), pdf.filter(regex="b.*", axis="columns")
)
pdf = pdf.set_index("ba", append=True)
kdf = ks.from_pandas(pdf)
self.assert_eq(
kdf.filter(items=[("aa", 1), ("bd", 2)], axis=0).sort_index(),
pdf.filter(items=[("aa", 1), ("bd", 2)], axis=0).sort_index(),
)
with self.assertRaisesRegex(TypeError, "Unsupported type <class 'list'>"):
kdf.filter(items=[["aa", 1], ("bd", 2)], axis=0)
with self.assertRaisesRegex(ValueError, "The item should not be empty."):
kdf.filter(items=[(), ("bd", 2)], axis=0)
self.assert_eq(kdf.filter(like="b", axis=0), pdf.filter(like="b", axis=0))
self.assert_eq(kdf.filter(regex="b.*", axis=0), pdf.filter(regex="b.*", axis=0))
with self.assertRaisesRegex(ValueError, "items should be a list-like object"):
kdf.filter(items="b")
with self.assertRaisesRegex(ValueError, "No axis named"):
kdf.filter(regex="b.*", axis=123)
with self.assertRaisesRegex(TypeError, "Must pass either `items`, `like`"):
kdf.filter()
with self.assertRaisesRegex(TypeError, "mutually exclusive"):
kdf.filter(regex="b.*", like="aaa")
# multi-index columns
pdf = pd.DataFrame(
{
("x", "aa"): ["aa", "ab", "bc", "bd", "ce"],
("x", "ba"): [1, 2, 3, 4, 5],
("y", "cb"): [1.0, 2.0, 3.0, 4.0, 5.0],
("z", "db"): [1.0, np.nan, 3.0, np.nan, 5.0],
}
)
pdf = pdf.set_index(("x", "aa"))
kdf = ks.from_pandas(pdf)
self.assert_eq(
kdf.filter(items=["ab", "aa"], axis=0).sort_index(),
pdf.filter(items=["ab", "aa"], axis=0).sort_index(),
)
self.assert_eq(
kdf.filter(items=[("x", "ba"), ("z", "db")], axis=1).sort_index(),
pdf.filter(items=[("x", "ba"), ("z", "db")], axis=1).sort_index(),
)
self.assert_eq(kdf.filter(like="b", axis="index"), pdf.filter(like="b", axis="index"))
self.assert_eq(kdf.filter(like="c", axis="columns"), pdf.filter(like="c", axis="columns"))
self.assert_eq(kdf.filter(regex="b.*", axis="index"), pdf.filter(regex="b.*", axis="index"))
self.assert_eq(
kdf.filter(regex="b.*", axis="columns"), pdf.filter(regex="b.*", axis="columns")
)
def test_pipe(self):
kdf = ks.DataFrame(
{"category": ["A", "A", "B"], "col1": [1, 2, 3], "col2": [4, 5, 6]},
columns=["category", "col1", "col2"],
)
self.assertRaisesRegex(
ValueError,
"arg is both the pipe target and a keyword argument",
lambda: kdf.pipe((lambda x: x, "arg"), arg="1"),
)
def test_transform(self):
pdf = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6] * 100,
"b": [1.0, 1.0, 2.0, 3.0, 5.0, 8.0] * 100,
"c": [1, 4, 9, 16, 25, 36] * 100,
},
columns=["a", "b", "c"],
index=np.random.rand(600),
)
kdf = ks.DataFrame(pdf)
self.assert_eq(
kdf.transform(lambda x: x + 1).sort_index(), pdf.transform(lambda x: x + 1).sort_index()
)
self.assert_eq(
kdf.transform(lambda x, y: x + y, y=2).sort_index(),
pdf.transform(lambda x, y: x + y, y=2).sort_index(),
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.transform(lambda x: x + 1).sort_index(),
pdf.transform(lambda x: x + 1).sort_index(),
)
self.assert_eq(
kdf.transform(lambda x, y: x + y, y=1).sort_index(),
pdf.transform(lambda x, y: x + y, y=1).sort_index(),
)
with self.assertRaisesRegex(AssertionError, "the first argument should be a callable"):
kdf.transform(1)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(
kdf.transform(lambda x: x + 1).sort_index(), pdf.transform(lambda x: x + 1).sort_index()
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.transform(lambda x: x + 1).sort_index(),
pdf.transform(lambda x: x + 1).sort_index(),
)
def test_apply(self):
pdf = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6] * 100,
"b": [1.0, 1.0, 2.0, 3.0, 5.0, 8.0] * 100,
"c": [1, 4, 9, 16, 25, 36] * 100,
},
columns=["a", "b", "c"],
index=np.random.rand(600),
)
kdf = ks.DataFrame(pdf)
self.assert_eq(
kdf.apply(lambda x: x + 1).sort_index(), pdf.apply(lambda x: x + 1).sort_index()
)
self.assert_eq(
kdf.apply(lambda x, b: x + b, args=(1,)).sort_index(),
pdf.apply(lambda x, b: x + b, args=(1,)).sort_index(),
)
self.assert_eq(
kdf.apply(lambda x, b: x + b, b=1).sort_index(),
pdf.apply(lambda x, b: x + b, b=1).sort_index(),
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.apply(lambda x: x + 1).sort_index(), pdf.apply(lambda x: x + 1).sort_index()
)
self.assert_eq(
kdf.apply(lambda x, b: x + b, args=(1,)).sort_index(),
pdf.apply(lambda x, b: x + b, args=(1,)).sort_index(),
)
self.assert_eq(
kdf.apply(lambda x, b: x + b, b=1).sort_index(),
pdf.apply(lambda x, b: x + b, b=1).sort_index(),
)
# returning a Series
self.assert_eq(
kdf.apply(lambda x: len(x), axis=1).sort_index(),
pdf.apply(lambda x: len(x), axis=1).sort_index(),
)
self.assert_eq(
kdf.apply(lambda x, c: len(x) + c, axis=1, c=100).sort_index(),
pdf.apply(lambda x, c: len(x) + c, axis=1, c=100).sort_index(),
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.apply(lambda x: len(x), axis=1).sort_index(),
pdf.apply(lambda x: len(x), axis=1).sort_index(),
)
self.assert_eq(
kdf.apply(lambda x, c: len(x) + c, axis=1, c=100).sort_index(),
pdf.apply(lambda x, c: len(x) + c, axis=1, c=100).sort_index(),
)
with self.assertRaisesRegex(AssertionError, "the first argument should be a callable"):
kdf.apply(1)
with self.assertRaisesRegex(TypeError, "The given function.*1 or 'column'; however"):
def f1(_) -> ks.DataFrame[int]:
pass
kdf.apply(f1, axis=0)
with self.assertRaisesRegex(TypeError, "The given function.*0 or 'index'; however"):
def f2(_) -> ks.Series[int]:
pass
kdf.apply(f2, axis=1)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(
kdf.apply(lambda x: x + 1).sort_index(), pdf.apply(lambda x: x + 1).sort_index()
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.apply(lambda x: x + 1).sort_index(), pdf.apply(lambda x: x + 1).sort_index()
)
# returning a Series
self.assert_eq(
kdf.apply(lambda x: len(x), axis=1).sort_index(),
pdf.apply(lambda x: len(x), axis=1).sort_index(),
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.apply(lambda x: len(x), axis=1).sort_index(),
pdf.apply(lambda x: len(x), axis=1).sort_index(),
)
def test_apply_batch(self):
pdf = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6] * 100,
"b": [1.0, 1.0, 2.0, 3.0, 5.0, 8.0] * 100,
"c": [1, 4, 9, 16, 25, 36] * 100,
},
columns=["a", "b", "c"],
index=np.random.rand(600),
)
kdf = ks.DataFrame(pdf)
self.assert_eq(kdf.apply_batch(lambda pdf: pdf + 1).sort_index(), (pdf + 1).sort_index())
self.assert_eq(
kdf.apply_batch(lambda pdf, a: pdf + a, args=(1,)).sort_index(), (pdf + 1).sort_index()
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.apply_batch(lambda pdf: pdf + 1).sort_index(), (pdf + 1).sort_index()
)
self.assert_eq(
kdf.apply_batch(lambda pdf, b: pdf + b, b=1).sort_index(), (pdf + 1).sort_index()
)
with self.assertRaisesRegex(AssertionError, "the first argument should be a callable"):
kdf.apply_batch(1)
with self.assertRaisesRegex(TypeError, "The given function.*frame as its type hints"):
def f2(_) -> ks.Series[int]:
pass
kdf.apply_batch(f2)
with self.assertRaisesRegex(ValueError, "The given function should return a frame"):
kdf.apply_batch(lambda pdf: 1)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.apply_batch(lambda x: x + 1).sort_index(), (pdf + 1).sort_index())
with option_context("compute.shortcut_limit", 500):
self.assert_eq(kdf.apply_batch(lambda x: x + 1).sort_index(), (pdf + 1).sort_index())
def test_transform_batch(self):
pdf = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6] * 100,
"b": [1.0, 1.0, 2.0, 3.0, 5.0, 8.0] * 100,
"c": [1, 4, 9, 16, 25, 36] * 100,
},
columns=["a", "b", "c"],
index=np.random.rand(600),
)
kdf = ks.DataFrame(pdf)
self.assert_eq(
kdf.transform_batch(lambda pdf: pdf + 1).sort_index(), (pdf + 1).sort_index()
)
self.assert_eq(
kdf.transform_batch(lambda pdf: pdf.c + 1).sort_index(), (pdf.c + 1).sort_index()
)
self.assert_eq(
kdf.transform_batch(lambda pdf, a: pdf + a, 1).sort_index(), (pdf + 1).sort_index()
)
self.assert_eq(
kdf.transform_batch(lambda pdf, a: pdf.c + a, a=1).sort_index(),
(pdf.c + 1).sort_index(),
)
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.transform_batch(lambda pdf: pdf + 1).sort_index(), (pdf + 1).sort_index()
)
self.assert_eq(
kdf.transform_batch(lambda pdf: pdf.b + 1).sort_index(), (pdf.b + 1).sort_index()
)
self.assert_eq(
kdf.transform_batch(lambda pdf, a: pdf + a, 1).sort_index(), (pdf + 1).sort_index()
)
self.assert_eq(
kdf.transform_batch(lambda pdf, a: pdf.c + a, a=1).sort_index(),
(pdf.c + 1).sort_index(),
)
with self.assertRaisesRegex(AssertionError, "the first argument should be a callable"):
kdf.transform_batch(1)
with self.assertRaisesRegex(ValueError, "The given function should return a frame"):
kdf.transform_batch(lambda pdf: 1)
with self.assertRaisesRegex(
ValueError, "transform_batch cannot produce aggregated results"
):
kdf.transform_batch(lambda pdf: pd.Series(1))
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.transform_batch(lambda x: x + 1).sort_index(), (pdf + 1).sort_index())
with option_context("compute.shortcut_limit", 500):
self.assert_eq(
kdf.transform_batch(lambda x: x + 1).sort_index(), (pdf + 1).sort_index()
)
def test_transform_batch_same_anchor(self):
kdf = ks.range(10)
kdf["d"] = kdf.transform_batch(lambda pdf: pdf.id + 1)
self.assert_eq(
kdf, pd.DataFrame({"id": list(range(10)), "d": list(range(1, 11))}, columns=["id", "d"])
)
kdf = ks.range(10)
kdf["d"] = kdf.id.transform_batch(lambda ser: ser + 1)
self.assert_eq(
kdf, pd.DataFrame({"id": list(range(10)), "d": list(range(1, 11))}, columns=["id", "d"])
)
kdf = ks.range(10)
def plus_one(pdf) -> ks.Series[np.int64]:
return pdf.id + 1
kdf["d"] = kdf.transform_batch(plus_one)
self.assert_eq(
kdf, pd.DataFrame({"id": list(range(10)), "d": list(range(1, 11))}, columns=["id", "d"])
)
kdf = ks.range(10)
def plus_one(ser) -> ks.Series[np.int64]:
return ser + 1
kdf["d"] = kdf.id.transform_batch(plus_one)
self.assert_eq(
kdf, pd.DataFrame({"id": list(range(10)), "d": list(range(1, 11))}, columns=["id", "d"])
)
def test_empty_timestamp(self):
pdf = pd.DataFrame(
{
"t": [
datetime(2019, 1, 1, 0, 0, 0),
datetime(2019, 1, 2, 0, 0, 0),
datetime(2019, 1, 3, 0, 0, 0),
]
},
index=np.random.rand(3),
)
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf[kdf["t"] != kdf["t"]], pdf[pdf["t"] != pdf["t"]])
self.assert_eq(kdf[kdf["t"] != kdf["t"]].dtypes, pdf[pdf["t"] != pdf["t"]].dtypes)
def test_to_spark(self):
kdf = ks.from_pandas(self.pdf)
with self.assertRaisesRegex(ValueError, "'index_col' cannot be overlapped"):
kdf.to_spark(index_col="a")
with self.assertRaisesRegex(ValueError, "length of index columns.*1.*3"):
kdf.to_spark(index_col=["x", "y", "z"])
def test_keys(self):
kdf = ks.DataFrame(
[[1, 2], [4, 5], [7, 8]],
index=["cobra", "viper", "sidewinder"],
columns=["max_speed", "shield"],
)
pdf = kdf.to_pandas()
self.assert_eq(kdf.keys(), pdf.keys())
def test_quantile(self):
kdf = ks.from_pandas(self.pdf)
with self.assertRaisesRegex(
NotImplementedError, 'axis should be either 0 or "index" currently.'
):
kdf.quantile(0.5, axis=1)
with self.assertRaisesRegex(
NotImplementedError, "quantile currently doesn't supports numeric_only"
):
kdf.quantile(0.5, numeric_only=False)
def test_pct_change(self):
kdf = ks.DataFrame(
{"a": [1, 2, 3, 2], "b": [4.0, 2.0, 3.0, 1.0], "c": [300, 200, 400, 200]},
index=np.random.rand(4),
)
kdf.columns = pd.MultiIndex.from_tuples([("a", "x"), ("b", "y"), ("c", "z")])
pdf = kdf.to_pandas()
self.assert_eq(repr(kdf.pct_change(2)), repr(pdf.pct_change(2)))
def test_where(self):
kdf = ks.from_pandas(self.pdf)
with self.assertRaisesRegex(ValueError, "type of cond must be a DataFrame or Series"):
kdf.where(1)
def test_mask(self):
kdf = ks.from_pandas(self.pdf)
with self.assertRaisesRegex(ValueError, "type of cond must be a DataFrame or Series"):
kdf.mask(1)
def test_query(self):
kdf = ks.DataFrame({"A": range(1, 6), "B": range(10, 0, -2), "C": range(10, 5, -1)})
pdf = kdf.to_pandas()
exprs = ("A > B", "A < C", "C == B")
for expr in exprs:
self.assert_eq(kdf.query(expr), pdf.query(expr))
# test `inplace=True`
for expr in exprs:
dummy_kdf = kdf.copy()
dummy_pdf = pdf.copy()
pser = dummy_pdf.A
kser = dummy_kdf.A
dummy_pdf.query(expr, inplace=True)
dummy_kdf.query(expr, inplace=True)
self.assert_eq(dummy_kdf, dummy_pdf)
self.assert_eq(kser, pser)
# invalid values for `expr`
invalid_exprs = (1, 1.0, (exprs[0],), [exprs[0]])
for expr in invalid_exprs:
with self.assertRaisesRegex(
ValueError, "expr must be a string to be evaluated, {} given".format(type(expr))
):
kdf.query(expr)
# invalid values for `inplace`
invalid_inplaces = (1, 0, "True", "False")
for inplace in invalid_inplaces:
with self.assertRaisesRegex(
ValueError,
'For argument "inplace" expected type bool, received type {}.'.format(
type(inplace).__name__
),
):
kdf.query("a < b", inplace=inplace)
# doesn't support for MultiIndex columns
columns = pd.MultiIndex.from_tuples([("A", "Z"), ("B", "X"), ("C", "C")])
kdf.columns = columns
with self.assertRaisesRegex(ValueError, "Doesn't support for MultiIndex columns"):
kdf.query("('A', 'Z') > ('B', 'X')")
def test_take(self):
kdf = ks.DataFrame(
{"A": range(0, 50000), "B": range(100000, 0, -2), "C": range(100000, 50000, -1)}
)
pdf = kdf.to_pandas()
# axis=0 (default)
self.assert_eq(kdf.take([1, 2]).sort_index(), pdf.take([1, 2]).sort_index())
self.assert_eq(kdf.take([-1, -2]).sort_index(), pdf.take([-1, -2]).sort_index())
self.assert_eq(
kdf.take(range(100, 110)).sort_index(), pdf.take(range(100, 110)).sort_index()
)
self.assert_eq(
kdf.take(range(-110, -100)).sort_index(), pdf.take(range(-110, -100)).sort_index()
)
self.assert_eq(
kdf.take([10, 100, 1000, 10000]).sort_index(),
pdf.take([10, 100, 1000, 10000]).sort_index(),
)
self.assert_eq(
kdf.take([-10, -100, -1000, -10000]).sort_index(),
pdf.take([-10, -100, -1000, -10000]).sort_index(),
)
# axis=1
self.assert_eq(kdf.take([1, 2], axis=1).sort_index(), pdf.take([1, 2], axis=1).sort_index())
self.assert_eq(
kdf.take([-1, -2], axis=1).sort_index(), pdf.take([-1, -2], axis=1).sort_index()
)
self.assert_eq(
kdf.take(range(1, 3), axis=1).sort_index(), pdf.take(range(1, 3), axis=1).sort_index(),
)
self.assert_eq(
kdf.take(range(-1, -3), axis=1).sort_index(),
pdf.take(range(-1, -3), axis=1).sort_index(),
)
self.assert_eq(
kdf.take([2, 1], axis=1).sort_index(), pdf.take([2, 1], axis=1).sort_index(),
)
self.assert_eq(
kdf.take([-1, -2], axis=1).sort_index(), pdf.take([-1, -2], axis=1).sort_index(),
)
# MultiIndex columns
columns = pd.MultiIndex.from_tuples([("A", "Z"), ("B", "X"), ("C", "C")])
kdf.columns = columns
pdf.columns = columns
# MultiIndex columns with axis=0 (default)
self.assert_eq(kdf.take([1, 2]).sort_index(), pdf.take([1, 2]).sort_index())
self.assert_eq(kdf.take([-1, -2]).sort_index(), pdf.take([-1, -2]).sort_index())
self.assert_eq(
kdf.take(range(100, 110)).sort_index(), pdf.take(range(100, 110)).sort_index()
)
self.assert_eq(
kdf.take(range(-110, -100)).sort_index(), pdf.take(range(-110, -100)).sort_index()
)
self.assert_eq(
kdf.take([10, 100, 1000, 10000]).sort_index(),
pdf.take([10, 100, 1000, 10000]).sort_index(),
)
self.assert_eq(
kdf.take([-10, -100, -1000, -10000]).sort_index(),
pdf.take([-10, -100, -1000, -10000]).sort_index(),
)
# axis=1
self.assert_eq(kdf.take([1, 2], axis=1).sort_index(), pdf.take([1, 2], axis=1).sort_index())
self.assert_eq(
kdf.take([-1, -2], axis=1).sort_index(), pdf.take([-1, -2], axis=1).sort_index()
)
self.assert_eq(
kdf.take(range(1, 3), axis=1).sort_index(), pdf.take(range(1, 3), axis=1).sort_index(),
)
self.assert_eq(
kdf.take(range(-1, -3), axis=1).sort_index(),
pdf.take(range(-1, -3), axis=1).sort_index(),
)
self.assert_eq(
kdf.take([2, 1], axis=1).sort_index(), pdf.take([2, 1], axis=1).sort_index(),
)
self.assert_eq(
kdf.take([-1, -2], axis=1).sort_index(), pdf.take([-1, -2], axis=1).sort_index(),
)
# Checking the type of indices.
self.assertRaises(ValueError, lambda: kdf.take(1))
self.assertRaises(ValueError, lambda: kdf.take("1"))
self.assertRaises(ValueError, lambda: kdf.take({1, 2}))
self.assertRaises(ValueError, lambda: kdf.take({1: None, 2: None}))
def test_axes(self):
pdf = self.pdf
kdf = ks.from_pandas(pdf)
self.assert_list_eq(pdf.axes, kdf.axes)
# multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("y", "b")])
pdf.columns = columns
kdf.columns = columns
self.assert_list_eq(pdf.axes, kdf.axes)
def test_udt(self):
sparse_values = {0: 0.1, 1: 1.1}
sparse_vector = SparseVector(len(sparse_values), sparse_values)
pdf = pd.DataFrame({"a": [sparse_vector], "b": [10]})
if LooseVersion(pyspark.__version__) < LooseVersion("2.4"):
with self.sql_conf({"spark.sql.execution.arrow.enabled": False}):
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
else:
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf, pdf)
def test_eval(self):
pdf = pd.DataFrame({"A": range(1, 6), "B": range(10, 0, -2)})
kdf = ks.from_pandas(pdf)
# operation between columns (returns Series)
self.assert_eq(pdf.eval("A + B"), kdf.eval("A + B"))
self.assert_eq(pdf.eval("A + A"), kdf.eval("A + A"))
# assignment (returns DataFrame)
self.assert_eq(pdf.eval("C = A + B"), kdf.eval("C = A + B"))
self.assert_eq(pdf.eval("A = A + A"), kdf.eval("A = A + A"))
# operation between scalars (returns scalar)
self.assert_eq(pdf.eval("1 + 1"), kdf.eval("1 + 1"))
# complicated operations with assignment
self.assert_eq(
pdf.eval("B = A + B // (100 + 200) * (500 - B) - 10.5"),
kdf.eval("B = A + B // (100 + 200) * (500 - B) - 10.5"),
)
# inplace=True (only support for assignment)
pdf.eval("C = A + B", inplace=True)
kdf.eval("C = A + B", inplace=True)
self.assert_eq(pdf, kdf)
pser = pdf.A
kser = kdf.A
pdf.eval("A = B + C", inplace=True)
kdf.eval("A = B + C", inplace=True)
self.assert_eq(pdf, kdf)
self.assert_eq(pser, kser)
# doesn't support for multi-index columns
columns = pd.MultiIndex.from_tuples([("x", "a"), ("y", "b"), ("z", "c")])
kdf.columns = columns
self.assertRaises(ValueError, lambda: kdf.eval("x.a + y.b"))
def test_to_markdown(self):
pdf = pd.DataFrame(data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]})
kdf = ks.from_pandas(pdf)
# `to_markdown()` is supported in pandas >= 1.0.0 since it's newly added in pandas 1.0.0.
if LooseVersion(pd.__version__) < LooseVersion("1.0.0"):
self.assertRaises(NotImplementedError, lambda: kdf.to_markdown())
else:
self.assert_eq(pdf.to_markdown(), kdf.to_markdown())
def test_cache(self):
pdf = pd.DataFrame(
[(0.2, 0.3), (0.0, 0.6), (0.6, 0.0), (0.2, 0.1)], columns=["dogs", "cats"]
)
kdf = ks.from_pandas(pdf)
with kdf.cache() as cached_df:
self.assert_eq(isinstance(cached_df, CachedDataFrame), True)
self.assert_eq(
repr(cached_df.storage_level), repr(StorageLevel(True, True, False, True))
)
def test_persist(self):
pdf = pd.DataFrame(
[(0.2, 0.3), (0.0, 0.6), (0.6, 0.0), (0.2, 0.1)], columns=["dogs", "cats"]
)
kdf = ks.from_pandas(pdf)
storage_levels = [
StorageLevel.DISK_ONLY,
StorageLevel.MEMORY_AND_DISK,
StorageLevel.MEMORY_ONLY,
StorageLevel.OFF_HEAP,
]
for storage_level in storage_levels:
with kdf.persist(storage_level) as cached_df:
self.assert_eq(isinstance(cached_df, CachedDataFrame), True)
self.assert_eq(repr(cached_df.storage_level), repr(storage_level))
self.assertRaises(TypeError, lambda: kdf.persist("DISK_ONLY"))
def test_squeeze(self):
axises = [None, 0, 1, "rows", "index", "columns"]
# Multiple columns
pdf = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
kdf = ks.from_pandas(pdf)
for axis in axises:
self.assert_eq(pdf.squeeze(axis), kdf.squeeze(axis))
# Multiple columns with MultiIndex columns
columns = pd.MultiIndex.from_tuples([("A", "Z"), ("B", "X")])
pdf.columns = columns
kdf.columns = columns
for axis in axises:
self.assert_eq(pdf.squeeze(axis), kdf.squeeze(axis))
# Single column with single value
pdf = pd.DataFrame([[1]], columns=["a"])
kdf = ks.from_pandas(pdf)
for axis in axises:
self.assert_eq(pdf.squeeze(axis), kdf.squeeze(axis))
# Single column with single value with MultiIndex column
columns = pd.MultiIndex.from_tuples([("A", "Z")])
pdf.columns = columns
kdf.columns = columns
for axis in axises:
self.assert_eq(pdf.squeeze(axis), kdf.squeeze(axis))
# Single column with multiple values
pdf = pd.DataFrame([1, 2, 3, 4], columns=["a"])
kdf = ks.from_pandas(pdf)
for axis in axises:
self.assert_eq(pdf.squeeze(axis), kdf.squeeze(axis))
# Single column with multiple values with MultiIndex column
pdf.columns = columns
kdf.columns = columns
for axis in axises:
self.assert_eq(pdf.squeeze(axis), kdf.squeeze(axis))
def test_rfloordiv(self):
pdf = pd.DataFrame(
{"angles": [0, 3, 4], "degrees": [360, 180, 360]},
index=["circle", "triangle", "rectangle"],
columns=["angles", "degrees"],
)
kdf = ks.from_pandas(pdf)
if LooseVersion(pd.__version__) < LooseVersion("1.0.0") and LooseVersion(
pd.__version__
) >= LooseVersion("0.24.0"):
expected_result = pd.DataFrame(
{"angles": [np.inf, 3.0, 2.0], "degrees": [0.0, 0.0, 0.0]},
index=["circle", "triangle", "rectangle"],
columns=["angles", "degrees"],
)
else:
expected_result = pdf.rfloordiv(10)
self.assert_eq(kdf.rfloordiv(10), expected_result)
def test_truncate(self):
pdf1 = pd.DataFrame(
{
"A": ["a", "b", "c", "d", "e", "f", "g"],
"B": ["h", "i", "j", "k", "l", "m", "n"],
"C": ["o", "p", "q", "r", "s", "t", "u"],
},
index=[-500, -20, -1, 0, 400, 550, 1000],
)
kdf1 = ks.from_pandas(pdf1)
pdf2 = pd.DataFrame(
{
"A": ["a", "b", "c", "d", "e", "f", "g"],
"B": ["h", "i", "j", "k", "l", "m", "n"],
"C": ["o", "p", "q", "r", "s", "t", "u"],
},
index=[1000, 550, 400, 0, -1, -20, -500],
)
kdf2 = ks.from_pandas(pdf2)
self.assert_eq(kdf1.truncate(), pdf1.truncate())
self.assert_eq(kdf1.truncate(before=-20), pdf1.truncate(before=-20))
self.assert_eq(kdf1.truncate(after=400), pdf1.truncate(after=400))
self.assert_eq(kdf1.truncate(copy=False), pdf1.truncate(copy=False))
self.assert_eq(kdf1.truncate(-20, 400, copy=False), pdf1.truncate(-20, 400, copy=False))
self.assert_eq(kdf2.truncate(0, 550), pdf2.truncate(0, 550))
self.assert_eq(kdf2.truncate(0, 550, copy=False), pdf2.truncate(0, 550, copy=False))
# axis = 1
self.assert_eq(kdf1.truncate(axis=1), pdf1.truncate(axis=1))
self.assert_eq(kdf1.truncate(before="B", axis=1), pdf1.truncate(before="B", axis=1))
self.assert_eq(kdf1.truncate(after="A", axis=1), pdf1.truncate(after="A", axis=1))
self.assert_eq(kdf1.truncate(copy=False, axis=1), pdf1.truncate(copy=False, axis=1))
self.assert_eq(kdf2.truncate("B", "C", axis=1), pdf2.truncate("B", "C", axis=1))
self.assert_eq(
kdf1.truncate("B", "C", copy=False, axis=1), pdf1.truncate("B", "C", copy=False, axis=1)
)
# MultiIndex columns
columns = pd.MultiIndex.from_tuples([("A", "Z"), ("B", "X"), ("C", "Z")])
pdf1.columns = columns
kdf1.columns = columns
pdf2.columns = columns
kdf2.columns = columns
self.assert_eq(kdf1.truncate(), pdf1.truncate())
self.assert_eq(kdf1.truncate(before=-20), pdf1.truncate(before=-20))
self.assert_eq(kdf1.truncate(after=400), pdf1.truncate(after=400))
self.assert_eq(kdf1.truncate(copy=False), pdf1.truncate(copy=False))
self.assert_eq(kdf1.truncate(-20, 400, copy=False), pdf1.truncate(-20, 400, copy=False))
self.assert_eq(kdf2.truncate(0, 550), pdf2.truncate(0, 550))
self.assert_eq(kdf2.truncate(0, 550, copy=False), pdf2.truncate(0, 550, copy=False))
# axis = 1
self.assert_eq(kdf1.truncate(axis=1), pdf1.truncate(axis=1))
self.assert_eq(kdf1.truncate(before="B", axis=1), pdf1.truncate(before="B", axis=1))
self.assert_eq(kdf1.truncate(after="A", axis=1), pdf1.truncate(after="A", axis=1))
self.assert_eq(kdf1.truncate(copy=False, axis=1), pdf1.truncate(copy=False, axis=1))
self.assert_eq(kdf2.truncate("B", "C", axis=1), pdf2.truncate("B", "C", axis=1))
self.assert_eq(
kdf1.truncate("B", "C", copy=False, axis=1), pdf1.truncate("B", "C", copy=False, axis=1)
)
# Exceptions
kdf = ks.DataFrame(
{
"A": ["a", "b", "c", "d", "e", "f", "g"],
"B": ["h", "i", "j", "k", "l", "m", "n"],
"C": ["o", "p", "q", "r", "s", "t", "u"],
},
index=[-500, 100, 400, 0, -1, 550, -20],
)
msg = "truncate requires a sorted index"
with self.assertRaisesRegex(ValueError, msg):
kdf.truncate()
kdf = ks.DataFrame(
{
"A": ["a", "b", "c", "d", "e", "f", "g"],
"B": ["h", "i", "j", "k", "l", "m", "n"],
"C": ["o", "p", "q", "r", "s", "t", "u"],
},
index=[-500, -20, -1, 0, 400, 550, 1000],
)
msg = "Truncate: -20 must be after 400"
with self.assertRaisesRegex(ValueError, msg):
kdf.truncate(400, -20)
msg = "Truncate: B must be after C"
with self.assertRaisesRegex(ValueError, msg):
kdf.truncate("C", "B", axis=1)
def test_explode(self):
pdf = pd.DataFrame({"A": [[-1.0, np.nan], [0.0, np.inf], [1.0, -np.inf]], "B": 1})
pdf.index.name = "index"
pdf.columns.name = "columns"
kdf = ks.from_pandas(pdf)
if LooseVersion(pd.__version__) >= LooseVersion("0.25.0"):
expected_result1 = pdf.explode("A")
expected_result2 = pdf.explode("B")
else:
expected_result1 = pd.DataFrame(
{"A": [-1, np.nan, 0, np.inf, 1, -np.inf], "B": [1, 1, 1, 1, 1, 1]},
index=pd.Index([0, 0, 1, 1, 2, 2]),
)
expected_result1.index.name = "index"
expected_result1.columns.name = "columns"
expected_result2 = pdf
self.assert_eq(kdf.explode("A"), expected_result1, almost=True)
self.assert_eq(repr(kdf.explode("B")), repr(expected_result2))
self.assert_eq(kdf.explode("A").index.name, expected_result1.index.name)
self.assert_eq(kdf.explode("A").columns.name, expected_result1.columns.name)
self.assertRaises(ValueError, lambda: kdf.explode(["A", "B"]))
# MultiIndex
midx = pd.MultiIndex.from_tuples(
[("x", "a"), ("x", "b"), ("y", "c")], names=["index1", "index2"]
)
pdf.index = midx
kdf = ks.from_pandas(pdf)
if LooseVersion(pd.__version__) >= LooseVersion("0.25.0"):
expected_result1 = pdf.explode("A")
expected_result2 = pdf.explode("B")
else:
midx = pd.MultiIndex.from_tuples(
[("x", "a"), ("x", "a"), ("x", "b"), ("x", "b"), ("y", "c"), ("y", "c")],
names=["index1", "index2"],
)
expected_result1.index = midx
expected_result2 = pdf
self.assert_eq(kdf.explode("A"), expected_result1, almost=True)
self.assert_eq(repr(kdf.explode("B")), repr(expected_result2))
self.assert_eq(kdf.explode("A").index.names, expected_result1.index.names)
self.assert_eq(kdf.explode("A").columns.name, expected_result1.columns.name)
self.assertRaises(ValueError, lambda: kdf.explode(["A", "B"]))
# MultiIndex columns
columns = pd.MultiIndex.from_tuples([("A", "Z"), ("B", "X")], names=["column1", "column2"])
pdf.columns = columns
kdf.columns = columns
if LooseVersion(pd.__version__) >= LooseVersion("0.25.0"):
expected_result1 = pdf.explode(("A", "Z"))
expected_result2 = pdf.explode(("B", "X"))
expected_result3 = pdf.A.explode("Z")
else:
expected_result1.columns = columns
expected_result2 = pdf
expected_result3 = pd.DataFrame({"Z": [-1, np.nan, 0, np.inf, 1, -np.inf]}, index=midx)
expected_result3.index.name = "index"
expected_result3.columns.name = "column2"
self.assert_eq(kdf.explode(("A", "Z")), expected_result1, almost=True)
self.assert_eq(repr(kdf.explode(("B", "X"))), repr(expected_result2))
self.assert_eq(kdf.explode(("A", "Z")).index.names, expected_result1.index.names)
self.assert_eq(kdf.explode(("A", "Z")).columns.names, expected_result1.columns.names)
self.assert_eq(kdf.A.explode("Z"), expected_result3, almost=True)
self.assertRaises(ValueError, lambda: kdf.explode(["A", "B"]))
self.assertRaises(ValueError, lambda: kdf.explode("A"))
def test_spark_schema(self):
kdf = ks.DataFrame(
{
"a": list("abc"),
"b": list(range(1, 4)),
"c": np.arange(3, 6).astype("i1"),
"d": np.arange(4.0, 7.0, dtype="float64"),
"e": [True, False, True],
"f": pd.date_range("20130101", periods=3),
},
columns=["a", "b", "c", "d", "e", "f"],
)
self.assertEqual(kdf.spark_schema(), kdf.spark.schema())
self.assertEqual(kdf.spark_schema("index"), kdf.spark.schema("index"))
def test_print_schema(self):
kdf = ks.DataFrame(
{"a": list("abc"), "b": list(range(1, 4)), "c": np.arange(3, 6).astype("i1")},
columns=["a", "b", "c"],
)
prev = sys.stdout
try:
out = StringIO()
sys.stdout = out
kdf.print_schema()
actual = out.getvalue().strip()
out = StringIO()
sys.stdout = out
kdf.spark.print_schema()
expected = out.getvalue().strip()
self.assertEqual(actual, expected)
finally:
sys.stdout = prev
def test_explain_hint(self):
kdf1 = ks.DataFrame(
{"lkey": ["foo", "bar", "baz", "foo"], "value": [1, 2, 3, 5]}, columns=["lkey", "value"]
)
kdf2 = ks.DataFrame(
{"rkey": ["foo", "bar", "baz", "foo"], "value": [5, 6, 7, 8]}, columns=["rkey", "value"]
)
merged = kdf1.merge(kdf2.hint("broadcast"), left_on="lkey", right_on="rkey")
prev = sys.stdout
try:
out = StringIO()
sys.stdout = out
merged.explain()
actual = out.getvalue().strip()
out = StringIO()
sys.stdout = out
merged.spark.explain()
expected = out.getvalue().strip()
self.assertEqual(actual, expected)
finally:
sys.stdout = prev
def test_mad(self):
pdf = pd.DataFrame({"A": [1, 2, None, 4, np.nan], "B": [-0.1, 0.2, -0.3, np.nan, 0.5]})
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.mad(), pdf.mad())
self.assert_eq(kdf.mad(axis=1), pdf.mad(axis=1))
with self.assertRaises(ValueError):
kdf.mad(axis=2)
# MultiIndex columns
columns = pd.MultiIndex.from_tuples([("A", "X"), ("A", "Y")])
pdf.columns = columns
kdf.columns = columns
self.assert_eq(kdf.mad(), pdf.mad())
self.assert_eq(kdf.mad(axis=1), pdf.mad(axis=1))
pdf = pd.DataFrame({"A": [True, True, False, False], "B": [True, False, False, True]})
kdf = ks.from_pandas(pdf)
self.assert_eq(kdf.mad(), pdf.mad())
self.assert_eq(kdf.mad(axis=1), pdf.mad(axis=1))
def test_abs(self):
pdf = pd.DataFrame({"a": [-2, -1, 0, 1]})
kdf = ks.from_pandas(pdf)
self.assert_eq(abs(kdf), abs(pdf))
self.assert_eq(np.abs(kdf), np.abs(pdf))
def test_iteritems(self):
pdf = pd.DataFrame(
{"species": ["bear", "bear", "marsupial"], "population": [1864, 22000, 80000]},
index=["panda", "polar", "koala"],
columns=["species", "population"],
)
kdf = ks.from_pandas(pdf)
for p_items, k_items in zip(pdf.iteritems(), kdf.iteritems()):
self.assert_eq(repr(p_items), repr(k_items))
| 1 | 15,682 | Why are we using `repr`? | databricks-koalas | py |
@@ -21,6 +21,6 @@ class ZMSBinder extends AbstractBinder {
@Override
protected void configure() {
- bind(new ZMSImpl()).to(ZMSHandler.class);
+ bind(ZMSImplFactory.getZmsInstance()).to(ZMSHandler.class);
}
} | 1 | /*
* Copyright 2017 Yahoo Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.zms;
import org.glassfish.jersey.internal.inject.AbstractBinder;
class ZMSBinder extends AbstractBinder {
@Override
protected void configure() {
bind(new ZMSImpl()).to(ZMSHandler.class);
}
}
| 1 | 5,495 | I use the same zms instance to check authentication in swagger endpoints. Same thing in ZTS. | AthenZ-athenz | java |
@@ -114,7 +114,11 @@ public class JavaProcessJobTest {
props.put(CommonJobProperties.JOB_ID, "test_job");
props.put(CommonJobProperties.EXEC_ID, "123");
props.put(CommonJobProperties.SUBMIT_USER, "test_user");
- props.put("execute.as.user", "false");
+
+ //The execute-as-user binary requires special permission. It's not convenient to
+ //set up in a unit test that is self contained. So EXECUTE_AS_USER is set to false
+ //so that we don't have to rely on the binary file to change user in the test case.
+ props.put(ProcessJob.EXECUTE_AS_USER, "false");
job = new JavaProcessJob("testJavaProcess", props, props, log);
} | 1 | /*
* Copyright 2014 LinkedIn 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.
*/
package azkaban.jobExecutor;
import java.io.IOException;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import azkaban.flow.CommonJobProperties;
import azkaban.utils.Props;
public class JavaProcessJobTest {
@ClassRule
public static TemporaryFolder classTemp = new TemporaryFolder();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private JavaProcessJob job = null;
private Props props = null;
private Logger log = Logger.getLogger(JavaProcessJob.class);
private static String classPaths;
private static final String inputContent =
"Quick Change in Strategy for a Bookseller \n"
+ " By JULIE BOSMAN \n"
+ "Published: August 11, 2010 \n"
+ " \n"
+ "Twelve years later, it may be Joe Fox's turn to worry. Readers have gone from skipping small \n"
+ "bookstores to wondering if they need bookstores at all. More people are ordering books online \n"
+ "or plucking them from the best-seller bin at Wal-Mart";
private static final String errorInputContent =
inputContent
+ "\n stop_here "
+ "But the threat that has the industry and some readers the most rattled is the growth of e-books. \n"
+ " In the first five months of 2009, e-books made up 2.9 percent of trade book sales. In the same period \n"
+ "in 2010, sales of e-books, which generally cost less than hardcover books, grew to 8.5 percent, according \n"
+ "to the Association of American Publishers, spurred by sales of the Amazon Kindle and the new Apple iPad. \n"
+ "For Barnes & Noble, long the largest and most powerful bookstore chain in the country, the new competition \n"
+ "has led to declining profits and store traffic.";
private static String inputFile;
private static String errorInputFile;
private static String outputFile;
@BeforeClass
public static void init() throws IOException {
// Get the classpath
Properties prop = System.getProperties();
classPaths =
String.format("'%s'", prop.getProperty("java.class.path", null));
long time = (new Date()).getTime();
inputFile = classTemp.newFile("azkaban_input_" + time).getCanonicalPath();
errorInputFile =
classTemp.newFile("azkaban_input_error_" + time).getCanonicalPath();
outputFile = classTemp.newFile("azkaban_output_" + time).getCanonicalPath();
// Dump input files
try {
Utils.dumpFile(inputFile, inputContent);
Utils.dumpFile(errorInputFile, errorInputContent);
} catch (IOException e) {
e.printStackTrace(System.err);
Assert.fail("error in creating input file:" + e.getLocalizedMessage());
}
}
@AfterClass
public static void cleanup() {
classTemp.delete();
}
@Before
public void setUp() throws IOException {
File workingDir = temp.newFolder("testJavaProcess");
// Initialize job
props = new Props();
props.put(AbstractProcessJob.WORKING_DIR, workingDir.getCanonicalPath());
props.put("type", "java");
props.put("fullPath", ".");
props.put(CommonJobProperties.PROJECT_NAME, "test_project");
props.put(CommonJobProperties.FLOW_ID, "test_flow");
props.put(CommonJobProperties.JOB_ID, "test_job");
props.put(CommonJobProperties.EXEC_ID, "123");
props.put(CommonJobProperties.SUBMIT_USER, "test_user");
props.put("execute.as.user", "false");
job = new JavaProcessJob("testJavaProcess", props, props, log);
}
@After
public void tearDown() {
temp.delete();
}
@Test
public void testJavaJob() throws Exception {
// initialize the Props
props.put(JavaProcessJob.JAVA_CLASS,
"azkaban.jobExecutor.WordCountLocal");
props.put("input", inputFile);
props.put("output", outputFile);
props.put("classpath", classPaths);
job.run();
}
@Test
public void testJavaJobHashmap() throws Exception {
// initialize the Props
props.put(JavaProcessJob.JAVA_CLASS,
"azkaban.executor.SleepJavaJob");
props.put("seconds", 1);
props.put("input", inputFile);
props.put("output", outputFile);
props.put("classpath", classPaths);
job.run();
}
@Test
public void testFailedJavaJob() throws Exception {
props.put(JavaProcessJob.JAVA_CLASS,
"azkaban.jobExecutor.WordCountLocal");
props.put("input", errorInputFile);
props.put("output", outputFile);
props.put("classpath", classPaths);
try {
job.run();
} catch (RuntimeException e) {
Assert.assertTrue(true);
}
}
}
| 1 | 11,827 | Consider consolidating the common code in a common setup method in tests? | azkaban-azkaban | java |
@@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verifyNoInteractions;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
-import org.hyperledger.besu.util.number.PositiveNumber;
+import org.hyperledger.besu.ethereum.eth.ImmutableEthProtocolConfiguration;
import org.junit.Test;
| 1 | /*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.cli.options;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verifyNoInteractions;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.util.number.PositiveNumber;
import org.junit.Test;
public class EthProtocolOptionsTest
extends AbstractCLIOptionsTest<EthProtocolConfiguration, EthProtocolOptions> {
@Test
public void parsesValidEwpMaxGetHeadersOptions() {
final TestBesuCommand cmd = parseCommand("--Xewp-max-get-headers", "13");
final EthProtocolOptions options = getOptionsFromBesuCommand(cmd);
final EthProtocolConfiguration config = options.toDomainObject();
assertThat(config.getMaxGetBlockHeaders()).isEqualTo(13);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString()).isEmpty();
}
@Test
public void parsesInvalidEwpMaxGetHeadersOptionsShouldFail() {
parseCommand("--Xewp-max-get-headers", "-13");
verifyNoInteractions(mockRunnerBuilder);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString())
.contains(
"Invalid value for option '--Xewp-max-get-headers': cannot convert '-13' to PositiveNumber");
}
@Test
public void parsesValidEwpMaxGetBodiesOptions() {
final TestBesuCommand cmd = parseCommand("--Xewp-max-get-bodies", "14");
final EthProtocolOptions options = getOptionsFromBesuCommand(cmd);
final EthProtocolConfiguration config = options.toDomainObject();
assertThat(config.getMaxGetBlockBodies()).isEqualTo(14);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString()).isEmpty();
}
@Test
public void parsesInvalidEwpMaxGetBodiesOptionsShouldFail() {
parseCommand("--Xewp-max-get-bodies", "-14");
verifyNoInteractions(mockRunnerBuilder);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString())
.contains(
"Invalid value for option '--Xewp-max-get-bodies': cannot convert '-14' to PositiveNumber");
}
@Test
public void parsesValidEwpMaxGetReceiptsOptions() {
final TestBesuCommand cmd = parseCommand("--Xewp-max-get-receipts", "15");
final EthProtocolOptions options = getOptionsFromBesuCommand(cmd);
final EthProtocolConfiguration config = options.toDomainObject();
assertThat(config.getMaxGetReceipts()).isEqualTo(15);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString()).isEmpty();
}
@Test
public void parsesInvalidEwpMaxGetReceiptsOptionsShouldFail() {
parseCommand("--Xewp-max-get-receipts", "-15");
verifyNoInteractions(mockRunnerBuilder);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString())
.contains(
"Invalid value for option '--Xewp-max-get-receipts': cannot convert '-15' to PositiveNumber");
}
@Test
public void parsesValidEwpMaxGetNodeDataOptions() {
final TestBesuCommand cmd = parseCommand("--Xewp-max-get-node-data", "16");
final EthProtocolOptions options = getOptionsFromBesuCommand(cmd);
final EthProtocolConfiguration config = options.toDomainObject();
assertThat(config.getMaxGetNodeData()).isEqualTo(16);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString()).isEmpty();
}
@Test
public void parsesInvalidEwpMaxGetNodeDataOptionsShouldFail() {
parseCommand("--Xewp-max-get-node-data", "-16");
verifyNoInteractions(mockRunnerBuilder);
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString())
.contains(
"Invalid value for option '--Xewp-max-get-node-data': cannot convert '-16' to PositiveNumber");
}
@Override
EthProtocolConfiguration createDefaultDomainObject() {
return EthProtocolConfiguration.builder().build();
}
@Override
EthProtocolConfiguration createCustomizedDomainObject() {
return EthProtocolConfiguration.builder()
.maxGetBlockHeaders(
PositiveNumber.fromInt(EthProtocolConfiguration.DEFAULT_MAX_GET_BLOCK_HEADERS + 2))
.maxGetBlockBodies(
PositiveNumber.fromInt(EthProtocolConfiguration.DEFAULT_MAX_GET_BLOCK_BODIES + 2))
.maxGetReceipts(
PositiveNumber.fromInt(EthProtocolConfiguration.DEFAULT_MAX_GET_RECEIPTS + 2))
.maxGetNodeData(
PositiveNumber.fromInt(EthProtocolConfiguration.DEFAULT_MAX_GET_NODE_DATA + 2))
.maxGetPooledTransactions(
PositiveNumber.fromInt(
EthProtocolConfiguration.DEFAULT_MAX_GET_POOLED_TRANSACTIONS + 2))
.eth65Enabled(!EthProtocolConfiguration.DEFAULT_ETH_65_ENABLED)
.build();
}
@Override
EthProtocolOptions optionsFromDomainObject(final EthProtocolConfiguration domainObject) {
return EthProtocolOptions.fromConfig(domainObject);
}
@Override
EthProtocolOptions getOptionsFromBesuCommand(final TestBesuCommand besuCommand) {
return besuCommand.getEthProtocolOptions();
}
}
| 1 | 22,993 | q: do you need to run the annotation processor over EthProtocolConfiguration prior to writing this file? (i.e.to ensure ImmutableEthProtcolConfiguration exists)? Does Auto-import etc. still work in the IDE? | hyperledger-besu | java |
@@ -69,12 +69,12 @@ public class SchemaTypeTable implements ImportTypeTable, SchemaTypeFormatter {
}
@Override
- public String getNicknameFor(Schema type) {
+ public String getNicknameFor(DiscoveryField type) {
return typeNameConverter.getTypeName(type).getNickname();
}
@Override
- public String getFullNameFor(Schema type) {
+ public String getFullNameFor(DiscoveryField type) {
return typeFormatter.getFullNameFor(type);
}
| 1 | /* Copyright 2017 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.codegen.transformer;
import com.google.api.codegen.config.DiscoveryField;
import com.google.api.codegen.config.DiscoveryRequestType;
import com.google.api.codegen.config.FieldConfig;
import com.google.api.codegen.config.FieldModel;
import com.google.api.codegen.config.InterfaceModel;
import com.google.api.codegen.config.TypeModel;
import com.google.api.codegen.discogapic.transformer.DiscoGapicNamer;
import com.google.api.codegen.discovery.Method;
import com.google.api.codegen.discovery.Schema;
import com.google.api.codegen.transformer.SchemaTypeNameConverter.BoxingBehavior;
import com.google.api.codegen.util.TypeAlias;
import com.google.api.codegen.util.TypeName;
import com.google.api.codegen.util.TypeTable;
import com.google.api.codegen.util.TypedValue;
import java.util.Map;
/**
* A SchemaTypeTable manages the imports for a set of fully-qualified type names, and provides
* helper methods for importing instances of Schema.
*/
public class SchemaTypeTable implements ImportTypeTable, SchemaTypeFormatter {
private SchemaTypeFormatterImpl typeFormatter;
private TypeTable typeTable;
private SchemaTypeNameConverter typeNameConverter;
private DiscoGapicNamer discoGapicNamer;
private SurfaceNamer languageNamer;
public SchemaTypeTable(
TypeTable typeTable, SchemaTypeNameConverter typeNameConverter, SurfaceNamer languageNamer) {
this(typeTable, typeNameConverter, languageNamer, new DiscoGapicNamer());
}
private SchemaTypeTable(
TypeTable typeTable,
SchemaTypeNameConverter typeNameConverter,
SurfaceNamer languageNamer,
DiscoGapicNamer discoGapicNamer) {
this.typeFormatter = new SchemaTypeFormatterImpl(typeNameConverter);
this.typeTable = typeTable;
this.typeNameConverter = typeNameConverter;
this.languageNamer = languageNamer;
this.discoGapicNamer = discoGapicNamer;
}
@Override
public SchemaTypeNameConverter getTypeNameConverter() {
return typeNameConverter;
}
@Override
public String renderPrimitiveValue(Schema type, String value) {
return typeFormatter.renderPrimitiveValue(type, value);
}
@Override
public String getNicknameFor(Schema type) {
return typeNameConverter.getTypeName(type).getNickname();
}
@Override
public String getFullNameFor(Schema type) {
return typeFormatter.getFullNameFor(type);
}
@Override
public String getImplicitPackageFullNameFor(String shortName) {
return typeFormatter.getImplicitPackageFullNameFor(shortName);
}
@Override
public String getInnerTypeNameFor(Schema schema) {
return typeFormatter.getInnerTypeNameFor(schema);
}
@Override
public String getEnumValue(FieldModel type, String value) {
return getNotImplementedString("SchemaTypeTable.getFullNameFor(FieldModel type, String value)");
}
@Override
public String getEnumValue(TypeModel type, String value) {
// TODO(andrealin): implement.
return getNotImplementedString("SchemaTypeTable.getEnumValue(TypeModel type, String value)");
}
@Override
public String getAndSaveNicknameFor(TypeModel type) {
return typeTable.getAndSaveNicknameFor(typeNameConverter.getTypeName(type));
}
/** Creates a new SchemaTypeTable of the same concrete type, but with an empty import set. */
@Override
public SchemaTypeTable cloneEmpty() {
return new SchemaTypeTable(
typeTable.cloneEmpty(), typeNameConverter, languageNamer, discoGapicNamer);
}
@Override
public SchemaTypeTable cloneEmpty(String packageName) {
return new SchemaTypeTable(
typeTable.cloneEmpty(packageName), typeNameConverter, languageNamer, discoGapicNamer);
}
/** Compute the nickname for the given fullName and save it in the import set. */
@Override
public void saveNicknameFor(String fullName) {
getAndSaveNicknameFor(fullName);
}
/**
* Computes the nickname for the given full name, adds the full name to the import set, and
* returns the nickname.
*/
@Override
public String getAndSaveNicknameFor(String fullName) {
return typeTable.getAndSaveNicknameFor(fullName);
}
/** Adds the given type alias to the import set, and returns the nickname. */
@Override
public String getAndSaveNicknameFor(TypeAlias typeAlias) {
return typeTable.getAndSaveNicknameFor(typeAlias);
}
/**
* Computes the nickname for the given container full name and inner type short name, adds the
* full inner type name to the static import set, and returns the nickname.
*/
@Override
public String getAndSaveNicknameForInnerType(
String containerFullName, String innerTypeShortName) {
return typeTable.getAndSaveNicknameForInnerType(containerFullName, innerTypeShortName);
}
/**
* Computes the nickname for the given type, adds the full name to the import set, and returns the
* nickname.
*/
public String getAndSaveNicknameFor(Schema schema) {
return typeTable.getAndSaveNicknameFor(
typeNameConverter.getTypeName(schema, BoxingBehavior.BOX_PRIMITIVES));
}
public String getFullNameForElementType(Schema type) {
return typeFormatter.getFullNameFor(type);
}
/** Get the full name for the given type. */
@Override
public String getFullNameFor(FieldModel type) {
return getFullNameFor(((DiscoveryField) type).getDiscoveryField());
}
@Override
public String getFullNameFor(InterfaceModel type) {
return type.getFullName();
}
@Override
public String getFullNameFor(TypeModel type) {
if (type instanceof DiscoveryRequestType) {
Method method = ((DiscoveryRequestType) type).parentMethod().getDiscoMethod();
return discoGapicNamer.getRequestTypeName(method, languageNamer).getFullName();
}
return typeFormatter.getFullNameFor(type);
}
@Override
public String getFullNameForMessageType(TypeModel type) {
return getFullNameFor(type);
}
/** Get the full name for the element type of the given type. */
@Override
public String getFullNameForElementType(FieldModel type) {
return getFullNameForElementType(((DiscoveryField) type).getDiscoveryField());
}
/** Get the full name for the element type of the given type. */
@Override
public String getFullNameForElementType(TypeModel type) {
return getFullNameForElementType(((DiscoveryField) type).getDiscoveryField());
}
@Override
public String getAndSaveNicknameForElementType(TypeModel type) {
return getAndSaveNicknameForElementType(((FieldModel) type));
}
/** Returns the nickname for the given type (without adding the full name to the import set). */
@Override
public String getNicknameFor(FieldModel type) {
return typeFormatter.getNicknameFor(type);
}
@Override
public String getNicknameFor(TypeModel type) {
return typeFormatter.getNicknameFor(type);
}
/** Renders the primitive value of the given type. */
@Override
public String renderPrimitiveValue(FieldModel type, String key) {
return typeNameConverter.renderPrimitiveValue(type, key);
}
@Override
public String renderPrimitiveValue(TypeModel type, String key) {
return typeFormatter.renderPrimitiveValue(type, key);
}
@Override
public String renderValueAsString(String key) {
return typeNameConverter.renderValueAsString(key);
}
/**
* Computes the nickname for the given type, adds the full name to the import set, and returns the
* nickname.
*/
@Override
public String getAndSaveNicknameFor(FieldModel type) {
return typeTable.getAndSaveNicknameFor(
typeNameConverter.getTypeName(((DiscoveryField) type).getDiscoveryField()));
}
/*
* Computes the nickname for the given FieldConfig, and ResourceName. Adds the full name to
* the import set, and returns the nickname.
*/
@Override
public String getAndSaveNicknameForTypedResourceName(
FieldConfig fieldConfig, String typedResourceShortName) {
return typeTable.getAndSaveNicknameFor(
typeNameConverter.getTypeNameForTypedResourceName(fieldConfig, typedResourceShortName));
}
/*
* Computes the nickname for the element type given FieldConfig, and ResourceName. Adds the full
* name to the import set, and returns the nickname.
*/
@Override
public String getAndSaveNicknameForResourceNameElementType(
FieldConfig fieldConfig, String typedResourceShortName) {
return typeTable.getAndSaveNicknameFor(
typeNameConverter.getTypeNameForResourceNameElementType(
fieldConfig, typedResourceShortName));
}
@Override
public String getAndSaveNicknameForElementType(FieldModel type) {
return typeTable.getAndSaveNicknameFor(typeNameConverter.getTypeNameForElementType(type));
}
@Override
public String getAndSaveNicknameForContainer(
String containerFullName, String... elementFullNames) {
TypeName completeTypeName = typeTable.getContainerTypeName(containerFullName, elementFullNames);
return typeTable.getAndSaveNicknameFor(completeTypeName);
}
@Override
public String getSnippetZeroValueAndSaveNicknameFor(FieldModel type) {
return typeNameConverter.getSnippetZeroValue(type).getValueAndSaveTypeNicknameIn(typeTable);
}
@Override
public String getSnippetZeroValueAndSaveNicknameFor(TypeModel type) {
TypedValue typedValue = typeNameConverter.getSnippetZeroValue(type);
return typedValue.getValueAndSaveTypeNicknameIn(typeTable);
}
@Override
public String getImplZeroValueAndSaveNicknameFor(FieldModel type) {
return typeNameConverter.getImplZeroValue(type).getValueAndSaveTypeNicknameIn(typeTable);
}
/** Returns the imports accumulated so far. */
@Override
public Map<String, TypeAlias> getImports() {
return typeTable.getImports();
}
@Override
public TypeTable getTypeTable() {
return typeTable;
}
public String getNotImplementedString(String feature) {
return "$ NOT IMPLEMENTED: " + feature + " $";
}
}
| 1 | 25,368 | What is the motivation for switching from `Schema` to `DiscoveryField` everywhere? | googleapis-gapic-generator | java |
@@ -353,6 +353,8 @@ func environmentConfig() (Config, error) {
errs = append(errs, err)
}
}
+ containerMetadataEnabled := utils.ParseBool(os.Getenv("ECS_ENABLE_CONTAINER_METADATA"), false)
+ dataDirOnHost := os.Getenv("ECS_HOST_DATA_DIR")
if len(errs) > 0 {
err = utils.NewMultiError(errs...) | 1 | // Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package config
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/aws/amazon-ecs-agent/agent/ec2"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/cihub/seelog"
cnitypes "github.com/containernetworking/cni/pkg/types"
)
const (
// http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker
DockerReservedPort = 2375
DockerReservedSSLPort = 2376
SSHPort = 22
// AgentIntrospectionPort is used to serve the metadata about the agent and to query the tasks being managed by the agent.
AgentIntrospectionPort = 51678
// AgentCredentialsPort is used to serve the credentials for tasks.
AgentCredentialsPort = 51679
// defaultConfigFileName is the default (json-formatted) config file
defaultConfigFileName = "/etc/ecs_container_agent/config.json"
// DefaultClusterName is the name of the default cluster.
DefaultClusterName = "default"
// DefaultTaskCleanupWaitDuration specifies the default value for task cleanup duration. It is used to
// clean up task's containers.
DefaultTaskCleanupWaitDuration = 3 * time.Hour
// DefaultDockerStopTimeout specifies the value for container stop timeout duration
DefaultDockerStopTimeout = 30 * time.Second
// DefaultImageCleanupTimeInterval specifies the default value for image cleanup duration. It is used to
// remove the images pulled by agent.
DefaultImageCleanupTimeInterval = 30 * time.Minute
// DefaultNumImagesToDeletePerCycle specifies the default number of images to delete when agent performs
// image cleanup.
DefaultNumImagesToDeletePerCycle = 5
//DefaultImageDeletionAge specifies the default value for minimum amount of elapsed time after an image
// has been pulled before it can be deleted.
DefaultImageDeletionAge = 1 * time.Hour
// minimumTaskCleanupWaitDuration specifies the minimum duration to wait before cleaning up
// a task's container. This is used to enforce sane values for the config.TaskCleanupWaitDuration field.
minimumTaskCleanupWaitDuration = 1 * time.Minute
// minimumDockerStopTimeout specifies the minimum value for docker StopContainer API
minimumDockerStopTimeout = 1 * time.Second
// minimumImageCleanupInterval specifies the minimum time for agent to wait before performing
// image cleanup.
minimumImageCleanupInterval = 10 * time.Minute
// minimumNumImagesToDeletePerCycle specifies the minimum number of images that to be deleted when
// performing image cleanup.
minimumNumImagesToDeletePerCycle = 1
// defaultCNIPluginsPath is the default path where cni binaries are located
defaultCNIPluginsPath = "/amazon-ecs-cni-plugins"
// DefaultMinSupportedCNIVersion denotes the minimum version of cni spec required
DefaultMinSupportedCNIVersion = "0.3.0"
// pauseContainerTarball is the path to the pause container tarball
pauseContainerTarballPath = "/images/amazon-ecs-pause.tar"
)
var (
// DefaultPauseContainerImageName is the name of the pause container image. The linker's
// load flags are used to populate this value from the Makefile
DefaultPauseContainerImageName = ""
// DefaultPauseContainerTag is the tag for the pause container image. The linker's load
// flags are used to populate this value from the Makefile
DefaultPauseContainerTag = ""
)
// Merge merges two config files, preferring the ones on the left. Any nil or
// zero values present in the left that are not present in the right will be
// overridden
func (cfg *Config) Merge(rhs Config) *Config {
left := reflect.ValueOf(cfg).Elem()
right := reflect.ValueOf(&rhs).Elem()
for i := 0; i < left.NumField(); i++ {
leftField := left.Field(i)
if utils.ZeroOrNil(leftField.Interface()) {
leftField.Set(reflect.ValueOf(right.Field(i).Interface()))
}
}
return cfg //make it chainable
}
// complete returns true if all fields of the config are populated / nonzero
func (cfg *Config) complete() bool {
cfgElem := reflect.ValueOf(cfg).Elem()
for i := 0; i < cfgElem.NumField(); i++ {
if utils.ZeroOrNil(cfgElem.Field(i).Interface()) {
return false
}
}
return true
}
// checkMissingAndDeprecated checks all zero-valued fields for tags of the form
// missing:STRING and acts based on that string. Current options are: fatal,
// warn. Fatal will result in an error being returned, warn will result in a
// warning that the field is missing being logged.
func (cfg *Config) checkMissingAndDepreciated() error {
cfgElem := reflect.ValueOf(cfg).Elem()
cfgStructField := reflect.Indirect(reflect.ValueOf(cfg)).Type()
fatalFields := []string{}
for i := 0; i < cfgElem.NumField(); i++ {
cfgField := cfgElem.Field(i)
if utils.ZeroOrNil(cfgField.Interface()) {
missingTag := cfgStructField.Field(i).Tag.Get("missing")
if len(missingTag) == 0 {
continue
}
switch missingTag {
case "warn":
seelog.Warnf("Configuration key not set, key: %v", cfgStructField.Field(i).Name)
case "fatal":
seelog.Criticalf("Configuration key not set, key: %v", cfgStructField.Field(i).Name)
fatalFields = append(fatalFields, cfgStructField.Field(i).Name)
default:
seelog.Warnf("Unexpected `missing` tag value, tag %v", missingTag)
}
} else {
// present
deprecatedTag := cfgStructField.Field(i).Tag.Get("deprecated")
if len(deprecatedTag) == 0 {
continue
}
seelog.Warnf("Use of deprecated configuration key, key: %v message: %v", cfgStructField.Field(i).Name, deprecatedTag)
}
}
if len(fatalFields) > 0 {
return errors.New("Missing required fields: " + strings.Join(fatalFields, ", "))
}
return nil
}
// trimWhitespace trims whitespace from all string cfg values with the
// `trim` tag
func (cfg *Config) trimWhitespace() {
cfgElem := reflect.ValueOf(cfg).Elem()
cfgStructField := reflect.Indirect(reflect.ValueOf(cfg)).Type()
for i := 0; i < cfgElem.NumField(); i++ {
cfgField := cfgElem.Field(i)
if !cfgField.CanInterface() {
continue
}
trimTag := cfgStructField.Field(i).Tag.Get("trim")
if len(trimTag) == 0 {
continue
}
if cfgField.Kind() != reflect.String {
seelog.Warnf("Cannot trim non-string field type %v index %v", cfgField.Kind().String(), i)
continue
}
str := cfgField.Interface().(string)
cfgField.SetString(strings.TrimSpace(str))
}
}
func fileConfig() (Config, error) {
fileName := utils.DefaultIfBlank(os.Getenv("ECS_AGENT_CONFIG_FILE_PATH"), defaultConfigFileName)
cfg := Config{}
file, err := os.Open(fileName)
if err != nil {
return cfg, nil
}
data, err := ioutil.ReadAll(file)
if err != nil {
seelog.Errorf("Unable to read cfg file, err %v", err)
return cfg, err
}
if strings.TrimSpace(string(data)) == "" {
// empty file, not an error
return cfg, nil
}
err = json.Unmarshal(data, &cfg)
if err != nil {
seelog.Criticalf("Error reading cfg json data, err %v", err)
return cfg, err
}
// Handle any deprecated keys correctly here
if utils.ZeroOrNil(cfg.Cluster) && !utils.ZeroOrNil(cfg.ClusterArn) {
cfg.Cluster = cfg.ClusterArn
}
return cfg, nil
}
// environmentConfig reads the given configs from the environment and attempts
// to convert them to the given type
func environmentConfig() (Config, error) {
var errs []error
endpoint := os.Getenv("ECS_BACKEND_HOST")
clusterRef := os.Getenv("ECS_CLUSTER")
awsRegion := os.Getenv("AWS_DEFAULT_REGION")
dockerEndpoint := os.Getenv("DOCKER_HOST")
engineAuthType := os.Getenv("ECS_ENGINE_AUTH_TYPE")
engineAuthData := os.Getenv("ECS_ENGINE_AUTH_DATA")
var checkpoint bool
dataDir := os.Getenv("ECS_DATADIR")
if dataDir != "" {
// if we have a directory to checkpoint to, default it to be on
checkpoint = utils.ParseBool(os.Getenv("ECS_CHECKPOINT"), true)
} else {
// if the directory is not set, default to checkpointing off for
// backwards compatibility
checkpoint = utils.ParseBool(os.Getenv("ECS_CHECKPOINT"), false)
}
// Format: json array, e.g. [1,2,3]
reservedPortEnv := os.Getenv("ECS_RESERVED_PORTS")
portDecoder := json.NewDecoder(strings.NewReader(reservedPortEnv))
var reservedPorts []uint16
err := portDecoder.Decode(&reservedPorts)
// EOF means the string was blank as opposed to UnexepctedEof which means an
// invalid parse
// Blank is not a warning; we have sane defaults
if err != io.EOF && err != nil {
err := fmt.Errorf("Invalid format for \"ECS_RESERVED_PORTS\" environment variable; expected a JSON array like [1,2,3]. err %v", err)
seelog.Warn(err)
}
reservedPortUDPEnv := os.Getenv("ECS_RESERVED_PORTS_UDP")
portDecoderUDP := json.NewDecoder(strings.NewReader(reservedPortUDPEnv))
var reservedPortsUDP []uint16
err = portDecoderUDP.Decode(&reservedPortsUDP)
// EOF means the string was blank as opposed to UnexepctedEof which means an
// invalid parse
// Blank is not a warning; we have sane defaults
if err != io.EOF && err != nil {
err := fmt.Errorf("Invalid format for \"ECS_RESERVED_PORTS_UDP\" environment variable; expected a JSON array like [1,2,3]. err %v", err)
seelog.Warn(err)
}
updateDownloadDir := os.Getenv("ECS_UPDATE_DOWNLOAD_DIR")
updatesEnabled := utils.ParseBool(os.Getenv("ECS_UPDATES_ENABLED"), false)
disableMetrics := utils.ParseBool(os.Getenv("ECS_DISABLE_METRICS"), false)
reservedMemory := parseEnvVariableUint16("ECS_RESERVED_MEMORY")
var dockerStopTimeout time.Duration
parsedStopTimeout := parseEnvVariableDuration("ECS_CONTAINER_STOP_TIMEOUT")
if parsedStopTimeout >= minimumDockerStopTimeout {
dockerStopTimeout = parsedStopTimeout
} else if parsedStopTimeout != 0 {
seelog.Warnf("Discarded invalid value for docker stop timeout, parsed as: %v", parsedStopTimeout)
}
taskCleanupWaitDuration := parseEnvVariableDuration("ECS_ENGINE_TASK_CLEANUP_WAIT_DURATION")
availableLoggingDriversEnv := os.Getenv("ECS_AVAILABLE_LOGGING_DRIVERS")
loggingDriverDecoder := json.NewDecoder(strings.NewReader(availableLoggingDriversEnv))
var availableLoggingDrivers []dockerclient.LoggingDriver
err = loggingDriverDecoder.Decode(&availableLoggingDrivers)
// EOF means the string was blank as opposed to UnexpectedEof which means an
// invalid parse
// Blank is not a warning; we have sane defaults
if err != io.EOF && err != nil {
err := fmt.Errorf("Invalid format for \"ECS_AVAILABLE_LOGGING_DRIVERS\" environment variable; expected a JSON array like [\"json-file\",\"syslog\"]. err %v", err)
seelog.Warn(err)
}
privilegedDisabled := utils.ParseBool(os.Getenv("ECS_DISABLE_PRIVILEGED"), false)
seLinuxCapable := utils.ParseBool(os.Getenv("ECS_SELINUX_CAPABLE"), false)
appArmorCapable := utils.ParseBool(os.Getenv("ECS_APPARMOR_CAPABLE"), false)
taskENIEnabled := utils.ParseBool(os.Getenv("ECS_ENABLE_TASK_ENI"), false)
taskIAMRoleEnabled := utils.ParseBool(os.Getenv("ECS_ENABLE_TASK_IAM_ROLE"), false)
taskIAMRoleEnabledForNetworkHost := utils.ParseBool(os.Getenv("ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST"), false)
credentialsAuditLogFile := os.Getenv("ECS_AUDIT_LOGFILE")
credentialsAuditLogDisabled := utils.ParseBool(os.Getenv("ECS_AUDIT_LOGFILE_DISABLED"), false)
imageCleanupDisabled := utils.ParseBool(os.Getenv("ECS_DISABLE_IMAGE_CLEANUP"), false)
minimumImageDeletionAge := parseEnvVariableDuration("ECS_IMAGE_MINIMUM_CLEANUP_AGE")
imageCleanupInterval := parseEnvVariableDuration("ECS_IMAGE_CLEANUP_INTERVAL")
numImagesToDeletePerCycleEnvVal := os.Getenv("ECS_NUM_IMAGES_DELETE_PER_CYCLE")
numImagesToDeletePerCycle, err := strconv.Atoi(numImagesToDeletePerCycleEnvVal)
if numImagesToDeletePerCycleEnvVal != "" && err != nil {
seelog.Warnf("Invalid format for \"ECS_NUM_IMAGES_DELETE_PER_CYCLE\", expected an integer. err %v", err)
}
cniPluginsPath := os.Getenv("ECS_CNI_PLUGINS_PATH")
awsVPCBlockInstanceMetadata := utils.ParseBool(os.Getenv("ECS_AWSVPC_BLOCK_IMDS"), false)
var instanceAttributes map[string]string
instanceAttributesEnv := os.Getenv("ECS_INSTANCE_ATTRIBUTES")
err = json.Unmarshal([]byte(instanceAttributesEnv), &instanceAttributes)
if instanceAttributesEnv != "" {
if err != nil {
wrappedErr := fmt.Errorf("Invalid format for ECS_INSTANCE_ATTRIBUTES. Expected a json hash: %v", err)
seelog.Error(wrappedErr)
errs = append(errs, wrappedErr)
}
}
for attributeKey, attributeValue := range instanceAttributes {
seelog.Debugf("Setting instance attribute %v: %v", attributeKey, attributeValue)
}
var additionalLocalRoutes []cnitypes.IPNet
additionalLocalRoutesEnv := os.Getenv("ECS_AWSVPC_ADDITIONAL_LOCAL_ROUTES")
if additionalLocalRoutesEnv != "" {
err := json.Unmarshal([]byte(additionalLocalRoutesEnv), &additionalLocalRoutes)
if err != nil {
seelog.Errorf("Invalid format for ECS_AWSVPC_ADDITIONAL_LOCAL_ROUTES, expected a json array of CIDRs: %v", err)
errs = append(errs, err)
}
}
if len(errs) > 0 {
err = utils.NewMultiError(errs...)
} else {
err = nil
}
return Config{
Cluster: clusterRef,
APIEndpoint: endpoint,
AWSRegion: awsRegion,
DockerEndpoint: dockerEndpoint,
ReservedPorts: reservedPorts,
ReservedPortsUDP: reservedPortsUDP,
DataDir: dataDir,
Checkpoint: checkpoint,
EngineAuthType: engineAuthType,
EngineAuthData: NewSensitiveRawMessage([]byte(engineAuthData)),
UpdatesEnabled: updatesEnabled,
UpdateDownloadDir: updateDownloadDir,
DisableMetrics: disableMetrics,
ReservedMemory: reservedMemory,
AvailableLoggingDrivers: availableLoggingDrivers,
PrivilegedDisabled: privilegedDisabled,
SELinuxCapable: seLinuxCapable,
AppArmorCapable: appArmorCapable,
TaskCleanupWaitDuration: taskCleanupWaitDuration,
TaskENIEnabled: taskENIEnabled,
TaskIAMRoleEnabled: taskIAMRoleEnabled,
DockerStopTimeout: dockerStopTimeout,
CredentialsAuditLogFile: credentialsAuditLogFile,
CredentialsAuditLogDisabled: credentialsAuditLogDisabled,
TaskIAMRoleEnabledForNetworkHost: taskIAMRoleEnabledForNetworkHost,
ImageCleanupDisabled: imageCleanupDisabled,
MinimumImageDeletionAge: minimumImageDeletionAge,
ImageCleanupInterval: imageCleanupInterval,
NumImagesToDeletePerCycle: numImagesToDeletePerCycle,
InstanceAttributes: instanceAttributes,
CNIPluginsPath: cniPluginsPath,
AWSVPCBlockInstanceMetdata: awsVPCBlockInstanceMetadata,
AWSVPCAdditionalLocalRoutes: additionalLocalRoutes,
}, err
}
func parseEnvVariableUint16(envVar string) uint16 {
envVal := os.Getenv(envVar)
var var16 uint16
if envVal != "" {
var64, err := strconv.ParseUint(envVal, 10, 16)
if err != nil {
seelog.Warnf("Invalid format for \""+envVar+"\" environment variable; expected unsigned integer. err %v", err)
} else {
var16 = uint16(var64)
}
}
return var16
}
func parseEnvVariableDuration(envVar string) time.Duration {
var duration time.Duration
envVal := os.Getenv(envVar)
if envVal == "" {
seelog.Debugf("Environment variable empty: %v", envVar)
} else {
var err error
duration, err = time.ParseDuration(envVal)
if err != nil {
seelog.Warnf("Could not parse duration value: %v for Environment Variable %v : %v", envVal, envVar, err)
}
}
return duration
}
func ec2MetadataConfig(ec2client ec2.EC2MetadataClient) Config {
iid, err := ec2client.InstanceIdentityDocument()
if err != nil {
seelog.Criticalf("Unable to communicate with EC2 Metadata service to infer region: %v", err.Error())
return Config{}
}
return Config{AWSRegion: iid.Region}
}
// NewConfig returns a config struct created by merging environment variables,
// a config file, and EC2 Metadata info.
// The 'config' struct it returns can be used, even if an error is returned. An
// error is returned, however, if the config is incomplete in some way that is
// considered fatal.
func NewConfig(ec2client ec2.EC2MetadataClient) (config *Config, err error) {
var errs []error
var errTmp error
envConfig, errTmp := environmentConfig() //Environment overrides all else
if errTmp != nil {
errs = append(errs, errTmp)
}
config = &envConfig
defer func() {
config.trimWhitespace()
config.Merge(DefaultConfig())
errTmp = config.validateAndOverrideBounds()
if errTmp != nil {
errs = append(errs, errTmp)
}
if len(errs) != 0 {
err = utils.NewMultiError(errs...)
} else {
err = nil
}
}()
if config.complete() {
// No need to do file / network IO
return config, nil
}
fcfg, errTmp := fileConfig()
if errTmp != nil {
errs = append(errs, errTmp)
}
config.Merge(fcfg)
if config.AWSRegion == "" {
// Get it from metadata only if we need to (network io)
config.Merge(ec2MetadataConfig(ec2client))
}
return config, err
}
// validateAndOverrideBounds performs validation over members of the Config struct
// and check the value against the minimum required value.
func (cfg *Config) validateAndOverrideBounds() error {
err := cfg.checkMissingAndDepreciated()
if err != nil {
return err
}
if cfg.DockerStopTimeout < minimumDockerStopTimeout {
return fmt.Errorf("Invalid negative DockerStopTimeout: %v", cfg.DockerStopTimeout.String())
}
var badDrivers []string
for _, driver := range cfg.AvailableLoggingDrivers {
_, ok := dockerclient.LoggingDriverMinimumVersion[driver]
if !ok {
badDrivers = append(badDrivers, string(driver))
}
}
if len(badDrivers) > 0 {
return errors.New("Invalid logging drivers: " + strings.Join(badDrivers, ", "))
}
// If a value has been set for taskCleanupWaitDuration and the value is less than the minimum allowed cleanup duration,
// print a warning and override it
if cfg.TaskCleanupWaitDuration < minimumTaskCleanupWaitDuration {
seelog.Warnf("Invalid value for image cleanup duration, will be overridden with the default value: %s. Parsed value: %v, minimum value: %v.", DefaultTaskCleanupWaitDuration.String(), cfg.TaskCleanupWaitDuration, minimumTaskCleanupWaitDuration)
cfg.TaskCleanupWaitDuration = DefaultTaskCleanupWaitDuration
}
if cfg.ImageCleanupInterval < minimumImageCleanupInterval {
seelog.Warnf("Invalid value for image cleanup duration, will be overridden with the default value: %s. Parsed value: %v, minimum value: %v.", DefaultImageCleanupTimeInterval.String(), cfg.ImageCleanupInterval, minimumImageCleanupInterval)
cfg.ImageCleanupInterval = DefaultImageCleanupTimeInterval
}
if cfg.NumImagesToDeletePerCycle < minimumNumImagesToDeletePerCycle {
seelog.Warnf("Invalid value for number of images to delete for image cleanup, will be overriden with the default value: %d. Parsed value: %d, minimum value: %d.", DefaultImageDeletionAge, cfg.NumImagesToDeletePerCycle, minimumNumImagesToDeletePerCycle)
cfg.NumImagesToDeletePerCycle = DefaultNumImagesToDeletePerCycle
}
cfg.platformOverrides()
return nil
}
// String returns a lossy string representation of the config suitable for human readable display.
// Consequently, it *should not* return any sensitive information.
func (cfg *Config) String() string {
return fmt.Sprintf(
"Cluster: %v, "+
" Region: %v, "+
" DataDir: %v,"+
" Checkpoint: %v, "+
"AuthType: %v, "+
"UpdatesEnabled: %v, "+
"DisableMetrics: %v, "+
"ReservedMem: %v, "+
"TaskCleanupWaitDuration: %v, "+
"DockerStopTimeout: %v"+
"%s",
cfg.Cluster,
cfg.AWSRegion,
cfg.DataDir,
cfg.Checkpoint,
cfg.EngineAuthType,
cfg.UpdatesEnabled,
cfg.DisableMetrics,
cfg.ReservedMemory,
cfg.TaskCleanupWaitDuration,
cfg.DockerStopTimeout,
cfg.platformString(),
)
}
| 1 | 17,291 | What happens when ECS Init/whatever's starting the Agent mounts some other directory as Agent's data directory (`-v /tmp:/data`) sets `ECS_HOST_DATA_DIR` to `"/var/lib/ecs"` It doesn't seem like a strong enough abstraction to be dependent on Agent configuration options to expect `ECS_HOST_DATA_DIR` to be the same as whatever's being mounted as `/data` on the host. My main concern is the late-binding/asynchronous failures this could lead to if the wrong host mount was specified. Wondering if there are better alternatives here. Can we at the very least inspect the Agent container and check if `ECS_HOST_DATA_DIR` is mounted? If the answer is that we'll revisit the validation here at some latter stage, that's fine too. But, I want us to be aware of potential failures here. | aws-amazon-ecs-agent | go |
@@ -54,6 +54,11 @@ eprint_version(void)
#else
const char *has_dbus = "✘";
#endif
+#ifdef WITH_XCB_ERRORS
+ const char *has_xcb_errors = "✔";
+#else
+ const char *has_xcb_errors = "✘";
+#endif
#ifdef HAS_EXECINFO
const char *has_execinfo = "✔";
#else | 1 | /*
* version.c - version message utility functions
*
* Copyright © 2008 Julien Danjou <julien@danjou.info>
* Copyright © 2008 Hans Ulrich Niedermann <hun@n-dimensional.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "common/version.h"
#include "awesome-version-internal.h"
#include <stdlib.h>
#include <stdio.h>
#include <lualib.h>
#include <lauxlib.h>
#include <xcb/randr.h> /* for XCB_RANDR_GET_MONITORS */
/** \brief Print version message and quit program.
* \param executable program name
*/
void
eprint_version(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "_VERSION");
lua_getglobal(L, "jit");
if (lua_istable(L, 2))
lua_getfield(L, 2, "version");
else
lua_pop(L, 1);
/* Either push version number or error message onto stack */
(void) luaL_dostring(L, "return require('lgi.version')");
#ifdef WITH_DBUS
const char *has_dbus = "✔";
#else
const char *has_dbus = "✘";
#endif
#ifdef HAS_EXECINFO
const char *has_execinfo = "✔";
#else
const char *has_execinfo = "✘";
#endif
printf("awesome %s (%s)\n"
" • Compiled against %s (running with %s)\n"
" • D-Bus support: %s\n"
" • execinfo support: %s\n"
" • xcb-randr version: %d.%d\n"
" • LGI version: %s\n",
AWESOME_VERSION, AWESOME_RELEASE,
LUA_RELEASE, lua_tostring(L, -2),
has_dbus, has_execinfo,
XCB_RANDR_MAJOR_VERSION, XCB_RANDR_MINOR_VERSION,
lua_tostring(L, -1));
lua_close(L);
exit(EXIT_SUCCESS);
}
/** Get version string.
* \return A string describing the current version.
*/
const char *
awesome_version_string(void)
{
return AWESOME_VERSION;
}
/** Get release string.
* \return A string describing the code name of the relase.
*/
const char *
awesome_release_string(void)
{
return AWESOME_RELEASE;
}
// vim: filetype=c:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| 1 | 17,240 | btw that's obviously out of scope of this PR but since i noticed this line here it reminded me a thing: on some systems i've noticed the font didn't had those characters, so it was just a square or empty space and sometimes they're just a bit shifted in position (if font doesn't have them and using from fallback font which have incompatible dimensions of characters) how do you think is it worth creating an issue to discuss/address it or it could just waste time on bikeshedding? | awesomeWM-awesome | c |
@@ -21,6 +21,7 @@ import (
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/server/itx"
+ recoverutil "github.com/iotexproject/iotex-core/tools/util"
)
// recoveryHeight is the blockchain height being recovered to | 1 | // Copyright (c) 2019 IoTeX Foundation
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
// This is a recovery tool that recovers a corrupted or missing state database.
// To use, run "make recover"
package main
import (
"context"
"flag"
"fmt"
glog "log"
"os"
"go.uber.org/zap"
"github.com/iotexproject/iotex-core/blockchain/genesis"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/server/itx"
)
// recoveryHeight is the blockchain height being recovered to
var recoveryHeight int
func init() {
flag.IntVar(&recoveryHeight, "recovery-height", 0, "Recovery height")
flag.Usage = func() {
_, _ = fmt.Fprintf(os.Stderr,
"usage: recover -config-path=[string]\n -recovery-height=[int]\n")
flag.PrintDefaults()
os.Exit(2)
}
flag.Parse()
}
func main() {
genesisCfg, err := genesis.New()
if err != nil {
glog.Fatalln("Failed to new genesis config.", zap.Error(err))
}
cfg, err := config.New()
if err != nil {
glog.Fatalln("Failed to new config.", zap.Error(err))
}
cfg.Genesis = genesisCfg
log.S().Infof("Config in use: %+v", cfg)
// create server
svr, err := itx.NewServer(cfg)
if err != nil {
log.L().Fatal("Failed to create server.", zap.Error(err))
}
// recover chain and state
bc := svr.ChainService(cfg.Chain.ID).Blockchain()
if err := bc.Start(context.Background()); err == nil {
log.L().Info("State DB status is normal.")
}
defer func() {
if err := bc.Stop(context.Background()); err != nil {
log.L().Fatal("Failed to stop blockchain")
}
}()
if err := bc.RecoverChainAndState(uint64(recoveryHeight)); err != nil {
log.L().Fatal("Failed to recover chain and state.", zap.Error(err))
}
}
| 1 | 19,872 | alias is not needed | iotexproject-iotex-core | go |
@@ -19,7 +19,7 @@ DEFINE_int32(num_accept_threads, 1, "Number of threads to accept incoming connec
DEFINE_bool(reuse_port, true, "Whether to turn on the SO_REUSEPORT option");
DEFINE_int32(listen_backlog, 1024, "Backlog of the listen socket");
DEFINE_string(listen_netdev, "any", "The network device to listen on");
-DEFINE_string(pid_file, "nebula-graphd.pid", "File to hold the process id");
+DEFINE_string(pid_file, "pids/nebula-graphd.pid", "File to hold the process id");
DEFINE_bool(redirect_stdout, true, "Whether to redirect stdout and stderr to separate files");
DEFINE_string(stdout_log_file, "graphd-stdout.log", "Destination filename of stdout"); | 1 | /* Copyright (c) 2018 - present, VE Software Inc. All rights reserved
*
* This source code is licensed under Apache 2.0 License
* (found in the LICENSE.Apache file in the root directory)
*/
#include "base/Base.h"
#include "graph/GraphFlags.h"
DEFINE_int32(port, 34500, "Nebula Graph daemon's listen port");
DEFINE_int32(client_idle_timeout_secs, 0,
"Seconds before we close the idle connections, 0 for infinite");
DEFINE_int32(session_idle_timeout_secs, 600,
"Seconds before we expire the idle sessions, 0 for infinite");
DEFINE_int32(session_reclaim_interval_secs, 10, "Period we try to reclaim expired sessions");
DEFINE_int32(num_netio_threads, 0,
"Number of networking threads, 0 for number of physical CPU cores");
DEFINE_int32(num_accept_threads, 1, "Number of threads to accept incoming connections");
DEFINE_bool(reuse_port, true, "Whether to turn on the SO_REUSEPORT option");
DEFINE_int32(listen_backlog, 1024, "Backlog of the listen socket");
DEFINE_string(listen_netdev, "any", "The network device to listen on");
DEFINE_string(pid_file, "nebula-graphd.pid", "File to hold the process id");
DEFINE_bool(redirect_stdout, true, "Whether to redirect stdout and stderr to separate files");
DEFINE_string(stdout_log_file, "graphd-stdout.log", "Destination filename of stdout");
DEFINE_string(stderr_log_file, "graphd-stderr.log", "Destination filename of stderr");
DEFINE_bool(daemonize, true, "Whether run as a daemon process");
| 1 | 16,425 | Do we need to include the path? | vesoft-inc-nebula | cpp |
@@ -1254,8 +1254,8 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment) {
const (
compactInterval = 2 * time.Minute
- compactSizeMin = 32 * 1024 * 1024
- compactNumMin = 4
+ compactSizeMin = 64 * 1024 * 1024
+ compactNumMin = 8192
)
t := time.NewTicker(compactInterval) | 1 | // Copyright 2020-2021 The NATS 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.
package server
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math/rand"
"path"
"reflect"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/klauspost/compress/s2"
"github.com/nats-io/nuid"
)
// jetStreamCluster holds information about the meta group and stream assignments.
type jetStreamCluster struct {
// The metacontroller raftNode.
meta RaftNode
// For stream and consumer assignments. All servers will have this be the same.
// ACC -> STREAM -> Stream Assignment -> Consumers
streams map[string]map[string]*streamAssignment
// Server.
s *Server
// Internal client.
c *client
// Processing assignment results.
streamResults *subscription
consumerResults *subscription
// System level request to have the leader stepdown.
stepdown *subscription
// System level requests to remove a peer.
peerRemove *subscription
}
// Used to guide placement of streams and meta controllers in clustered JetStream.
type Placement struct {
Cluster string `json:"cluster"`
Tags []string `json:"tags,omitempty"`
}
// Define types of the entry.
type entryOp uint8
const (
// Meta ops.
assignStreamOp entryOp = iota
assignConsumerOp
removeStreamOp
removeConsumerOp
// Stream ops.
streamMsgOp
purgeStreamOp
deleteMsgOp
// Consumer ops
updateDeliveredOp
updateAcksOp
// Compressed consumer assignments.
assignCompressedConsumerOp
// Filtered Consumer skip.
updateSkipOp
// Update Stream
updateStreamOp
)
// raftGroups are controlled by the metagroup controller.
// The raftGroups will house streams and consumers.
type raftGroup struct {
Name string `json:"name"`
Peers []string `json:"peers"`
Storage StorageType `json:"store"`
Preferred string `json:"preferred,omitempty"`
// Internal
node RaftNode
}
// streamAssignment is what the meta controller uses to assign streams to peers.
type streamAssignment struct {
Client *ClientInfo `json:"client,omitempty"`
Created time.Time `json:"created"`
Config *StreamConfig `json:"stream"`
Group *raftGroup `json:"group"`
Sync string `json:"sync"`
Subject string `json:"subject"`
Reply string `json:"reply"`
Restore *StreamState `json:"restore_state,omitempty"`
// Internal
consumers map[string]*consumerAssignment
responded bool
err error
}
// consumerAssignment is what the meta controller uses to assign consumers to streams.
type consumerAssignment struct {
Client *ClientInfo `json:"client,omitempty"`
Created time.Time `json:"created"`
Name string `json:"name"`
Stream string `json:"stream"`
Config *ConsumerConfig `json:"consumer"`
Group *raftGroup `json:"group"`
Subject string `json:"subject"`
Reply string `json:"reply"`
State *ConsumerState `json:"state,omitempty"`
// Internal
responded bool
deleted bool
err error
}
// streamPurge is what the stream leader will replicate when purging a stream.
type streamPurge struct {
Client *ClientInfo `json:"client,omitempty"`
Stream string `json:"stream"`
LastSeq uint64 `json:"last_seq"`
Subject string `json:"subject"`
Reply string `json:"reply"`
}
// streamMsgDelete is what the stream leader will replicate when deleting a message.
type streamMsgDelete struct {
Client *ClientInfo `json:"client,omitempty"`
Stream string `json:"stream"`
Seq uint64 `json:"seq"`
NoErase bool `json:"no_erase,omitempty"`
Subject string `json:"subject"`
Reply string `json:"reply"`
}
const (
defaultStoreDirName = "_js_"
defaultMetaGroupName = "_meta_"
defaultMetaFSBlkSize = 1024 * 1024
)
// For validating clusters.
func validateJetStreamOptions(o *Options) error {
// If not clustered no checks.
if !o.JetStream || o.Cluster.Port == 0 {
return nil
}
if o.ServerName == _EMPTY_ {
return fmt.Errorf("jetstream cluster requires `server_name` to be set")
}
if o.Cluster.Name == _EMPTY_ {
return fmt.Errorf("jetstream cluster requires `cluster.name` to be set")
}
return nil
}
func (s *Server) getJetStreamCluster() (*jetStream, *jetStreamCluster) {
s.mu.Lock()
shutdown := s.shutdown
js := s.js
s.mu.Unlock()
if shutdown || js == nil {
return nil, nil
}
js.mu.RLock()
cc := js.cluster
js.mu.RUnlock()
if cc == nil {
return nil, nil
}
return js, cc
}
func (s *Server) JetStreamIsClustered() bool {
js := s.getJetStream()
if js == nil {
return false
}
js.mu.RLock()
isClustered := js.cluster != nil
js.mu.RUnlock()
return isClustered
}
func (s *Server) JetStreamIsLeader() bool {
js := s.getJetStream()
if js == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isLeader()
}
func (s *Server) JetStreamIsCurrent() bool {
js := s.getJetStream()
if js == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isCurrent()
}
func (s *Server) JetStreamSnapshotMeta() error {
js := s.getJetStream()
if js == nil {
return ErrJetStreamNotEnabled
}
js.mu.RLock()
defer js.mu.RUnlock()
cc := js.cluster
if !cc.isLeader() {
return errNotLeader
}
return cc.meta.InstallSnapshot(js.metaSnapshot())
}
func (s *Server) JetStreamStepdownStream(account, stream string) error {
js, cc := s.getJetStreamCluster()
if js == nil {
return ErrJetStreamNotEnabled
}
if cc == nil {
return ErrJetStreamNotClustered
}
// Grab account
acc, err := s.LookupAccount(account)
if err != nil {
return err
}
// Grab stream
mset, err := acc.lookupStream(stream)
if err != nil {
return err
}
if node := mset.raftNode(); node != nil && node.Leader() {
node.StepDown()
}
return nil
}
func (s *Server) JetStreamSnapshotStream(account, stream string) error {
js, cc := s.getJetStreamCluster()
if js == nil {
return ErrJetStreamNotEnabled
}
if cc == nil {
return ErrJetStreamNotClustered
}
// Grab account
acc, err := s.LookupAccount(account)
if err != nil {
return err
}
// Grab stream
mset, err := acc.lookupStream(stream)
if err != nil {
return err
}
mset.mu.RLock()
if !mset.node.Leader() {
mset.mu.RUnlock()
return ErrJetStreamNotLeader
}
n := mset.node
mset.mu.RUnlock()
return n.InstallSnapshot(mset.stateSnapshot())
}
func (s *Server) JetStreamClusterPeers() []string {
js := s.getJetStream()
if js == nil {
return nil
}
js.mu.RLock()
defer js.mu.RUnlock()
cc := js.cluster
if !cc.isLeader() {
return nil
}
peers := cc.meta.Peers()
var nodes []string
for _, p := range peers {
si, ok := s.nodeToInfo.Load(p.ID)
if !ok || si.(nodeInfo).offline {
continue
}
nodes = append(nodes, si.(nodeInfo).name)
}
return nodes
}
// Read lock should be held.
func (cc *jetStreamCluster) isLeader() bool {
if cc == nil {
// Non-clustered mode
return true
}
return cc.meta.Leader()
}
// isCurrent will determine if this node is a leader or an up to date follower.
// Read lock should be held.
func (cc *jetStreamCluster) isCurrent() bool {
if cc == nil {
// Non-clustered mode
return true
}
if cc.meta == nil {
return false
}
return cc.meta.Current()
}
// isStreamCurrent will determine if this node is a participant for the stream and if its up to date.
// Read lock should be held.
func (cc *jetStreamCluster) isStreamCurrent(account, stream string) bool {
if cc == nil {
// Non-clustered mode
return true
}
as := cc.streams[account]
if as == nil {
return false
}
sa := as[stream]
if sa == nil {
return false
}
rg := sa.Group
if rg == nil || rg.node == nil {
return false
}
isCurrent := rg.node.Current()
if isCurrent {
// Check if we are processing a snapshot and are catching up.
acc, err := cc.s.LookupAccount(account)
if err != nil {
return false
}
mset, err := acc.lookupStream(stream)
if err != nil {
return false
}
if mset.isCatchingUp() {
return false
}
}
return isCurrent
}
func (a *Account) getJetStreamFromAccount() (*Server, *jetStream, *jsAccount) {
a.mu.RLock()
jsa := a.js
a.mu.RUnlock()
if jsa == nil {
return nil, nil, nil
}
jsa.mu.RLock()
js := jsa.js
jsa.mu.RUnlock()
if js == nil {
return nil, nil, nil
}
js.mu.RLock()
s := js.srv
js.mu.RUnlock()
return s, js, jsa
}
func (s *Server) JetStreamIsStreamLeader(account, stream string) bool {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return cc.isStreamLeader(account, stream)
}
func (a *Account) JetStreamIsStreamLeader(stream string) bool {
s, js, jsa := a.getJetStreamFromAccount()
if s == nil || js == nil || jsa == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isStreamLeader(a.Name, stream)
}
func (s *Server) JetStreamIsStreamCurrent(account, stream string) bool {
js, cc := s.getJetStreamCluster()
if js == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return cc.isStreamCurrent(account, stream)
}
func (a *Account) JetStreamIsConsumerLeader(stream, consumer string) bool {
s, js, jsa := a.getJetStreamFromAccount()
if s == nil || js == nil || jsa == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isConsumerLeader(a.Name, stream, consumer)
}
func (s *Server) JetStreamIsConsumerLeader(account, stream, consumer string) bool {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return cc.isConsumerLeader(account, stream, consumer)
}
func (s *Server) enableJetStreamClustering() error {
if !s.isRunning() {
return nil
}
js := s.getJetStream()
if js == nil {
return ErrJetStreamNotEnabled
}
// Already set.
if js.cluster != nil {
return nil
}
s.Noticef("Starting JetStream cluster")
// We need to determine if we have a stable cluster name and expected number of servers.
s.Debugf("JetStream cluster checking for stable cluster name and peers")
if s.isClusterNameDynamic() || s.configuredRoutes() == 0 {
return errors.New("JetStream cluster requires cluster name and explicit routes")
}
return js.setupMetaGroup()
}
func (js *jetStream) setupMetaGroup() error {
s := js.srv
s.Noticef("Creating JetStream metadata controller")
// Setup our WAL for the metagroup.
sysAcc := s.SystemAccount()
storeDir := path.Join(js.config.StoreDir, sysAcc.Name, defaultStoreDirName, defaultMetaGroupName)
fs, err := newFileStore(
FileStoreConfig{StoreDir: storeDir, BlockSize: defaultMetaFSBlkSize, AsyncFlush: false},
StreamConfig{Name: defaultMetaGroupName, Storage: FileStorage},
)
if err != nil {
s.Errorf("Error creating filestore: %v", err)
return err
}
cfg := &RaftConfig{Name: defaultMetaGroupName, Store: storeDir, Log: fs}
var bootstrap bool
if _, err := readPeerState(storeDir); err != nil {
s.Noticef("JetStream cluster bootstrapping")
bootstrap = true
peers := s.ActivePeers()
s.Debugf("JetStream cluster initial peers: %+v", peers)
if err := s.bootstrapRaftNode(cfg, peers, false); err != nil {
return err
}
} else {
s.Noticef("JetStream cluster recovering state")
}
// Start up our meta node.
n, err := s.startRaftNode(cfg)
if err != nil {
s.Warnf("Could not start metadata controller: %v", err)
return err
}
// If we are bootstrapped with no state, start campaign early.
if bootstrap {
n.Campaign()
}
c := s.createInternalJetStreamClient()
sacc := s.SystemAccount()
js.mu.Lock()
defer js.mu.Unlock()
js.cluster = &jetStreamCluster{
meta: n,
streams: make(map[string]map[string]*streamAssignment),
s: s,
c: c,
}
c.registerWithAccount(sacc)
js.srv.startGoRoutine(js.monitorCluster)
return nil
}
func (js *jetStream) getMetaGroup() RaftNode {
js.mu.RLock()
defer js.mu.RUnlock()
if js.cluster == nil {
return nil
}
return js.cluster.meta
}
func (js *jetStream) server() *Server {
js.mu.RLock()
s := js.srv
js.mu.RUnlock()
return s
}
// Will respond if we do not think we have a metacontroller leader.
func (js *jetStream) isLeaderless() bool {
js.mu.RLock()
defer js.mu.RUnlock()
cc := js.cluster
if cc == nil {
return false
}
// If we don't have a leader.
if cc.meta.GroupLeader() == _EMPTY_ {
// Make sure we have been running for enough time.
if time.Since(cc.meta.Created()) > lostQuorumInterval {
return true
}
}
return false
}
// Will respond iff we are a member and we know we have no leader.
func (js *jetStream) isGroupLeaderless(rg *raftGroup) bool {
if rg == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
cc := js.cluster
// If we are not a member we can not say..
if !rg.isMember(cc.meta.ID()) {
return false
}
// Single peer groups always have a leader if we are here.
if rg.node == nil {
return false
}
// If we don't have a leader.
if rg.node.GroupLeader() == _EMPTY_ {
// Make sure we have been running for enough time.
if time.Since(rg.node.Created()) > lostQuorumInterval {
return true
}
}
return false
}
func (s *Server) JetStreamIsStreamAssigned(account, stream string) bool {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return false
}
acc, _ := s.LookupAccount(account)
if acc == nil {
return false
}
return cc.isStreamAssigned(acc, stream)
}
// streamAssigned informs us if this server has this stream assigned.
func (jsa *jsAccount) streamAssigned(stream string) bool {
jsa.mu.RLock()
js, acc := jsa.js, jsa.account
jsa.mu.RUnlock()
if js == nil {
return false
}
js.mu.RLock()
assigned := js.cluster.isStreamAssigned(acc, stream)
js.mu.RUnlock()
return assigned
}
// Read lock should be held.
func (cc *jetStreamCluster) isStreamAssigned(a *Account, stream string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
as := cc.streams[a.Name]
if as == nil {
return false
}
sa := as[stream]
if sa == nil {
return false
}
rg := sa.Group
if rg == nil {
return false
}
// Check if we are the leader of this raftGroup assigned to the stream.
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
return true
}
}
return false
}
// Read lock should be held.
func (cc *jetStreamCluster) isStreamLeader(account, stream string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
if cc.meta == nil {
return false
}
var sa *streamAssignment
if as := cc.streams[account]; as != nil {
sa = as[stream]
}
if sa == nil {
return false
}
rg := sa.Group
if rg == nil {
return false
}
// Check if we are the leader of this raftGroup assigned to the stream.
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
if len(rg.Peers) == 1 || rg.node != nil && rg.node.Leader() {
return true
}
}
}
return false
}
// Read lock should be held.
func (cc *jetStreamCluster) isConsumerLeader(account, stream, consumer string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
if cc.meta == nil {
return false
}
var sa *streamAssignment
if as := cc.streams[account]; as != nil {
sa = as[stream]
}
if sa == nil {
return false
}
// Check if we are the leader of this raftGroup assigned to this consumer.
ca := sa.consumers[consumer]
if ca == nil {
return false
}
rg := ca.Group
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
if len(rg.Peers) == 1 || (rg.node != nil && rg.node.Leader()) {
return true
}
}
}
return false
}
func (js *jetStream) monitorCluster() {
s, n := js.server(), js.getMetaGroup()
qch, lch, ach := n.QuitC(), n.LeadChangeC(), n.ApplyC()
defer s.grWG.Done()
s.Debugf("Starting metadata monitor")
defer s.Debugf("Exiting metadata monitor")
const compactInterval = 2 * time.Minute
t := time.NewTicker(compactInterval)
defer t.Stop()
var (
isLeader bool
lastSnap []byte
lastSnapTime time.Time
)
doSnapshot := func() {
if snap := js.metaSnapshot(); !bytes.Equal(lastSnap, snap) {
if err := n.InstallSnapshot(snap); err == nil {
lastSnap = snap
lastSnapTime = time.Now()
}
}
}
isRecovering := true
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case ce := <-ach:
if ce == nil {
// Signals we have replayed all of our metadata.
isRecovering = false
s.Debugf("Recovered JetStream cluster metadata")
continue
}
// FIXME(dlc) - Deal with errors.
if _, didRemoval, err := js.applyMetaEntries(ce.Entries, isRecovering); err == nil {
n.Applied(ce.Index)
if js.hasPeerEntries(ce.Entries) || (didRemoval && time.Since(lastSnapTime) > 2*time.Second) {
// Since we received one make sure we have our own since we do not store
// our meta state outside of raft.
doSnapshot()
} else if _, b := n.Size(); b > uint64(len(lastSnap)*4) {
doSnapshot()
}
}
case isLeader = <-lch:
js.processLeaderChange(isLeader)
case <-t.C:
doSnapshot()
}
}
}
// Represents our stable meta state that we can write out.
type writeableStreamAssignment struct {
Client *ClientInfo `json:"client,omitempty"`
Created time.Time `json:"created"`
Config *StreamConfig `json:"stream"`
Group *raftGroup `json:"group"`
Sync string `json:"sync"`
Consumers []*consumerAssignment
}
func (js *jetStream) metaSnapshot() []byte {
var streams []writeableStreamAssignment
js.mu.RLock()
cc := js.cluster
for _, asa := range cc.streams {
for _, sa := range asa {
wsa := writeableStreamAssignment{
Client: sa.Client,
Created: sa.Created,
Config: sa.Config,
Group: sa.Group,
Sync: sa.Sync,
}
for _, ca := range sa.consumers {
wsa.Consumers = append(wsa.Consumers, ca)
}
streams = append(streams, wsa)
}
}
if len(streams) == 0 {
js.mu.RUnlock()
return nil
}
b, _ := json.Marshal(streams)
js.mu.RUnlock()
return s2.EncodeBetter(nil, b)
}
func (js *jetStream) applyMetaSnapshot(buf []byte, isRecovering bool) error {
if len(buf) == 0 {
return nil
}
jse, err := s2.Decode(nil, buf)
if err != nil {
return err
}
var wsas []writeableStreamAssignment
if err = json.Unmarshal(jse, &wsas); err != nil {
return err
}
// Build our new version here outside of js.
streams := make(map[string]map[string]*streamAssignment)
for _, wsa := range wsas {
as := streams[wsa.Client.serviceAccount()]
if as == nil {
as = make(map[string]*streamAssignment)
streams[wsa.Client.serviceAccount()] = as
}
sa := &streamAssignment{Client: wsa.Client, Created: wsa.Created, Config: wsa.Config, Group: wsa.Group, Sync: wsa.Sync}
if len(wsa.Consumers) > 0 {
sa.consumers = make(map[string]*consumerAssignment)
for _, ca := range wsa.Consumers {
sa.consumers[ca.Name] = ca
}
}
as[wsa.Config.Name] = sa
}
js.mu.Lock()
cc := js.cluster
var saAdd, saDel, saChk []*streamAssignment
// Walk through the old list to generate the delete list.
for account, asa := range cc.streams {
nasa := streams[account]
for sn, sa := range asa {
if nsa := nasa[sn]; nsa == nil {
saDel = append(saDel, sa)
} else {
saChk = append(saChk, nsa)
}
}
}
// Walk through the new list to generate the add list.
for account, nasa := range streams {
asa := cc.streams[account]
for sn, sa := range nasa {
if asa[sn] == nil {
saAdd = append(saAdd, sa)
}
}
}
// Now walk the ones to check and process consumers.
var caAdd, caDel []*consumerAssignment
for _, sa := range saChk {
if osa := js.streamAssignment(sa.Client.serviceAccount(), sa.Config.Name); osa != nil {
for _, ca := range osa.consumers {
if sa.consumers[ca.Name] == nil {
caDel = append(caDel, ca)
} else {
caAdd = append(caAdd, ca)
}
}
}
}
js.mu.Unlock()
// Do removals first.
for _, sa := range saDel {
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamRemoval(sa)
}
// Now do add for the streams. Also add in all consumers.
for _, sa := range saAdd {
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamAssignment(sa)
// We can simply add the consumers.
for _, ca := range sa.consumers {
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
}
}
// Now do the deltas for existing stream's consumers.
for _, ca := range caDel {
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerRemoval(ca)
}
for _, ca := range caAdd {
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
}
return nil
}
// Called on recovery to make sure we do not process like original.
func (js *jetStream) setStreamAssignmentRecovering(sa *streamAssignment) {
js.mu.Lock()
defer js.mu.Unlock()
sa.responded = true
sa.Restore = nil
if sa.Group != nil {
sa.Group.Preferred = _EMPTY_
}
}
// Called on recovery to make sure we do not process like original.
func (js *jetStream) setConsumerAssignmentRecovering(ca *consumerAssignment) {
js.mu.Lock()
defer js.mu.Unlock()
ca.responded = true
if ca.Group != nil {
ca.Group.Preferred = _EMPTY_
}
}
// Just copied over and changes out the group so it can be encoded.
// Lock should be held.
func (sa *streamAssignment) copyGroup() *streamAssignment {
csa, cg := *sa, *sa.Group
csa.Group = &cg
csa.Group.Peers = append(sa.Group.Peers[:0:0], sa.Group.Peers...)
return &csa
}
func (js *jetStream) remapStreams(peer string) {
js.mu.Lock()
defer js.mu.Unlock()
js.remapStreamsLocked(peer)
}
// Lock should be held.
func (js *jetStream) remapStreamsLocked(peer string) {
cc := js.cluster
// Grab our nodes.
// Need to search for this peer in our stream assignments for potential remapping.
for _, as := range cc.streams {
for _, sa := range as {
if sa.Group.isMember(peer) {
js.removePeerFromStream(sa, peer)
}
}
}
}
func (js *jetStream) processRemovePeer(peer string) {
js.mu.Lock()
s, cc := js.srv, js.cluster
// Only leader will do remappings for streams and consumers.
if cc.isLeader() {
js.remapStreamsLocked(peer)
}
// All nodes will check if this is them.
isUs := cc.meta.ID() == peer
disabled := js.disabled
js.mu.Unlock()
// We may be already disabled.
if disabled {
return
}
if isUs {
s.Errorf("JetStream being DISABLED, our server was removed from the cluster")
adv := &JSServerRemovedAdvisory{
TypedEvent: TypedEvent{
Type: JSServerRemovedAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Server: s.Name(),
ServerID: s.ID(),
Cluster: s.cachedClusterName(),
}
s.publishAdvisory(nil, JSAdvisoryServerRemoved, adv)
go s.DisableJetStream()
}
}
// Assumes all checks have already been done.
// Lock should be held.
func (js *jetStream) removePeerFromStream(sa *streamAssignment, peer string) {
s, cc := js.srv, js.cluster
csa := sa.copyGroup()
if !cc.remapStreamAssignment(csa, peer) {
s.Warnf("JetStream cluster could not remap stream '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
}
// Send our proposal for this csa. Also use same group definition for all the consumers as well.
cc.meta.Propose(encodeAddStreamAssignment(csa))
rg := csa.Group
for _, ca := range sa.consumers {
cca := *ca
cca.Group.Peers = rg.Peers
cc.meta.Propose(encodeAddConsumerAssignment(&cca))
}
}
// Check if we have peer related entries.
func (js *jetStream) hasPeerEntries(entries []*Entry) bool {
for _, e := range entries {
if e.Type == EntryRemovePeer || e.Type == EntryAddPeer {
return true
}
}
return false
}
func (js *jetStream) applyMetaEntries(entries []*Entry, isRecovering bool) (bool, bool, error) {
var didSnap, didRemove bool
for _, e := range entries {
if e.Type == EntrySnapshot {
js.applyMetaSnapshot(e.Data, isRecovering)
didSnap = true
} else if e.Type == EntryRemovePeer {
if !isRecovering {
js.processRemovePeer(string(e.Data))
}
} else {
buf := e.Data
switch entryOp(buf[0]) {
case assignStreamOp:
sa, err := decodeStreamAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamAssignment(sa)
case removeStreamOp:
sa, err := decodeStreamAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamRemoval(sa)
didRemove = true
case assignConsumerOp:
ca, err := decodeConsumerAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode consumer assigment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
case assignCompressedConsumerOp:
ca, err := decodeConsumerAssignmentCompressed(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode compressed consumer assigment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
case removeConsumerOp:
ca, err := decodeConsumerAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode consumer assigment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerRemoval(ca)
didRemove = true
case updateStreamOp:
sa, err := decodeStreamAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processUpdateStreamAssignment(sa)
default:
panic("JetStream Cluster Unknown meta entry op type")
}
}
}
return didSnap, didRemove, nil
}
func (rg *raftGroup) isMember(id string) bool {
if rg == nil {
return false
}
for _, peer := range rg.Peers {
if peer == id {
return true
}
}
return false
}
func (rg *raftGroup) setPreferred() {
if rg == nil || len(rg.Peers) == 0 {
return
}
if len(rg.Peers) == 1 {
rg.Preferred = rg.Peers[0]
} else {
// For now just randomly select a peer for the preferred.
pi := rand.Int31n(int32(len(rg.Peers)))
rg.Preferred = rg.Peers[pi]
}
}
// createRaftGroup is called to spin up this raft group if needed.
func (js *jetStream) createRaftGroup(rg *raftGroup, storage StorageType) error {
js.mu.Lock()
defer js.mu.Unlock()
s, cc := js.srv, js.cluster
// If this is a single peer raft group or we are not a member return.
if len(rg.Peers) <= 1 || !rg.isMember(cc.meta.ID()) {
// Nothing to do here.
return nil
}
// We already have this assigned.
if node := s.lookupRaftNode(rg.Name); node != nil {
s.Debugf("JetStream cluster already has raft group %q assigned", rg.Name)
rg.node = node
return nil
}
s.Debugf("JetStream cluster creating raft group:%+v", rg)
sysAcc := s.SystemAccount()
if sysAcc == nil {
s.Debugf("JetStream cluster detected shutdown processing raft group: %+v", rg)
return errors.New("shutting down")
}
storeDir := path.Join(js.config.StoreDir, sysAcc.Name, defaultStoreDirName, rg.Name)
var store StreamStore
if storage == FileStorage {
fs, err := newFileStore(
FileStoreConfig{StoreDir: storeDir, BlockSize: 4_000_000, AsyncFlush: false, SyncInterval: 5 * time.Minute},
StreamConfig{Name: rg.Name, Storage: FileStorage},
)
if err != nil {
s.Errorf("Error creating filestore WAL: %v", err)
return err
}
store = fs
} else {
ms, err := newMemStore(&StreamConfig{Name: rg.Name, Storage: MemoryStorage})
if err != nil {
s.Errorf("Error creating memstore WAL: %v", err)
return err
}
store = ms
}
cfg := &RaftConfig{Name: rg.Name, Store: storeDir, Log: store}
if _, err := readPeerState(storeDir); err != nil {
s.bootstrapRaftNode(cfg, rg.Peers, true)
}
n, err := s.startRaftNode(cfg)
if err != nil {
s.Debugf("Error creating raft group: %v", err)
return err
}
rg.node = n
// See if we are preferred and should start campaign immediately.
if n.ID() == rg.Preferred {
n.Campaign()
}
return nil
}
func (mset *stream) raftGroup() *raftGroup {
if mset == nil {
return nil
}
mset.mu.RLock()
defer mset.mu.RUnlock()
if mset.sa == nil {
return nil
}
return mset.sa.Group
}
func (mset *stream) raftNode() RaftNode {
if mset == nil {
return nil
}
mset.mu.RLock()
defer mset.mu.RUnlock()
return mset.node
}
// Monitor our stream node for this stream.
func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment) {
s, cc, n := js.server(), js.cluster, sa.Group.node
defer s.grWG.Done()
if n == nil {
s.Warnf("No RAFT group for '%s > %s", sa.Client.serviceAccount(), sa.Config.Name)
return
}
qch, lch, ach := n.QuitC(), n.LeadChangeC(), n.ApplyC()
s.Debugf("Starting stream monitor for '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
defer s.Debugf("Exiting stream monitor for '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
const (
compactInterval = 2 * time.Minute
compactSizeMin = 32 * 1024 * 1024
compactNumMin = 4
)
t := time.NewTicker(compactInterval)
defer t.Stop()
js.mu.RLock()
isLeader := cc.isStreamLeader(sa.Client.serviceAccount(), sa.Config.Name)
isRestore := sa.Restore != nil
js.mu.RUnlock()
acc, err := s.LookupAccount(sa.Client.serviceAccount())
if err != nil {
s.Warnf("Could not retrieve account for stream '%s > %s", sa.Client.serviceAccount(), sa.Config.Name)
return
}
var lastSnap []byte
var lastApplied uint64
// Should only to be called from leader.
doSnapshot := func() {
if mset == nil || isRestore {
return
}
if snap := mset.stateSnapshot(); !bytes.Equal(lastSnap, snap) {
if err := n.InstallSnapshot(snap); err == nil {
lastSnap = snap
_, _, lastApplied = n.Progress()
}
}
}
// Check on startup if we should compact.
if _, b := n.Size(); b > compactSizeMin {
doSnapshot()
}
// We will establish a restoreDoneCh no matter what. Will never be triggered unless
// we replace with the restore chan.
restoreDoneCh := make(<-chan error)
isRecovering := true
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case ce := <-ach:
// No special processing needed for when we are caught up on restart.
if ce == nil {
isRecovering = false
continue
}
// Apply our entries.
//TODO mset may be nil see doSnapshot(). applyStreamEntries is sensitive to this
if err := js.applyStreamEntries(mset, ce, isRecovering); err == nil {
n.Applied(ce.Index)
ne := ce.Index - lastApplied
// If over our compact min and we have at least min entries to compact, go ahead and snapshot/compact.
if _, b := n.Size(); b > compactSizeMin && ne >= compactNumMin {
doSnapshot()
}
} else {
s.Warnf("Error applying entries to '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
}
case isLeader = <-lch:
if isLeader {
if isRestore {
acc, _ := s.LookupAccount(sa.Client.serviceAccount())
restoreDoneCh = s.processStreamRestore(sa.Client, acc, sa.Config, _EMPTY_, sa.Reply, _EMPTY_)
continue
} else {
doSnapshot()
}
} else if n.GroupLeader() != noLeader {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamLeaderChange(mset, isLeader)
case <-t.C:
doSnapshot()
case err := <-restoreDoneCh:
// We have completed a restore from snapshot on this server. The stream assignment has
// already been assigned but the replicas will need to catch up out of band. Consumers
// will need to be assigned by forwarding the proposal and stamping the initial state.
s.Debugf("Stream restore for '%s > %s' completed", sa.Client.serviceAccount(), sa.Config.Name)
if err != nil {
s.Debugf("Stream restore failed: %v", err)
}
isRestore = false
sa.Restore = nil
// If we were successful lookup up our stream now.
if err == nil {
mset, err = acc.lookupStream(sa.Config.Name)
if mset != nil {
mset.setStreamAssignment(sa)
}
}
if err != nil {
if mset != nil {
mset.delete()
}
js.mu.Lock()
sa.err = err
if n != nil {
n.Delete()
}
result := &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Restore: &JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}},
}
result.Restore.Error = jsError(sa.err)
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, b)
return
}
if !isLeader {
panic("Finished restore but not leader")
}
// Trigger the stream followers to catchup.
if n := mset.raftNode(); n != nil {
n.SendSnapshot(mset.stateSnapshot())
}
js.processStreamLeaderChange(mset, isLeader)
// Check to see if we have restored consumers here.
// These are not currently assigned so we will need to do so here.
if consumers := mset.getConsumers(); len(consumers) > 0 {
for _, o := range mset.getConsumers() {
rg := cc.createGroupForConsumer(sa)
// Pick a preferred leader.
rg.setPreferred()
name, cfg := o.String(), o.config()
// Place our initial state here as well for assignment distribution.
ca := &consumerAssignment{
Group: rg,
Stream: sa.Config.Name,
Name: name,
Config: &cfg,
Client: sa.Client,
Created: o.createdTime(),
State: o.readStoreState(),
}
// We make these compressed in case state is complex.
addEntry := encodeAddConsumerAssignmentCompressed(ca)
cc.meta.ForwardProposal(addEntry)
// Check to make sure we see the assignment.
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
js.mu.RLock()
ca, meta := js.consumerAssignment(ca.Client.serviceAccount(), sa.Config.Name, name), cc.meta
js.mu.RUnlock()
if ca == nil {
s.Warnf("Consumer assignment has not been assigned, retrying")
if meta != nil {
meta.ForwardProposal(addEntry)
} else {
return
}
} else {
return
}
}
}()
}
}
}
}
}
func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isRecovering bool) error {
for _, e := range ce.Entries {
if e.Type == EntryNormal {
buf := e.Data
switch entryOp(buf[0]) {
case streamMsgOp:
subject, reply, hdr, msg, lseq, ts, err := decodeStreamMsg(buf[1:])
if err != nil {
panic(err.Error())
}
// We can skip if we know this is less than what we already have.
if isRecovering && lseq <= mset.lastSeq() {
continue
}
// Skip by hand here since first msg special case.
// Reason is sequence is unsigned and for lseq being 0
// the lseq under stream would have be -1.
if lseq == 0 && mset.lastSeq() != 0 {
continue
}
s := js.srv
if err := mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts); err != nil {
if err != errLastSeqMismatch || !isRecovering {
s.Debugf("Got error processing JetStream msg: %v", err)
}
if isOutOfSpaceErr(err) {
s.handleOutOfSpace(mset.name())
return err
}
}
case deleteMsgOp:
md, err := decodeMsgDelete(buf[1:])
if err != nil {
panic(err.Error())
}
s, cc := js.server(), js.cluster
var removed bool
if md.NoErase {
removed, err = mset.removeMsg(md.Seq)
} else {
removed, err = mset.eraseMsg(md.Seq)
}
if err != nil && !isRecovering {
s.Debugf("JetStream cluster failed to delete msg %d from stream %q for account %q: %v",
md.Seq, md.Stream, md.Client.serviceAccount(), err)
}
js.mu.RLock()
isLeader := cc.isStreamLeader(md.Client.serviceAccount(), md.Stream)
js.mu.RUnlock()
if isLeader && !isRecovering {
var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
if err != nil {
resp.Error = jsError(err)
s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
} else if !removed {
resp.Error = &ApiError{Code: 400, Description: fmt.Sprintf("sequence [%d] not found", md.Seq)}
s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Success = true
s.sendAPIResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
case purgeStreamOp:
sp, err := decodeStreamPurge(buf[1:])
if err != nil {
panic(err.Error())
}
// Ignore if we are recovering and we have already processed.
if isRecovering {
if mset.state().FirstSeq <= sp.LastSeq {
// Make sure all messages from the purge are gone.
mset.store.Compact(sp.LastSeq + 1)
}
continue
}
s := js.server()
purged, err := mset.purge()
if err != nil {
s.Warnf("JetStream cluster failed to purge stream %q for account %q: %v", sp.Stream, sp.Client.serviceAccount(), err)
}
js.mu.RLock()
isLeader := js.cluster.isStreamLeader(sp.Client.serviceAccount(), sp.Stream)
js.mu.RUnlock()
if isLeader && !isRecovering {
var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
if err != nil {
resp.Error = jsError(err)
s.sendAPIErrResponse(sp.Client, mset.account(), sp.Subject, sp.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Purged = purged
resp.Success = true
s.sendAPIResponse(sp.Client, mset.account(), sp.Subject, sp.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
default:
panic("JetStream Cluster Unknown group entry op type!")
}
} else if e.Type == EntrySnapshot {
if !isRecovering && mset != nil {
var snap streamSnapshot
if err := json.Unmarshal(e.Data, &snap); err != nil {
return err
}
mset.processSnapshot(&snap)
}
} else if e.Type == EntryRemovePeer {
js.mu.RLock()
ourID := js.cluster.meta.ID()
js.mu.RUnlock()
if peer := string(e.Data); peer == ourID {
mset.stop(true, false)
}
return nil
}
}
return nil
}
// Returns the PeerInfo for all replicas of a raft node. This is different than node.Peers()
// and is used for external facing advisories.
func (s *Server) replicas(node RaftNode) []*PeerInfo {
now := time.Now()
var replicas []*PeerInfo
for _, rp := range node.Peers() {
if sir, ok := s.nodeToInfo.Load(rp.ID); ok && sir != nil {
si := sir.(nodeInfo)
pi := &PeerInfo{Name: si.name, Current: rp.Current, Active: now.Sub(rp.Last), Offline: si.offline, Lag: rp.Lag}
replicas = append(replicas, pi)
}
}
return replicas
}
// Will check our node peers and see if we should remove a peer.
func (js *jetStream) checkPeers(rg *raftGroup) {
js.mu.Lock()
defer js.mu.Unlock()
// FIXME(dlc) - Single replicas?
if rg == nil || rg.node == nil {
return
}
for _, peer := range rg.node.Peers() {
if !rg.isMember(peer.ID) {
rg.node.ProposeRemovePeer(peer.ID)
}
}
}
func (js *jetStream) processStreamLeaderChange(mset *stream, isLeader bool) {
if mset == nil {
return
}
sa := mset.streamAssignment()
if sa == nil {
return
}
js.mu.Lock()
s, account, err := js.srv, sa.Client.serviceAccount(), sa.err
client, subject, reply := sa.Client, sa.Subject, sa.Reply
hasResponded := sa.responded
sa.responded = true
js.mu.Unlock()
streamName := mset.name()
if isLeader {
s.Noticef("JetStream cluster new stream leader for '%s > %s'", sa.Client.serviceAccount(), streamName)
s.sendStreamLeaderElectAdvisory(mset)
// Check for peer removal and process here if needed.
js.checkPeers(sa.Group)
} else {
// We are stepping down.
// Make sure if we are doing so because we have lost quorum that we send the appropriate advisories.
if node := mset.raftNode(); node != nil && !node.Quorum() && time.Since(node.Created()) > 5*time.Second {
s.sendStreamLostQuorumAdvisory(mset)
}
}
// Tell stream to switch leader status.
mset.setLeader(isLeader)
if !isLeader || hasResponded {
return
}
acc, _ := s.LookupAccount(account)
if acc == nil {
return
}
// Send our response.
var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}}
if err != nil {
resp.Error = jsError(err)
s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
} else {
resp.StreamInfo = &StreamInfo{
Created: mset.createdTime(),
State: mset.state(),
Config: mset.config(),
Cluster: js.clusterInfo(mset.raftGroup()),
Sources: mset.sourcesInfo(),
Mirror: mset.mirrorInfo(),
}
s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
if node := mset.raftNode(); node != nil {
mset.sendCreateAdvisory()
}
}
}
// Fixed value ok for now.
const lostQuorumAdvInterval = 10 * time.Second
// Determines if we should send lost quorum advisory. We throttle these after first one.
func (mset *stream) shouldSendLostQuorum() bool {
mset.mu.Lock()
defer mset.mu.Unlock()
if time.Since(mset.lqsent) >= lostQuorumAdvInterval {
mset.lqsent = time.Now()
return true
}
return false
}
func (s *Server) sendStreamLostQuorumAdvisory(mset *stream) {
if mset == nil {
return
}
node, stream, acc := mset.raftNode(), mset.name(), mset.account()
if node == nil {
return
}
if !mset.shouldSendLostQuorum() {
return
}
s.Warnf("JetStream cluster stream '%s > %s' has NO quorum, stalled.", acc.GetName(), stream)
subj := JSAdvisoryStreamQuorumLostPre + "." + stream
adv := &JSStreamQuorumLostAdvisory{
TypedEvent: TypedEvent{
Type: JSStreamQuorumLostAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Replicas: s.replicas(node),
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
func (s *Server) sendStreamLeaderElectAdvisory(mset *stream) {
if mset == nil {
return
}
node, stream, acc := mset.raftNode(), mset.name(), mset.account()
if node == nil {
return
}
subj := JSAdvisoryStreamLeaderElectedPre + "." + stream
adv := &JSStreamLeaderElectedAdvisory{
TypedEvent: TypedEvent{
Type: JSStreamLeaderElectedAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Leader: s.serverNameForNode(node.GroupLeader()),
Replicas: s.replicas(node),
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
// Will lookup a stream assignment.
// Lock should be held.
func (js *jetStream) streamAssignment(account, stream string) (sa *streamAssignment) {
cc := js.cluster
if cc == nil {
return nil
}
if as := cc.streams[account]; as != nil {
sa = as[stream]
}
return sa
}
// processStreamAssignment is called when followers have replicated an assignment.
func (js *jetStream) processStreamAssignment(sa *streamAssignment) {
js.mu.RLock()
s, cc := js.srv, js.cluster
js.mu.RUnlock()
if s == nil || cc == nil {
// TODO(dlc) - debug at least
return
}
acc, err := s.LookupAccount(sa.Client.serviceAccount())
if err != nil {
// TODO(dlc) - log error
return
}
stream := sa.Config.Name
js.mu.Lock()
if cc.meta == nil {
js.mu.Unlock()
return
}
ourID := cc.meta.ID()
var isMember bool
if sa.Group != nil {
isMember = sa.Group.isMember(ourID)
}
accStreams := cc.streams[acc.Name]
if accStreams == nil {
accStreams = make(map[string]*streamAssignment)
} else if osa := accStreams[stream]; osa != nil {
// Copy over private existing state from former SA.
sa.Group.node = osa.Group.node
sa.consumers = osa.consumers
sa.responded = osa.responded
sa.err = osa.err
}
// Update our state.
accStreams[stream] = sa
cc.streams[acc.Name] = accStreams
js.mu.Unlock()
// Check if this is for us..
if isMember {
js.processClusterCreateStream(acc, sa)
} else if mset, _ := acc.lookupStream(sa.Config.Name); mset != nil {
// We have one here even though we are not a member. This can happen on re-assignment.
s.Debugf("JetStream removing stream '%s > %s' from this server, re-assigned", sa.Client.serviceAccount(), sa.Config.Name)
if node := mset.raftNode(); node != nil {
node.ProposeRemovePeer(ourID)
}
mset.stop(true, false)
}
}
// processUpdateStreamAssignment is called when followers have replicated an updated assignment.
func (js *jetStream) processUpdateStreamAssignment(sa *streamAssignment) {
js.mu.RLock()
s, cc := js.srv, js.cluster
js.mu.RUnlock()
if s == nil || cc == nil {
// TODO(dlc) - debug at least
return
}
acc, err := s.LookupAccount(sa.Client.serviceAccount())
if err != nil {
// TODO(dlc) - log error
return
}
stream := sa.Config.Name
js.mu.Lock()
if cc.meta == nil {
js.mu.Unlock()
return
}
ourID := cc.meta.ID()
var isMember bool
if sa.Group != nil {
isMember = sa.Group.isMember(ourID)
}
accStreams := cc.streams[acc.Name]
if accStreams == nil {
js.mu.Unlock()
return
}
osa := accStreams[stream]
if osa == nil {
js.mu.Unlock()
return
}
// Copy over private existing state from former SA.
sa.Group.node = osa.Group.node
sa.consumers = osa.consumers
sa.err = osa.err
// Update our state.
accStreams[stream] = sa
cc.streams[acc.Name] = accStreams
js.mu.Unlock()
// Check if this is for us..
if isMember {
js.processClusterUpdateStream(acc, sa)
} else if mset, _ := acc.lookupStream(sa.Config.Name); mset != nil {
// We have one here even though we are not a member. This can happen on re-assignment.
s.Debugf("JetStream removing stream '%s > %s' from this server, re-assigned", sa.Client.serviceAccount(), sa.Config.Name)
if node := mset.raftNode(); node != nil {
node.ProposeRemovePeer(ourID)
}
mset.stop(true, false)
}
}
// processClusterUpdateStream is called when we have a stream assignment that
// has been updated for an existing assignment.
func (js *jetStream) processClusterUpdateStream(acc *Account, sa *streamAssignment) {
if sa == nil {
return
}
js.mu.RLock()
s, rg := js.srv, sa.Group
client, subject, reply := sa.Client, sa.Subject, sa.Reply
alreadyRunning := rg.node != nil
hasResponded := sa.responded
js.mu.RUnlock()
mset, err := acc.lookupStream(sa.Config.Name)
if err == nil && mset != nil {
if rg.node != nil && !alreadyRunning {
s.startGoRoutine(func() { js.monitorStream(mset, sa) })
}
mset.setStreamAssignment(sa)
if err = mset.update(sa.Config); err != nil {
s.Warnf("JetStream cluster error updating stream %q for account %q: %v", sa.Config.Name, acc.Name, err)
}
}
if err != nil {
js.mu.Lock()
sa.err = err
if rg.node != nil {
rg.node.Delete()
}
result := &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
}
result.Response.Error = jsError(err)
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
return
}
mset.mu.RLock()
isLeader := mset.isLeader()
mset.mu.RUnlock()
js.mu.Lock()
sa.responded = true
js.mu.Unlock()
if !isLeader || hasResponded {
return
}
// Send our response.
var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}}
resp.StreamInfo = &StreamInfo{
Created: mset.createdTime(),
State: mset.state(),
Config: mset.config(),
Cluster: js.clusterInfo(mset.raftGroup()),
Mirror: mset.mirrorInfo(),
Sources: mset.sourcesInfo(),
}
s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
}
// processClusterCreateStream is called when we have a stream assignment that
// has been committed and this server is a member of the peer group.
func (js *jetStream) processClusterCreateStream(acc *Account, sa *streamAssignment) {
if sa == nil {
return
}
js.mu.RLock()
s, rg := js.srv, sa.Group
alreadyRunning := rg.node != nil
storage := sa.Config.Storage
js.mu.RUnlock()
// Process the raft group and make sure it's running if needed.
err := js.createRaftGroup(rg, storage)
// If we are restoring, create the stream if we are R>1 and not the preferred who handles the
// receipt of the snapshot itself.
shouldCreate := true
if sa.Restore != nil {
if len(rg.Peers) == 1 || rg.node != nil && rg.node.ID() == rg.Preferred {
shouldCreate = false
} else {
sa.Restore = nil
}
}
// Our stream.
var mset *stream
// Process here if not restoring or not the leader.
if shouldCreate && err == nil {
// Go ahead and create or update the stream.
mset, err = acc.lookupStream(sa.Config.Name)
if err == nil && mset != nil {
mset.setStreamAssignment(sa)
if err := mset.update(sa.Config); err != nil {
s.Warnf("JetStream cluster error updating stream %q for account %q: %v", sa.Config.Name, acc.Name, err)
}
} else if err == ErrJetStreamStreamNotFound {
// Add in the stream here.
mset, err = acc.addStreamWithAssignment(sa.Config, nil, sa)
}
if mset != nil {
mset.setCreatedTime(sa.Created)
}
}
// This is an error condition.
if err != nil {
s.Warnf("Stream create failed for '%s > %s': %v", sa.Client.serviceAccount(), sa.Config.Name, err)
js.mu.Lock()
sa.err = err
hasResponded := sa.responded
// If out of space do nothing for now.
if isOutOfSpaceErr(err) {
hasResponded = true
}
if rg.node != nil {
rg.node.Delete()
}
var result *streamAssignmentResult
if !hasResponded {
result = &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
}
result.Response.Error = jsError(err)
}
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
if result != nil {
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
}
return
}
// Start our monitoring routine.
if rg.node != nil {
if !alreadyRunning {
s.startGoRoutine(func() { js.monitorStream(mset, sa) })
}
} else {
// Single replica stream, process manually here.
// If we are restoring, process that first.
if sa.Restore != nil {
// We are restoring a stream here.
restoreDoneCh := s.processStreamRestore(sa.Client, acc, sa.Config, _EMPTY_, sa.Reply, _EMPTY_)
s.startGoRoutine(func() {
defer s.grWG.Done()
select {
case err := <-restoreDoneCh:
if err == nil {
mset, err = acc.lookupStream(sa.Config.Name)
if mset != nil {
mset.setStreamAssignment(sa)
mset.setCreatedTime(sa.Created)
}
}
if err != nil {
if mset != nil {
mset.delete()
}
js.mu.Lock()
sa.err = err
result := &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Restore: &JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}},
}
result.Restore.Error = jsError(sa.err)
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, b)
return
}
js.processStreamLeaderChange(mset, true)
// Check to see if we have restored consumers here.
// These are not currently assigned so we will need to do so here.
if consumers := mset.getConsumers(); len(consumers) > 0 {
js.mu.RLock()
cc := js.cluster
js.mu.RUnlock()
for _, o := range consumers {
rg := cc.createGroupForConsumer(sa)
name, cfg := o.String(), o.config()
// Place our initial state here as well for assignment distribution.
ca := &consumerAssignment{
Group: rg,
Stream: sa.Config.Name,
Name: name,
Config: &cfg,
Client: sa.Client,
Created: o.createdTime(),
}
addEntry := encodeAddConsumerAssignment(ca)
cc.meta.ForwardProposal(addEntry)
// Check to make sure we see the assignment.
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
js.mu.RLock()
ca, meta := js.consumerAssignment(ca.Client.serviceAccount(), sa.Config.Name, name), cc.meta
js.mu.RUnlock()
if ca == nil {
s.Warnf("Consumer assignment has not been assigned, retrying")
if meta != nil {
meta.ForwardProposal(addEntry)
} else {
return
}
} else {
return
}
}
}()
}
}
case <-s.quitCh:
return
}
})
} else {
js.processStreamLeaderChange(mset, true)
}
}
}
// processStreamRemoval is called when followers have replicated an assignment.
func (js *jetStream) processStreamRemoval(sa *streamAssignment) {
js.mu.Lock()
s, cc := js.srv, js.cluster
if s == nil || cc == nil || cc.meta == nil {
// TODO(dlc) - debug at least
js.mu.Unlock()
return
}
stream := sa.Config.Name
isMember := sa.Group.isMember(cc.meta.ID())
wasLeader := cc.isStreamLeader(sa.Client.serviceAccount(), stream)
// Check if we already have this assigned.
accStreams := cc.streams[sa.Client.serviceAccount()]
needDelete := accStreams != nil && accStreams[stream] != nil
if needDelete {
delete(accStreams, stream)
if len(accStreams) == 0 {
delete(cc.streams, sa.Client.serviceAccount())
}
}
js.mu.Unlock()
if needDelete {
js.processClusterDeleteStream(sa, isMember, wasLeader)
}
}
func (js *jetStream) processClusterDeleteStream(sa *streamAssignment, isMember, wasLeader bool) {
if sa == nil {
return
}
js.mu.RLock()
s := js.srv
hadLeader := sa.Group.node == nil || sa.Group.node.GroupLeader() != noLeader
js.mu.RUnlock()
acc, err := s.LookupAccount(sa.Client.serviceAccount())
if err != nil {
s.Debugf("JetStream cluster failed to lookup account %q: %v", sa.Client.serviceAccount(), err)
return
}
var resp = JSApiStreamDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamDeleteResponseType}}
// Go ahead and delete the stream.
mset, err := acc.lookupStream(sa.Config.Name)
if err != nil {
resp.Error = jsNotFoundError(err)
} else if mset != nil {
err = mset.stop(true, wasLeader)
}
if sa.Group.node != nil {
sa.Group.node.Delete()
}
if !isMember || !wasLeader && hadLeader {
return
}
if err != nil {
if resp.Error == nil {
resp.Error = jsError(err)
}
s.sendAPIErrResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Success = true
s.sendAPIResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
// processConsumerAssignment is called when followers have replicated an assignment for a consumer.
func (js *jetStream) processConsumerAssignment(ca *consumerAssignment) {
js.mu.Lock()
s, cc := js.srv, js.cluster
if s == nil || cc == nil || cc.meta == nil {
// TODO(dlc) - debug at least
js.mu.Unlock()
return
}
acc, err := s.LookupAccount(ca.Client.serviceAccount())
if err != nil {
// TODO(dlc) - log error
return
}
sa := js.streamAssignment(ca.Client.serviceAccount(), ca.Stream)
if sa == nil {
s.Debugf("Consumer create failed, could not locate stream '%s > %s'", ca.Client.serviceAccount(), ca.Stream)
ca.err = ErrJetStreamStreamNotFound
result := &consumerAssignmentResult{
Account: ca.Client.serviceAccount(),
Stream: ca.Stream,
Consumer: ca.Name,
Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
}
result.Response.Error = jsNotFoundError(ErrJetStreamStreamNotFound)
// Send response to the metadata leader. They will forward to the user as needed.
b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, b)
js.mu.Unlock()
return
}
if sa.consumers == nil {
sa.consumers = make(map[string]*consumerAssignment)
} else if oca := sa.consumers[ca.Name]; oca != nil {
// Copy over private existing state from former CA.
ca.Group.node = oca.Group.node
ca.responded = oca.responded
ca.err = oca.err
}
// Place into our internal map under the stream assignment.
// Ok to replace an existing one, we check on process call below.
sa.consumers[ca.Name] = ca
// See if we are a member
ourID := cc.meta.ID()
isMember := ca.Group.isMember(ourID)
js.mu.Unlock()
// Check if this is for us..
if isMember {
js.processClusterCreateConsumer(ca)
} else {
// We are not a member, if we have this consumer on this
// server remove it.
if mset, _ := acc.lookupStream(ca.Stream); mset != nil {
if o := mset.lookupConsumer(ca.Name); o != nil {
s.Debugf("JetStream removing consumer '%s > %s > %s' from this server, re-assigned",
ca.Client.serviceAccount(), ca.Stream, ca.Name)
if node := o.raftNode(); node != nil {
node.ProposeRemovePeer(ourID)
}
o.stopWithFlags(true, false, false)
}
}
}
}
func (js *jetStream) processConsumerRemoval(ca *consumerAssignment) {
js.mu.Lock()
s, cc := js.srv, js.cluster
if s == nil || cc == nil || cc.meta == nil {
// TODO(dlc) - debug at least
js.mu.Unlock()
return
}
isMember := ca.Group.isMember(cc.meta.ID())
wasLeader := cc.isConsumerLeader(ca.Client.serviceAccount(), ca.Stream, ca.Name)
// Delete from our state.
var needDelete bool
if accStreams := cc.streams[ca.Client.serviceAccount()]; accStreams != nil {
if sa := accStreams[ca.Stream]; sa != nil && sa.consumers != nil && sa.consumers[ca.Name] != nil {
needDelete = true
delete(sa.consumers, ca.Name)
}
}
js.mu.Unlock()
if needDelete {
js.processClusterDeleteConsumer(ca, isMember, wasLeader)
}
}
type consumerAssignmentResult struct {
Account string `json:"account"`
Stream string `json:"stream"`
Consumer string `json:"consumer"`
Response *JSApiConsumerCreateResponse `json:"response,omitempty"`
}
// processClusterCreateConsumer is when we are a member fo the group and need to create the consumer.
func (js *jetStream) processClusterCreateConsumer(ca *consumerAssignment) {
if ca == nil {
return
}
js.mu.RLock()
s := js.srv
acc, err := s.LookupAccount(ca.Client.serviceAccount())
if err != nil {
s.Warnf("JetStream cluster failed to lookup account %q: %v", ca.Client.serviceAccount(), err)
js.mu.RUnlock()
return
}
rg := ca.Group
alreadyRunning := rg.node != nil
js.mu.RUnlock()
// Go ahead and create or update the consumer.
mset, err := acc.lookupStream(ca.Stream)
if err != nil {
js.mu.Lock()
s.Debugf("Consumer create failed, could not locate stream '%s > %s'", ca.Client.serviceAccount(), ca.Stream)
ca.err = ErrJetStreamStreamNotFound
result := &consumerAssignmentResult{
Account: ca.Client.serviceAccount(),
Stream: ca.Stream,
Consumer: ca.Name,
Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
}
result.Response.Error = jsNotFoundError(ErrJetStreamStreamNotFound)
// Send response to the metadata leader. They will forward to the user as needed.
b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, b)
js.mu.Unlock()
return
}
// Process the raft group and make sure its running if needed.
js.createRaftGroup(rg, mset.config().Storage)
// Check if we already have this consumer running.
o := mset.lookupConsumer(ca.Name)
if o != nil {
if o.isDurable() && o.isPushMode() {
ocfg := o.config()
if configsEqualSansDelivery(ocfg, *ca.Config) && o.hasNoLocalInterest() {
o.updateDeliverSubject(ca.Config.DeliverSubject)
}
}
o.setConsumerAssignment(ca)
s.Debugf("JetStream cluster, consumer was already running")
}
// Add in the consumer if needed.
if o == nil {
o, err = mset.addConsumerWithAssignment(ca.Config, ca.Name, ca)
}
// If we have an initial state set apply that now.
if ca.State != nil && o != nil {
err = o.setStoreState(ca.State)
}
if err != nil {
s.Warnf("Consumer create failed for '%s > %s > %s': %v\n", ca.Client.serviceAccount(), ca.Stream, ca.Name, err)
js.mu.Lock()
ca.err = err
hasResponded := ca.responded
// If out of space do nothing for now.
if isOutOfSpaceErr(err) {
hasResponded = true
}
if rg.node != nil {
rg.node.Delete()
}
var result *consumerAssignmentResult
if !hasResponded {
result = &consumerAssignmentResult{
Account: ca.Client.serviceAccount(),
Stream: ca.Stream,
Consumer: ca.Name,
Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
}
result.Response.Error = jsError(err)
}
js.mu.Unlock()
if result != nil {
// Send response to the metadata leader. They will forward to the user as needed.
b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, b)
}
} else {
o.setCreatedTime(ca.Created)
// Start our monitoring routine.
if rg.node != nil {
if !alreadyRunning {
s.startGoRoutine(func() { js.monitorConsumer(o, ca) })
}
} else {
// Single replica consumer, process manually here.
js.processConsumerLeaderChange(o, true)
}
}
}
func (js *jetStream) processClusterDeleteConsumer(ca *consumerAssignment, isMember, wasLeader bool) {
if ca == nil {
return
}
js.mu.RLock()
s := js.srv
js.mu.RUnlock()
acc, err := s.LookupAccount(ca.Client.serviceAccount())
if err != nil {
s.Warnf("JetStream cluster failed to lookup account %q: %v", ca.Client.serviceAccount(), err)
return
}
var resp = JSApiConsumerDeleteResponse{ApiResponse: ApiResponse{Type: JSApiConsumerDeleteResponseType}}
// Go ahead and delete the consumer.
mset, err := acc.lookupStream(ca.Stream)
if err != nil {
resp.Error = jsNotFoundError(err)
} else if mset != nil {
if o := mset.lookupConsumer(ca.Name); o != nil {
err = o.stopWithFlags(true, true, wasLeader)
} else {
resp.Error = jsNoConsumerErr
}
}
if ca.Group.node != nil {
ca.Group.node.Delete()
}
if !wasLeader || ca.Reply == _EMPTY_ {
return
}
if err != nil {
if resp.Error == nil {
resp.Error = jsError(err)
}
s.sendAPIErrResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Success = true
s.sendAPIResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
// Returns the consumer assignment, or nil if not present.
// Lock should be held.
func (js *jetStream) consumerAssignment(account, stream, consumer string) *consumerAssignment {
if sa := js.streamAssignment(account, stream); sa != nil {
return sa.consumers[consumer]
}
return nil
}
// consumerAssigned informs us if this server has this consumer assigned.
func (jsa *jsAccount) consumerAssigned(stream, consumer string) bool {
jsa.mu.RLock()
defer jsa.mu.RUnlock()
js, acc := jsa.js, jsa.account
if js == nil {
return false
}
return js.cluster.isConsumerAssigned(acc, stream, consumer)
}
// Read lock should be held.
func (cc *jetStreamCluster) isConsumerAssigned(a *Account, stream, consumer string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
var sa *streamAssignment
accStreams := cc.streams[a.Name]
if accStreams != nil {
sa = accStreams[stream]
}
if sa == nil {
// TODO(dlc) - This should not happen.
return false
}
ca := sa.consumers[consumer]
if ca == nil {
return false
}
rg := ca.Group
// Check if we are the leader of this raftGroup assigned to the stream.
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
return true
}
}
return false
}
func (o *consumer) raftGroup() *raftGroup {
if o == nil {
return nil
}
o.mu.RLock()
defer o.mu.RUnlock()
if o.ca == nil {
return nil
}
return o.ca.Group
}
func (o *consumer) raftNode() RaftNode {
if o == nil {
return nil
}
o.mu.RLock()
defer o.mu.RUnlock()
return o.node
}
func (js *jetStream) monitorConsumer(o *consumer, ca *consumerAssignment) {
s, n := js.server(), o.raftNode()
defer s.grWG.Done()
if n == nil {
s.Warnf("No RAFT group for consumer")
return
}
qch, lch, ach := n.QuitC(), n.LeadChangeC(), n.ApplyC()
s.Debugf("Starting consumer monitor for '%s > %s > %s", o.acc.Name, ca.Stream, ca.Name)
defer s.Debugf("Exiting consumer monitor for '%s > %s > %s'", o.acc.Name, ca.Stream, ca.Name)
const (
compactInterval = 2 * time.Minute
compactSizeMin = 4 * 1024 * 1024
compactNumMin = 4
)
t := time.NewTicker(compactInterval)
defer t.Stop()
var lastSnap []byte
var lastApplied uint64
// Should only to be called from leader.
doSnapshot := func() {
if state, err := o.store.State(); err == nil && state != nil {
if snap := encodeConsumerState(state); !bytes.Equal(lastSnap, snap) {
if err := n.InstallSnapshot(snap); err == nil {
lastSnap = snap
_, _, lastApplied = n.Progress()
}
}
}
}
// Track if we are leader.
var isLeader bool
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case ce := <-ach:
// No special processing needed for when we are caught up on restart.
if ce == nil {
continue
}
if err := js.applyConsumerEntries(o, ce, isLeader); err == nil {
n.Applied(ce.Index)
ne := ce.Index - lastApplied
// If over our compact min and we have at least min entries to compact, go ahead and snapshot/compact.
if _, b := n.Size(); b > compactSizeMin && ne > compactNumMin {
doSnapshot()
}
} else {
s.Warnf("Error applying consumer entries to '%s > %s'", ca.Client.serviceAccount(), ca.Name)
}
case isLeader = <-lch:
if !isLeader && n.GroupLeader() != noLeader {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerLeaderChange(o, isLeader)
case <-t.C:
doSnapshot()
}
}
}
func (js *jetStream) applyConsumerEntries(o *consumer, ce *CommittedEntry, isLeader bool) error {
for _, e := range ce.Entries {
if e.Type == EntrySnapshot {
// No-op needed?
state, err := decodeConsumerState(e.Data)
if err != nil {
panic(err.Error())
}
o.store.Update(state)
} else if e.Type == EntryRemovePeer {
js.mu.RLock()
ourID := js.cluster.meta.ID()
js.mu.RUnlock()
if peer := string(e.Data); peer == ourID {
o.stopWithFlags(true, false, false)
}
return nil
} else {
// Consumer leaders process these already.
buf := e.Data
switch entryOp(buf[0]) {
case updateDeliveredOp:
// These are handled in place in leaders.
if !isLeader {
dseq, sseq, dc, ts, err := decodeDeliveredUpdate(buf[1:])
if err != nil {
panic(err.Error())
}
if err := o.store.UpdateDelivered(dseq, sseq, dc, ts); err != nil {
panic(err.Error())
}
}
case updateAcksOp:
dseq, sseq, err := decodeAckUpdate(buf[1:])
if err != nil {
panic(err.Error())
}
o.processReplicatedAck(dseq, sseq)
case updateSkipOp:
o.mu.Lock()
if !o.isLeader() {
var le = binary.LittleEndian
o.sseq = le.Uint64(buf[1:])
}
o.mu.Unlock()
default:
panic(fmt.Sprintf("JetStream Cluster Unknown group entry op type! %v", entryOp(buf[0])))
}
}
}
return nil
}
func (o *consumer) processReplicatedAck(dseq, sseq uint64) {
o.store.UpdateAcks(dseq, sseq)
o.mu.RLock()
mset := o.mset
if mset == nil || mset.cfg.Retention != InterestPolicy {
o.mu.RUnlock()
return
}
var sagap uint64
if o.cfg.AckPolicy == AckAll {
if o.isLeader() {
sagap = sseq - o.asflr
} else {
// We are a follower so only have the store state, so read that in.
state, err := o.store.State()
if err != nil {
o.mu.RUnlock()
return
}
sagap = sseq - state.AckFloor.Stream
}
}
o.mu.RUnlock()
if sagap > 1 {
// FIXME(dlc) - This is very inefficient, will need to fix.
for seq := sseq; seq > sseq-sagap; seq-- {
mset.ackMsg(o, seq)
}
} else {
mset.ackMsg(o, sseq)
}
}
var errBadAckUpdate = errors.New("jetstream cluster bad replicated ack update")
var errBadDeliveredUpdate = errors.New("jetstream cluster bad replicated delivered update")
func decodeAckUpdate(buf []byte) (dseq, sseq uint64, err error) {
var bi, n int
if dseq, n = binary.Uvarint(buf); n < 0 {
return 0, 0, errBadAckUpdate
}
bi += n
if sseq, n = binary.Uvarint(buf[bi:]); n < 0 {
return 0, 0, errBadAckUpdate
}
return dseq, sseq, nil
}
func decodeDeliveredUpdate(buf []byte) (dseq, sseq, dc uint64, ts int64, err error) {
var bi, n int
if dseq, n = binary.Uvarint(buf); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if sseq, n = binary.Uvarint(buf[bi:]); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if dc, n = binary.Uvarint(buf[bi:]); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if ts, n = binary.Varint(buf[bi:]); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
return dseq, sseq, dc, ts, nil
}
func (js *jetStream) processConsumerLeaderChange(o *consumer, isLeader bool) {
ca := o.consumerAssignment()
if ca == nil {
return
}
js.mu.Lock()
s, account, err := js.srv, ca.Client.serviceAccount(), ca.err
client, subject, reply := ca.Client, ca.Subject, ca.Reply
hasResponded := ca.responded
ca.responded = true
js.mu.Unlock()
streamName := o.streamName()
consumerName := o.String()
acc, _ := s.LookupAccount(account)
if acc == nil {
return
}
if isLeader {
s.Noticef("JetStream cluster new consumer leader for '%s > %s > %s'", ca.Client.serviceAccount(), streamName, consumerName)
s.sendConsumerLeaderElectAdvisory(o)
// Check for peer removal and process here if needed.
js.checkPeers(ca.Group)
} else {
// We are stepping down.
// Make sure if we are doing so because we have lost quorum that we send the appropriate advisories.
if node := o.raftNode(); node != nil && !node.Quorum() && time.Since(node.Created()) > 5*time.Second {
s.sendConsumerLostQuorumAdvisory(o)
}
}
// Tell consumer to switch leader status.
o.setLeader(isLeader)
if !isLeader || hasResponded {
return
}
var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
if err != nil {
resp.Error = jsError(err)
s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
} else {
resp.ConsumerInfo = o.info()
s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
if node := o.raftNode(); node != nil {
o.sendCreateAdvisory()
}
}
}
// Determines if we should send lost quorum advisory. We throttle these after first one.
func (o *consumer) shouldSendLostQuorum() bool {
o.mu.Lock()
defer o.mu.Unlock()
if time.Since(o.lqsent) >= lostQuorumAdvInterval {
o.lqsent = time.Now()
return true
}
return false
}
func (s *Server) sendConsumerLostQuorumAdvisory(o *consumer) {
if o == nil {
return
}
node, stream, consumer, acc := o.raftNode(), o.streamName(), o.String(), o.account()
if node == nil {
return
}
if !o.shouldSendLostQuorum() {
return
}
s.Warnf("JetStream cluster consumer '%s > %s > %s' has NO quorum, stalled.", acc.GetName(), stream, consumer)
subj := JSAdvisoryConsumerQuorumLostPre + "." + stream + "." + consumer
adv := &JSConsumerQuorumLostAdvisory{
TypedEvent: TypedEvent{
Type: JSConsumerQuorumLostAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Consumer: consumer,
Replicas: s.replicas(node),
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
func (s *Server) sendConsumerLeaderElectAdvisory(o *consumer) {
if o == nil {
return
}
node, stream, consumer, acc := o.raftNode(), o.streamName(), o.String(), o.account()
if node == nil {
return
}
subj := JSAdvisoryConsumerLeaderElectedPre + "." + stream + "." + consumer
adv := &JSConsumerLeaderElectedAdvisory{
TypedEvent: TypedEvent{
Type: JSConsumerLeaderElectedAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Consumer: consumer,
Leader: s.serverNameForNode(node.GroupLeader()),
Replicas: s.replicas(node),
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
type streamAssignmentResult struct {
Account string `json:"account"`
Stream string `json:"stream"`
Response *JSApiStreamCreateResponse `json:"create_response,omitempty"`
Restore *JSApiStreamRestoreResponse `json:"restore_response,omitempty"`
}
// Process error results of stream and consumer assignments.
// Success will be handled by stream leader.
func (js *jetStream) processStreamAssignmentResults(sub *subscription, c *client, subject, reply string, msg []byte) {
var result streamAssignmentResult
if err := json.Unmarshal(msg, &result); err != nil {
// TODO(dlc) - log
return
}
acc, _ := js.srv.LookupAccount(result.Account)
if acc == nil {
// TODO(dlc) - log
return
}
js.mu.Lock()
defer js.mu.Unlock()
s, cc := js.srv, js.cluster
// FIXME(dlc) - suppress duplicates?
if sa := js.streamAssignment(result.Account, result.Stream); sa != nil {
var resp string
if result.Response != nil {
resp = s.jsonResponse(result.Response)
} else if result.Restore != nil {
resp = s.jsonResponse(result.Restore)
}
if !sa.responded {
sa.responded = true
js.srv.sendAPIErrResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, resp)
// TODO(dlc) - Could have mixed results, should track per peer.
// Set sa.err while we are deleting so we will not respond to list/names requests.
sa.err = ErrJetStreamNotAssigned
cc.meta.Propose(encodeDeleteStreamAssignment(sa))
}
}
}
func (js *jetStream) processConsumerAssignmentResults(sub *subscription, c *client, subject, reply string, msg []byte) {
var result consumerAssignmentResult
if err := json.Unmarshal(msg, &result); err != nil {
// TODO(dlc) - log
return
}
acc, _ := js.srv.LookupAccount(result.Account)
if acc == nil {
// TODO(dlc) - log
return
}
js.mu.Lock()
defer js.mu.Unlock()
s, cc := js.srv, js.cluster
if sa := js.streamAssignment(result.Account, result.Stream); sa != nil && sa.consumers != nil {
if ca := sa.consumers[result.Consumer]; ca != nil && !ca.responded {
js.srv.sendAPIErrResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(result.Response))
ca.responded = true
// Check if this failed.
// TODO(dlc) - Could have mixed results, should track per peer.
if result.Response.Error != nil {
// So while we are delting we will not respond to list/names requests.
ca.err = ErrJetStreamNotAssigned
cc.meta.Propose(encodeDeleteConsumerAssignment(ca))
}
}
}
}
const (
streamAssignmentSubj = "$SYS.JSC.STREAM.ASSIGNMENT.RESULT"
consumerAssignmentSubj = "$SYS.JSC.CONSUMER.ASSIGNMENT.RESULT"
)
// Lock should be held.
func (js *jetStream) startUpdatesSub() {
cc, s, c := js.cluster, js.srv, js.cluster.c
if cc.streamResults == nil {
cc.streamResults, _ = s.systemSubscribe(streamAssignmentSubj, _EMPTY_, false, c, js.processStreamAssignmentResults)
}
if cc.consumerResults == nil {
cc.consumerResults, _ = s.systemSubscribe(consumerAssignmentSubj, _EMPTY_, false, c, js.processConsumerAssignmentResults)
}
if cc.stepdown == nil {
cc.stepdown, _ = s.systemSubscribe(JSApiLeaderStepDown, _EMPTY_, false, c, s.jsLeaderStepDownRequest)
}
if cc.peerRemove == nil {
cc.peerRemove, _ = s.systemSubscribe(JSApiRemoveServer, _EMPTY_, false, c, s.jsLeaderServerRemoveRequest)
}
}
// Lock should be held.
func (js *jetStream) stopUpdatesSub() {
cc := js.cluster
if cc.streamResults != nil {
cc.s.sysUnsubscribe(cc.streamResults)
cc.streamResults = nil
}
if cc.consumerResults != nil {
cc.s.sysUnsubscribe(cc.consumerResults)
cc.consumerResults = nil
}
if cc.stepdown != nil {
cc.s.sysUnsubscribe(cc.stepdown)
cc.stepdown = nil
}
if cc.peerRemove != nil {
cc.s.sysUnsubscribe(cc.peerRemove)
cc.peerRemove = nil
}
}
func (js *jetStream) processLeaderChange(isLeader bool) {
if isLeader {
js.srv.Noticef("JetStream cluster new metadata leader")
}
js.mu.Lock()
defer js.mu.Unlock()
if isLeader {
js.startUpdatesSub()
} else {
js.stopUpdatesSub()
// TODO(dlc) - stepdown.
}
}
// Lock should be held.
func (cc *jetStreamCluster) remapStreamAssignment(sa *streamAssignment, removePeer string) bool {
// Need to select a replacement peer
s, now, cluster := cc.s, time.Now(), sa.Client.Cluster
if sa.Config.Placement != nil && sa.Config.Placement.Cluster != _EMPTY_ {
cluster = sa.Config.Placement.Cluster
}
ourID := cc.meta.ID()
for _, p := range cc.meta.Peers() {
// If it is not in our list it's probably shutdown, so don't consider.
if si, ok := s.nodeToInfo.Load(p.ID); !ok || si.(nodeInfo).offline {
continue
}
// Make sure they are active and current and not already part of our group.
current, lastSeen := p.Current, now.Sub(p.Last)
// We do not track activity of ourselves so ignore.
if p.ID == ourID {
lastSeen = 0
}
if !current || lastSeen > lostQuorumInterval || sa.Group.isMember(p.ID) {
continue
}
// Make sure the correct cluster.
if s.clusterNameForNode(p.ID) != cluster {
continue
}
// If we are here we have our candidate replacement, swap out the old one.
for i, peer := range sa.Group.Peers {
if peer == removePeer {
sa.Group.Peers[i] = p.ID
// Don't influence preferred leader.
sa.Group.Preferred = _EMPTY_
return true
}
}
}
return false
}
// selectPeerGroup will select a group of peers to start a raft group.
// TODO(dlc) - For now randomly select. Can be way smarter.
func (cc *jetStreamCluster) selectPeerGroup(r int, cluster string) []string {
var nodes []string
peers := cc.meta.Peers()
s := cc.s
for _, p := range peers {
// If we know its offline or it is not in our list it probably shutdown, so don't consider.
if si, ok := s.nodeToInfo.Load(p.ID); !ok || si.(nodeInfo).offline {
continue
}
if cluster != _EMPTY_ {
if s.clusterNameForNode(p.ID) == cluster {
nodes = append(nodes, p.ID)
}
} else {
nodes = append(nodes, p.ID)
}
}
if len(nodes) < r {
return nil
}
// Don't depend on range to randomize.
rand.Shuffle(len(nodes), func(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] })
return nodes[:r]
}
func groupNameForStream(peers []string, storage StorageType) string {
return groupName("S", peers, storage)
}
func groupNameForConsumer(peers []string, storage StorageType) string {
return groupName("C", peers, storage)
}
func groupName(prefix string, peers []string, storage StorageType) string {
var gns string
if len(peers) == 1 {
gns = peers[0]
} else {
gns = string(getHash(nuid.Next()))
}
return fmt.Sprintf("%s-R%d%s-%s", prefix, len(peers), storage.String()[:1], gns)
}
// createGroupForStream will create a group for assignment for the stream.
// Lock should be held.
func (cc *jetStreamCluster) createGroupForStream(ci *ClientInfo, cfg *StreamConfig) *raftGroup {
replicas := cfg.Replicas
if replicas == 0 {
replicas = 1
}
cluster := ci.Cluster
if cfg.Placement != nil && cfg.Placement.Cluster != _EMPTY_ {
cluster = cfg.Placement.Cluster
}
// Need to create a group here.
// TODO(dlc) - Can be way smarter here.
peers := cc.selectPeerGroup(replicas, cluster)
if len(peers) == 0 {
return nil
}
return &raftGroup{Name: groupNameForStream(peers, cfg.Storage), Storage: cfg.Storage, Peers: peers}
}
func (s *Server) jsClusteredStreamRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, config *StreamConfig) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}}
// Grab our jetstream account info.
acc.mu.RLock()
jsa := acc.js
acc.mu.RUnlock()
if jsa == nil {
resp.Error = jsNotEnabledErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
ccfg, err := checkStreamCfg(config)
if err != nil {
resp.Error = jsError(err)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
cfg := &ccfg
js.mu.RLock()
numStreams := len(cc.streams[acc.Name])
js.mu.RUnlock()
// Check for stream limits here before proposing. These need to be tracked from meta layer, not jsa.
jsa.mu.RLock()
exceeded := jsa.limits.MaxStreams > 0 && numStreams >= jsa.limits.MaxStreams
jsa.mu.RUnlock()
if exceeded {
resp.Error = jsError(fmt.Errorf("maximum number of streams reached"))
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Check for stream limits here before proposing.
if err := jsa.checkLimits(cfg); err != nil {
resp.Error = jsError(err)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Now process the request and proposal.
js.mu.Lock()
defer js.mu.Unlock()
if sa := js.streamAssignment(acc.Name, cfg.Name); sa != nil {
resp.Error = jsError(ErrJetStreamStreamAlreadyUsed)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Raft group selection and placement.
rg := cc.createGroupForStream(ci, cfg)
if rg == nil {
resp.Error = jsInsufficientErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Pick a preferred leader.
rg.setPreferred()
// Sync subject for post snapshot sync.
sa := &streamAssignment{Group: rg, Sync: syncSubjForStream(), Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
cc.meta.Propose(encodeAddStreamAssignment(sa))
}
func (s *Server) jsClusteredStreamUpdateRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, cfg *StreamConfig) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
// Now process the request and proposal.
js.mu.Lock()
defer js.mu.Unlock()
var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}}
osa := js.streamAssignment(acc.Name, cfg.Name)
if osa == nil {
resp.Error = jsNotFoundError(ErrJetStreamStreamNotFound)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
var newCfg *StreamConfig
if jsa := js.accounts[acc]; jsa != nil {
if ncfg, err := jsa.configUpdateCheck(osa.Config, cfg); err != nil {
resp.Error = jsError(err)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
} else {
newCfg = ncfg
}
} else {
resp.Error = jsNotEnabledErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Check for cluster changes that we want to error on.
if newCfg.Replicas != len(osa.Group.Peers) {
resp.Error = &ApiError{Code: 400, Description: "Replicas configuration can not be updated"}
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
if !reflect.DeepEqual(newCfg.Mirror, osa.Config.Mirror) {
resp.Error = &ApiError{Code: 400, Description: "Mirror configuration can not be updated"}
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
sa := &streamAssignment{Group: osa.Group, Config: newCfg, Subject: subject, Reply: reply, Client: ci}
cc.meta.Propose(encodeUpdateStreamAssignment(sa))
}
func (s *Server) jsClusteredStreamDeleteRequest(ci *ClientInfo, acc *Account, stream, subject, reply string, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
osa := js.streamAssignment(acc.Name, stream)
if osa == nil {
var resp = JSApiStreamDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamDeleteResponseType}}
resp.Error = jsNotFoundError(ErrJetStreamStreamNotFound)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Remove any remaining consumers as well.
for _, ca := range osa.consumers {
ca.Reply, ca.State = _EMPTY_, nil
cc.meta.Propose(encodeDeleteConsumerAssignment(ca))
}
sa := &streamAssignment{Group: osa.Group, Config: osa.Config, Subject: subject, Reply: reply, Client: ci}
cc.meta.Propose(encodeDeleteStreamAssignment(sa))
}
func (s *Server) jsClusteredStreamPurgeRequest(ci *ClientInfo, acc *Account, mset *stream, stream, subject, reply string, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
resp := JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
resp.Error = jsNotFoundError(ErrJetStreamStreamNotFound)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
if n := sa.Group.node; n != nil {
sp := &streamPurge{Stream: stream, LastSeq: mset.state().LastSeq, Subject: subject, Reply: reply, Client: ci}
n.Propose(encodeStreamPurge(sp))
} else if mset != nil {
var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
purged, err := mset.purge()
if err != nil {
resp.Error = jsError(err)
} else {
resp.Purged = purged
resp.Success = true
}
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
}
func (s *Server) jsClusteredStreamRestoreRequest(ci *ClientInfo, acc *Account, req *JSApiStreamRestoreRequest, stream, subject, reply string, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
cfg := &req.Config
resp := JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}}
if sa := js.streamAssignment(ci.serviceAccount(), cfg.Name); sa != nil {
resp.Error = jsError(ErrJetStreamStreamAlreadyUsed)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Raft group selection and placement.
rg := cc.createGroupForStream(ci, cfg)
if rg == nil {
resp.Error = jsInsufficientErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Pick a preferred leader.
rg.setPreferred()
sa := &streamAssignment{Group: rg, Sync: syncSubjForStream(), Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
// Now add in our restore state and pre-select a peer to handle the actual receipt of the snapshot.
sa.Restore = &req.State
cc.meta.Propose(encodeAddStreamAssignment(sa))
}
// This will do a scatter and gather operation for all streams for this account. This is only called from metadata leader.
// This will be running in a separate Go routine.
func (s *Server) jsClusteredStreamListRequest(acc *Account, ci *ClientInfo, offset int, subject, reply string, rmsg []byte) {
defer s.grWG.Done()
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
var streams []*streamAssignment
for _, sa := range cc.streams[acc.Name] {
streams = append(streams, sa)
}
// Needs to be sorted.
if len(streams) > 1 {
sort.Slice(streams, func(i, j int) bool {
return strings.Compare(streams[i].Config.Name, streams[j].Config.Name) < 0
})
}
scnt := len(streams)
if offset > scnt {
offset = scnt
}
if offset > 0 {
streams = streams[offset:]
}
if len(streams) > JSApiListLimit {
streams = streams[:JSApiListLimit]
}
var resp = JSApiStreamListResponse{
ApiResponse: ApiResponse{Type: JSApiStreamListResponseType},
Streams: make([]*StreamInfo, 0, len(streams)),
}
if len(streams) == 0 {
js.mu.Unlock()
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
return
}
// Create an inbox for our responses and send out our requests.
s.mu.Lock()
inbox := s.newRespInbox()
rc := make(chan *StreamInfo, len(streams))
// Store our handler.
s.sys.replies[inbox] = func(sub *subscription, _ *client, subject, _ string, msg []byte) {
var si StreamInfo
if err := json.Unmarshal(msg, &si); err != nil {
s.Warnf("Error unmarshaling clustered stream info response:%v", err)
return
}
select {
case rc <- &si:
default:
s.Warnf("Failed placing remote stream info result on internal channel")
}
}
s.mu.Unlock()
// Cleanup after.
defer func() {
s.mu.Lock()
if s.sys != nil && s.sys.replies != nil {
delete(s.sys.replies, inbox)
}
s.mu.Unlock()
}()
// Send out our requests here.
for _, sa := range streams {
isubj := fmt.Sprintf(clusterStreamInfoT, sa.Client.serviceAccount(), sa.Config.Name)
s.sendInternalMsgLocked(isubj, inbox, nil, nil)
}
// Don't hold lock.
js.mu.Unlock()
const timeout = 5 * time.Second
notActive := time.NewTimer(timeout)
defer notActive.Stop()
LOOP:
for {
select {
case <-s.quitCh:
return
case <-notActive.C:
s.Warnf("Did not receive all stream info results for %q", acc)
resp.Error = jsClusterIncompleteErr
break LOOP
case si := <-rc:
resp.Streams = append(resp.Streams, si)
// Check to see if we are done.
if len(resp.Streams) == len(streams) {
break LOOP
}
}
}
// Needs to be sorted as well.
if len(resp.Streams) > 1 {
sort.Slice(resp.Streams, func(i, j int) bool {
return strings.Compare(resp.Streams[i].Config.Name, resp.Streams[j].Config.Name) < 0
})
}
resp.Total = len(resp.Streams)
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
// This will do a scatter and gather operation for all consumers for this stream and account.
// This will be running in a separate Go routine.
func (s *Server) jsClusteredConsumerListRequest(acc *Account, ci *ClientInfo, offset int, stream, subject, reply string, rmsg []byte) {
defer s.grWG.Done()
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
var consumers []*consumerAssignment
if sas := cc.streams[acc.Name]; sas != nil {
if sa := sas[stream]; sa != nil {
// Copy over since we need to sort etc.
for _, ca := range sa.consumers {
consumers = append(consumers, ca)
}
}
}
// Needs to be sorted.
if len(consumers) > 1 {
sort.Slice(consumers, func(i, j int) bool {
return strings.Compare(consumers[i].Name, consumers[j].Name) < 0
})
}
ocnt := len(consumers)
if offset > ocnt {
offset = ocnt
}
if offset > 0 {
consumers = consumers[offset:]
}
if len(consumers) > JSApiListLimit {
consumers = consumers[:JSApiListLimit]
}
// Send out our requests here.
var resp = JSApiConsumerListResponse{
ApiResponse: ApiResponse{Type: JSApiConsumerListResponseType},
Consumers: []*ConsumerInfo{},
}
if len(consumers) == 0 {
js.mu.Unlock()
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
return
}
// Create an inbox for our responses and send out requests.
s.mu.Lock()
inbox := s.newRespInbox()
rc := make(chan *ConsumerInfo, len(consumers))
// Store our handler.
s.sys.replies[inbox] = func(sub *subscription, _ *client, subject, _ string, msg []byte) {
var ci ConsumerInfo
if err := json.Unmarshal(msg, &ci); err != nil {
s.Warnf("Error unmarshaling clustered consumer info response:%v", err)
return
}
select {
case rc <- &ci:
default:
s.Warnf("Failed placing consumer info result on internal chan")
}
}
s.mu.Unlock()
// Cleanup after.
defer func() {
s.mu.Lock()
if s.sys != nil && s.sys.replies != nil {
delete(s.sys.replies, inbox)
}
s.mu.Unlock()
}()
for _, ca := range consumers {
isubj := fmt.Sprintf(clusterConsumerInfoT, ca.Client.serviceAccount(), stream, ca.Name)
s.sendInternalMsgLocked(isubj, inbox, nil, nil)
}
js.mu.Unlock()
const timeout = 2 * time.Second
notActive := time.NewTimer(timeout)
defer notActive.Stop()
LOOP:
for {
select {
case <-s.quitCh:
return
case <-notActive.C:
s.Warnf("Did not receive all stream info results for %q", acc)
break LOOP
case ci := <-rc:
resp.Consumers = append(resp.Consumers, ci)
// Check to see if we are done.
if len(resp.Consumers) == len(consumers) {
break LOOP
}
}
}
// Needs to be sorted as well.
if len(resp.Consumers) > 1 {
sort.Slice(resp.Consumers, func(i, j int) bool {
return strings.Compare(resp.Consumers[i].Name, resp.Consumers[j].Name) < 0
})
}
resp.Total = len(resp.Consumers)
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
func encodeStreamPurge(sp *streamPurge) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(purgeStreamOp))
json.NewEncoder(&bb).Encode(sp)
return bb.Bytes()
}
func decodeStreamPurge(buf []byte) (*streamPurge, error) {
var sp streamPurge
err := json.Unmarshal(buf, &sp)
return &sp, err
}
func (s *Server) jsClusteredConsumerDeleteRequest(ci *ClientInfo, acc *Account, stream, consumer, subject, reply string, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
var resp = JSApiConsumerDeleteResponse{ApiResponse: ApiResponse{Type: JSApiConsumerDeleteResponseType}}
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
resp.Error = jsNotFoundError(ErrJetStreamStreamNotFound)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
if sa.consumers == nil {
resp.Error = jsNoConsumerErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
oca := sa.consumers[consumer]
if oca == nil {
resp.Error = jsNoConsumerErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
oca.deleted = true
ca := &consumerAssignment{Group: oca.Group, Stream: stream, Name: consumer, Config: oca.Config, Subject: subject, Reply: reply, Client: ci}
cc.meta.Propose(encodeDeleteConsumerAssignment(ca))
}
func encodeMsgDelete(md *streamMsgDelete) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(deleteMsgOp))
json.NewEncoder(&bb).Encode(md)
return bb.Bytes()
}
func decodeMsgDelete(buf []byte) (*streamMsgDelete, error) {
var md streamMsgDelete
err := json.Unmarshal(buf, &md)
return &md, err
}
func (s *Server) jsClusteredMsgDeleteRequest(ci *ClientInfo, acc *Account, mset *stream, stream, subject, reply string, req *JSApiMsgDeleteRequest, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
s.Debugf("Message delete failed, could not locate stream '%s > %s'", acc.Name, stream)
return
}
// Check for single replica items.
if n := sa.Group.node; n != nil {
md := &streamMsgDelete{Seq: req.Seq, NoErase: req.NoErase, Stream: stream, Subject: subject, Reply: reply, Client: ci}
n.Propose(encodeMsgDelete(md))
} else if mset != nil {
var err error
var removed bool
if req.NoErase {
removed, err = mset.removeMsg(req.Seq)
} else {
removed, err = mset.eraseMsg(req.Seq)
}
var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
if err != nil {
resp.Error = jsError(err)
} else if !removed {
resp.Error = &ApiError{Code: 400, Description: fmt.Sprintf("sequence [%d] not found", req.Seq)}
} else {
resp.Success = true
}
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
}
func encodeAddStreamAssignment(sa *streamAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(assignStreamOp))
json.NewEncoder(&bb).Encode(sa)
return bb.Bytes()
}
func encodeUpdateStreamAssignment(sa *streamAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(updateStreamOp))
json.NewEncoder(&bb).Encode(sa)
return bb.Bytes()
}
func encodeDeleteStreamAssignment(sa *streamAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(removeStreamOp))
json.NewEncoder(&bb).Encode(sa)
return bb.Bytes()
}
func decodeStreamAssignment(buf []byte) (*streamAssignment, error) {
var sa streamAssignment
err := json.Unmarshal(buf, &sa)
return &sa, err
}
// createGroupForConsumer will create a new group with same peer set as the stream.
func (cc *jetStreamCluster) createGroupForConsumer(sa *streamAssignment) *raftGroup {
peers := sa.Group.Peers
if len(peers) == 0 {
return nil
}
return &raftGroup{Name: groupNameForConsumer(peers, sa.Config.Storage), Storage: sa.Config.Storage, Peers: peers}
}
func (s *Server) jsClusteredConsumerRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, stream string, cfg *ConsumerConfig) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
// Lookup the stream assignment.
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
resp.Error = jsError(ErrJetStreamStreamNotFound)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
rg := cc.createGroupForConsumer(sa)
if rg == nil {
resp.Error = jsInsufficientErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Pick a preferred leader.
rg.setPreferred()
// We need to set the ephemeral here before replicating.
var oname string
if !isDurableConsumer(cfg) {
// We chose to have ephemerals be R=1.
rg.Peers = []string{rg.Preferred}
rg.Name = groupNameForConsumer(rg.Peers, rg.Storage)
// Make sure name is unique.
for {
oname = createConsumerName()
if sa.consumers != nil {
if sa.consumers[oname] != nil {
continue
}
}
break
}
} else {
oname = cfg.Durable
if ca := sa.consumers[oname]; ca != nil && !ca.deleted {
// This can be ok if delivery subject update.
if !reflect.DeepEqual(cfg, ca.Config) && !configsEqualSansDelivery(*cfg, *ca.Config) {
resp.Error = jsError(ErrJetStreamConsumerAlreadyUsed)
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
}
}
ca := &consumerAssignment{Group: rg, Stream: stream, Name: oname, Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
cc.meta.Propose(encodeAddConsumerAssignment(ca))
}
func encodeAddConsumerAssignment(ca *consumerAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(assignConsumerOp))
json.NewEncoder(&bb).Encode(ca)
return bb.Bytes()
}
func encodeDeleteConsumerAssignment(ca *consumerAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(removeConsumerOp))
json.NewEncoder(&bb).Encode(ca)
return bb.Bytes()
}
func decodeConsumerAssignment(buf []byte) (*consumerAssignment, error) {
var ca consumerAssignment
err := json.Unmarshal(buf, &ca)
return &ca, err
}
func encodeAddConsumerAssignmentCompressed(ca *consumerAssignment) []byte {
b, err := json.Marshal(ca)
if err != nil {
return nil
}
// TODO(dlc) - Streaming better approach here probably.
var bb bytes.Buffer
bb.WriteByte(byte(assignCompressedConsumerOp))
bb.Write(s2.Encode(nil, b))
return bb.Bytes()
}
func decodeConsumerAssignmentCompressed(buf []byte) (*consumerAssignment, error) {
var ca consumerAssignment
js, err := s2.Decode(nil, buf)
if err != nil {
return nil, err
}
err = json.Unmarshal(js, &ca)
return &ca, err
}
var errBadStreamMsg = errors.New("jetstream cluster bad replicated stream msg")
func decodeStreamMsg(buf []byte) (subject, reply string, hdr, msg []byte, lseq uint64, ts int64, err error) {
var le = binary.LittleEndian
if len(buf) < 26 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
lseq = le.Uint64(buf)
buf = buf[8:]
ts = int64(le.Uint64(buf))
buf = buf[8:]
sl := int(le.Uint16(buf))
buf = buf[2:]
if len(buf) < sl {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
subject = string(buf[:sl])
buf = buf[sl:]
if len(buf) < 2 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
rl := int(le.Uint16(buf))
buf = buf[2:]
if len(buf) < rl {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
reply = string(buf[:rl])
buf = buf[rl:]
if len(buf) < 2 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
hl := int(le.Uint16(buf))
buf = buf[2:]
if len(buf) < hl {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
hdr = buf[:hl]
buf = buf[hl:]
if len(buf) < 4 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
ml := int(le.Uint32(buf))
buf = buf[4:]
if len(buf) < ml {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
msg = buf[:ml]
return subject, reply, hdr, msg, lseq, ts, nil
}
func encodeStreamMsg(subject, reply string, hdr, msg []byte, lseq uint64, ts int64) []byte {
elen := 1 + 8 + 8 + len(subject) + len(reply) + len(hdr) + len(msg)
elen += (2 + 2 + 2 + 4) // Encoded lengths, 4bytes
// TODO(dlc) - check sizes of subject, reply and hdr, make sure uint16 ok.
buf := make([]byte, elen)
buf[0] = byte(streamMsgOp)
var le = binary.LittleEndian
wi := 1
le.PutUint64(buf[wi:], lseq)
wi += 8
le.PutUint64(buf[wi:], uint64(ts))
wi += 8
le.PutUint16(buf[wi:], uint16(len(subject)))
wi += 2
copy(buf[wi:], subject)
wi += len(subject)
le.PutUint16(buf[wi:], uint16(len(reply)))
wi += 2
copy(buf[wi:], reply)
wi += len(reply)
le.PutUint16(buf[wi:], uint16(len(hdr)))
wi += 2
if len(hdr) > 0 {
copy(buf[wi:], hdr)
wi += len(hdr)
}
le.PutUint32(buf[wi:], uint32(len(msg)))
wi += 4
if len(msg) > 0 {
copy(buf[wi:], msg)
wi += len(msg)
}
return buf[:wi]
}
// StreamSnapshot is used for snapshotting and out of band catch up in clustered mode.
type streamSnapshot struct {
Msgs uint64 `json:"messages"`
Bytes uint64 `json:"bytes"`
FirstSeq uint64 `json:"first_seq"`
LastSeq uint64 `json:"last_seq"`
Deleted []uint64 `json:"deleted,omitempty"`
}
// Grab a snapshot of a stream for clustered mode.
func (mset *stream) stateSnapshot() []byte {
mset.mu.RLock()
defer mset.mu.RUnlock()
state := mset.store.State()
snap := &streamSnapshot{
Msgs: state.Msgs,
Bytes: state.Bytes,
FirstSeq: state.FirstSeq,
LastSeq: state.LastSeq,
Deleted: state.Deleted,
}
b, _ := json.Marshal(snap)
return b
}
// processClusteredMsg will propose the inbound message to the underlying raft group.
func (mset *stream) processClusteredInboundMsg(subject, reply string, hdr, msg []byte) error {
// For possible error response.
var response []byte
mset.mu.RLock()
canRespond := !mset.cfg.NoAck && len(reply) > 0
s, jsa, st, rf, outq := mset.srv, mset.jsa, mset.cfg.Storage, mset.cfg.Replicas, mset.outq
maxMsgSize := int(mset.cfg.MaxMsgSize)
msetName := mset.cfg.Name
mset.mu.RUnlock()
// Check here pre-emptively if we have exceeded our account limits.
var exceeded bool
jsa.mu.RLock()
if st == MemoryStorage {
total := jsa.storeTotal + int64(memStoreMsgSize(subject, hdr, msg)*uint64(rf))
if jsa.limits.MaxMemory > 0 && total > jsa.limits.MaxMemory {
exceeded = true
}
} else {
total := jsa.storeTotal + int64(fileStoreMsgSize(subject, hdr, msg)*uint64(rf))
if jsa.limits.MaxStore > 0 && total > jsa.limits.MaxStore {
exceeded = true
}
}
jsa.mu.RUnlock()
// If we have exceeded our account limits go ahead and return.
if exceeded {
err := fmt.Errorf("JetStream resource limits exceeded for account: %q", jsa.acc().Name)
s.Warnf(err.Error())
if canRespond {
var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: mset.name()}}
resp.Error = &ApiError{Code: 400, Description: "resource limits exceeded for account"}
response, _ = json.Marshal(resp)
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, response, nil, 0, nil})
}
return err
}
// Check msgSize if we have a limit set there. Again this works if it goes through but better to be pre-emptive.
if maxMsgSize >= 0 && (len(hdr)+len(msg)) > maxMsgSize {
err := fmt.Errorf("JetStream message size exceeds limits for '%s > %s'", jsa.acc().Name, mset.cfg.Name)
s.Warnf(err.Error())
if canRespond {
var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: mset.name()}}
resp.Error = &ApiError{Code: 400, Description: "message size exceeds maximum allowed"}
response, _ = json.Marshal(resp)
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, response, nil, 0, nil})
}
return err
}
// Proceed with proposing this message.
mset.mu.Lock()
// We only use mset.clseq for clustering and in case we run ahead of actual commits.
// Check if we need to set initial value here
if mset.clseq == 0 {
mset.clseq = mset.lseq
}
// Do proposal.
err := mset.node.Propose(encodeStreamMsg(subject, reply, hdr, msg, mset.clseq, time.Now().UnixNano()))
if err != nil {
if canRespond {
var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: mset.cfg.Name}}
resp.Error = &ApiError{Code: 503, Description: err.Error()}
response, _ = json.Marshal(resp)
}
} else {
mset.clseq++
}
mset.mu.Unlock()
// If we errored out respond here.
if err != nil && canRespond {
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, response, nil, 0, nil})
}
if err != nil && isOutOfSpaceErr(err) {
s.handleOutOfSpace(msetName)
}
return err
}
// For requesting messages post raft snapshot to catch up streams post server restart.
// Any deleted msgs etc will be handled inline on catchup.
type streamSyncRequest struct {
FirstSeq uint64 `json:"first_seq"`
LastSeq uint64 `json:"last_seq"`
}
// Given a stream state that represents a snapshot, calculate the sync request based on our current state.
func (mset *stream) calculateSyncRequest(state *StreamState, snap *streamSnapshot) *streamSyncRequest {
// Quick check if we are already caught up.
if state.LastSeq >= snap.LastSeq {
return nil
}
return &streamSyncRequest{FirstSeq: state.LastSeq + 1, LastSeq: snap.LastSeq}
}
// processSnapshotDeletes will update our current store based on the snapshot
// but only processing deletes and new FirstSeq / purges.
func (mset *stream) processSnapshotDeletes(snap *streamSnapshot) {
state := mset.store.State()
// Adjust if FirstSeq has moved.
if snap.FirstSeq > state.FirstSeq {
mset.store.Compact(snap.FirstSeq)
state = mset.store.State()
}
// Range the deleted and delete if applicable.
for _, dseq := range snap.Deleted {
if dseq <= state.LastSeq {
mset.store.RemoveMsg(dseq)
}
}
}
func (mset *stream) setCatchingUp() {
mset.mu.Lock()
mset.catchup = true
mset.mu.Unlock()
}
func (mset *stream) clearCatchingUp() {
mset.mu.Lock()
mset.catchup = false
mset.mu.Unlock()
}
func (mset *stream) isCatchingUp() bool {
mset.mu.RLock()
defer mset.mu.RUnlock()
return mset.catchup
}
// Process a stream snapshot.
func (mset *stream) processSnapshot(snap *streamSnapshot) {
// Update any deletes, etc.
mset.processSnapshotDeletes(snap)
mset.mu.Lock()
state := mset.store.State()
sreq := mset.calculateSyncRequest(&state, snap)
s, subject, n := mset.srv, mset.sa.Sync, mset.node
msetName := mset.cfg.Name
mset.mu.Unlock()
// Just return if up to date..
if sreq == nil {
return
}
// Pause the apply channel for our raft group while we catch up.
n.PauseApply()
defer n.ResumeApply()
// Set our catchup state.
mset.setCatchingUp()
defer mset.clearCatchingUp()
js := s.getJetStream()
var sub *subscription
var err error
const activityInterval = 5 * time.Second
notActive := time.NewTimer(activityInterval)
defer notActive.Stop()
defer func() {
if sub != nil {
s.sysUnsubscribe(sub)
}
// Make sure any consumers are updated for the pending amounts.
mset.mu.Lock()
for _, o := range mset.consumers {
o.mu.Lock()
if o.isLeader() {
o.setInitialPending()
}
o.mu.Unlock()
}
mset.mu.Unlock()
}()
RETRY:
// If we have a sub clear that here.
if sub != nil {
s.sysUnsubscribe(sub)
sub = nil
}
// Grab sync request again on failures.
if sreq == nil {
mset.mu.Lock()
state := mset.store.State()
sreq = mset.calculateSyncRequest(&state, snap)
mset.mu.Unlock()
if sreq == nil {
return
}
}
// Used to transfer message from the wire to another Go routine internally.
type im struct {
msg []byte
reply string
}
msgsC := make(chan *im, 32768)
// Send our catchup request here.
reply := syncReplySubject()
sub, err = s.sysSubscribe(reply, func(_ *subscription, _ *client, _, reply string, msg []byte) {
// Make copies - https://github.com/go101/go101/wiki
// TODO(dlc) - Since we are using a buffer from the inbound client/route.
select {
case msgsC <- &im{append(msg[:0:0], msg...), reply}:
default:
s.Warnf("Failed to place catchup message onto internal channel: %d pending", len(msgsC))
return
}
})
if err != nil {
s.Errorf("Could not subscribe to stream catchup: %v", err)
return
}
b, _ := json.Marshal(sreq)
s.sendInternalMsgLocked(subject, reply, nil, b)
// Clear our sync request and capture last.
last := sreq.LastSeq
sreq = nil
// Run our own select loop here.
for qch, lch := n.QuitC(), n.LeadChangeC(); ; {
select {
case mrec := <-msgsC:
notActive.Reset(activityInterval)
msg := mrec.msg
// Check for eof signaling.
if len(msg) == 0 {
return
}
if lseq, err := mset.processCatchupMsg(msg); err == nil {
if lseq >= last {
return
}
} else if isOutOfSpaceErr(err) {
s.handleOutOfSpace(msetName)
return
} else {
goto RETRY
}
if mrec.reply != _EMPTY_ {
s.sendInternalMsgLocked(mrec.reply, _EMPTY_, nil, nil)
}
case <-notActive.C:
s.Warnf("Catchup for stream '%s > %s' stalled", mset.account(), mset.name())
notActive.Reset(activityInterval)
goto RETRY
case <-s.quitCh:
return
case <-qch:
return
case isLeader := <-lch:
js.processStreamLeaderChange(mset, isLeader)
}
}
}
// processCatchupMsg will be called to process out of band catchup msgs from a sync request.
func (mset *stream) processCatchupMsg(msg []byte) (uint64, error) {
if len(msg) == 0 || entryOp(msg[0]) != streamMsgOp {
// TODO(dlc) - This is error condition, log.
return 0, errors.New("bad catchup msg")
}
subj, _, hdr, msg, seq, ts, err := decodeStreamMsg(msg[1:])
if err != nil {
return 0, errors.New("bad catchup msg")
}
// Put into our store
// Messages to be skipped have no subject or timestamp.
// TODO(dlc) - formalize with skipMsgOp
if subj == _EMPTY_ && ts == 0 {
lseq := mset.store.SkipMsg()
if lseq != seq {
return 0, errors.New("wrong sequence for skipped msg")
}
} else if err := mset.store.StoreRawMsg(subj, hdr, msg, seq, ts); err != nil {
return 0, err
}
// Update our lseq.
mset.setLastSeq(seq)
return seq, nil
}
func (mset *stream) handleClusterSyncRequest(sub *subscription, c *client, subject, reply string, msg []byte) {
var sreq streamSyncRequest
if err := json.Unmarshal(msg, &sreq); err != nil {
// Log error.
return
}
mset.srv.startGoRoutine(func() { mset.runCatchup(reply, &sreq) })
}
// clusterInfo will report on the status of the raft group.
func (js *jetStream) clusterInfo(rg *raftGroup) *ClusterInfo {
if js == nil {
return nil
}
js.mu.RLock()
defer js.mu.RUnlock()
s := js.srv
if rg == nil || rg.node == nil {
return &ClusterInfo{
Name: s.ClusterName(),
Leader: s.Name(),
}
}
n := rg.node
ci := &ClusterInfo{
Name: s.ClusterName(),
Leader: s.serverNameForNode(n.GroupLeader()),
}
now := time.Now()
id, peers := n.ID(), n.Peers()
for _, rp := range peers {
if rp.ID != id && rg.isMember(rp.ID) {
lastSeen := now.Sub(rp.Last)
current := rp.Current
if current && lastSeen > lostQuorumInterval {
current = false
}
if sir, ok := s.nodeToInfo.Load(rp.ID); ok && sir != nil {
si := sir.(nodeInfo)
pi := &PeerInfo{Name: si.name, Current: current, Offline: si.offline, Active: lastSeen, Lag: rp.Lag}
ci.Replicas = append(ci.Replicas, pi)
}
}
}
return ci
}
func (mset *stream) handleClusterStreamInfoRequest(sub *subscription, c *client, subject, reply string, msg []byte) {
mset.mu.RLock()
sysc, js, config := mset.sysc, mset.srv.js, mset.cfg
mset.mu.RUnlock()
si := &StreamInfo{
Created: mset.createdTime(),
State: mset.state(),
Config: config,
Cluster: js.clusterInfo(mset.raftGroup()),
Sources: mset.sourcesInfo(),
Mirror: mset.mirrorInfo(),
}
sysc.sendInternalMsg(reply, _EMPTY_, nil, si)
}
func (mset *stream) runCatchup(sendSubject string, sreq *streamSyncRequest) {
s := mset.srv
defer s.grWG.Done()
const maxOutBytes = int64(2 * 1024 * 1024) // 2MB for now.
const maxOutMsgs = int32(16384)
outb := int64(0)
outm := int32(0)
// Flow control processing.
ackReplySize := func(subj string) int64 {
if li := strings.LastIndexByte(subj, btsep); li > 0 && li < len(subj) {
return parseAckReplyNum(subj[li+1:])
}
return 0
}
nextBatchC := make(chan struct{}, 1)
nextBatchC <- struct{}{}
// Setup ackReply for flow control.
ackReply := syncAckSubject()
ackSub, _ := s.sysSubscribe(ackReply, func(sub *subscription, c *client, subject, reply string, msg []byte) {
sz := ackReplySize(subject)
atomic.AddInt64(&outb, -sz)
atomic.AddInt32(&outm, -1)
select {
case nextBatchC <- struct{}{}:
default:
}
})
defer s.sysUnsubscribe(ackSub)
ackReplyT := strings.ReplaceAll(ackReply, ".*", ".%d")
// EOF
defer s.sendInternalMsgLocked(sendSubject, _EMPTY_, nil, nil)
const activityInterval = 5 * time.Second
notActive := time.NewTimer(activityInterval)
defer notActive.Stop()
// Setup sequences to walk through.
seq, last := sreq.FirstSeq, sreq.LastSeq
sendNextBatch := func() {
for ; seq <= last && atomic.LoadInt64(&outb) <= maxOutBytes && atomic.LoadInt32(&outm) <= maxOutMsgs; seq++ {
subj, hdr, msg, ts, err := mset.store.LoadMsg(seq)
// if this is not a deleted msg, bail out.
if err != nil && err != ErrStoreMsgNotFound && err != errDeletedMsg {
// break, something changed.
seq = last + 1
return
}
// S2?
em := encodeStreamMsg(subj, _EMPTY_, hdr, msg, seq, ts)
// Place size in reply subject for flow control.
reply := fmt.Sprintf(ackReplyT, len(em))
atomic.AddInt64(&outb, int64(len(em)))
atomic.AddInt32(&outm, 1)
s.sendInternalMsgLocked(sendSubject, reply, nil, em)
}
}
// Grab stream quit channel.
mset.mu.RLock()
qch := mset.qch
mset.mu.RUnlock()
if qch == nil {
return
}
// Run as long as we are still active and need catchup.
// FIXME(dlc) - Purge event? Stream delete?
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case <-notActive.C:
s.Warnf("Catchup for stream '%s > %s' stalled", mset.account(), mset.name())
return
case <-nextBatchC:
// Update our activity timer.
notActive.Reset(activityInterval)
sendNextBatch()
// Check if we are finished.
if seq > last {
s.Debugf("Done resync for stream '%s > %s'", mset.account(), mset.name())
return
}
}
}
}
func syncSubjForStream() string {
return syncSubject("$JSC.SYNC")
}
func syncReplySubject() string {
return syncSubject("$JSC.R")
}
func infoReplySubject() string {
return syncSubject("$JSC.R")
}
func syncAckSubject() string {
return syncSubject("$JSC.ACK") + ".*"
}
func syncSubject(pre string) string {
var sb strings.Builder
sb.WriteString(pre)
sb.WriteByte(btsep)
var b [replySuffixLen]byte
rn := rand.Int63()
for i, l := 0, rn; i < len(b); i++ {
b[i] = digits[l%base]
l /= base
}
sb.Write(b[:])
return sb.String()
}
const (
clusterStreamInfoT = "$JSC.SI.%s.%s"
clusterConsumerInfoT = "$JSC.CI.%s.%s.%s"
jsaUpdatesSubT = "$JSC.ARU.%s.*"
jsaUpdatesPubT = "$JSC.ARU.%s.%s"
)
| 1 | 12,784 | During our zoom and working on this, I said that I believe it was set to 64MB, not 32MB, but the diff shows that I was wrong. So we could change it back to 32MB. | nats-io-nats-server | go |
@@ -1,5 +1,7 @@
package platform
+import "log"
+
// App is an interface apps for Drud Local must implement to use shared functionality
type App interface {
Init(string) error | 1 | package platform
// App is an interface apps for Drud Local must implement to use shared functionality
type App interface {
Init(string) error
Describe() (string, error)
GetType() string
ContainerPrefix() string
ContainerName() string
AppRoot() string
GetName() string
Start() error
Stop() error
DockerEnv()
DockerComposeYAMLPath() string
Down() error
Config() error
Wait(string) error
HostName() string
URL() string
ImportDB(string) error
ImportFiles(string) error
}
// AppBase is the parent type for all local app implementations
type AppBase struct {
Plugin string
Archive string //absolute path to the downloaded archive
WebPublicPort int64
DbPublicPort int64
Status string
}
// PluginMap maps the name of the plugins to their implementation.
var PluginMap = map[string]App{
"local": &LocalApp{},
}
| 1 | 10,993 | Here I thought you always insisted on ` log "github.com/Sirupsen/logrus" ` :) I might do a PR that just globally switches that out wherever we have log. | drud-ddev | php |
@@ -495,10 +495,9 @@ type KeyMetadata interface {
GetTlfHandle() *TlfHandle
// HasKeyForUser returns whether or not the given user has
- // keys for at least one device at the given key
- // generation. Returns false if the TLF is public, or if the
- // given key generation is invalid.
- HasKeyForUser(keyGen KeyGen, user keybase1.UID) bool
+ // keys for at least one device. Returns an error if the TLF
+ // is public.
+ HasKeyForUser(user keybase1.UID) (bool, error)
// GetTLFCryptKeyParams returns all the necessary info to
// construct the TLF crypt key for the given key generation, | 1 | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"time"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfsblock"
"github.com/keybase/kbfs/kbfscodec"
"github.com/keybase/kbfs/kbfscrypto"
"github.com/keybase/kbfs/tlf"
metrics "github.com/rcrowley/go-metrics"
"golang.org/x/net/context"
)
type dataVersioner interface {
// DataVersion returns the data version for this block
DataVersion() DataVer
}
type logMaker interface {
MakeLogger(module string) logger.Logger
}
type blockCacher interface {
BlockCache() BlockCache
}
// Block just needs to be (de)serialized using msgpack
type Block interface {
dataVersioner
// GetEncodedSize returns the encoded size of this block, but only
// if it has been previously set; otherwise it returns 0.
GetEncodedSize() uint32
// SetEncodedSize sets the encoded size of this block, locally
// caching it. The encoded size is not serialized.
SetEncodedSize(size uint32)
// NewEmpty returns a new block of the same type as this block
NewEmpty() Block
// Set sets this block to the same value as the passed-in block
Set(other Block, codec kbfscodec.Codec)
}
// NodeID is a unique but transient ID for a Node. That is, two Node
// objects in memory at the same time represent the same file or
// directory if and only if their NodeIDs are equal (by pointer).
type NodeID interface {
// ParentID returns the NodeID of the directory containing the
// pointed-to file or directory, or nil if none exists.
ParentID() NodeID
}
// Node represents a direct pointer to a file or directory in KBFS.
// It is somewhat like an inode in a regular file system. Users of
// KBFS can use Node as a handle when accessing files or directories
// they have previously looked up.
type Node interface {
// GetID returns the ID of this Node. This should be used as a
// map key instead of the Node itself.
GetID() NodeID
// GetFolderBranch returns the folder ID and branch for this Node.
GetFolderBranch() FolderBranch
// GetBasename returns the current basename of the node, or ""
// if the node has been unlinked.
GetBasename() string
}
// KBFSOps handles all file system operations. Expands all indirect
// pointers. Operations that modify the server data change all the
// block IDs along the path, and so must return a path with the new
// BlockIds so the caller can update their references.
//
// KBFSOps implementations must guarantee goroutine-safety of calls on
// a per-top-level-folder basis.
//
// There are two types of operations that could block:
// * remote-sync operations, that need to synchronously update the
// MD for the corresponding top-level folder. When these
// operations return successfully, they will have guaranteed to
// have successfully written the modification to the KBFS servers.
// * remote-access operations, that don't sync any modifications to KBFS
// servers, but may block on reading data from the servers.
//
// KBFSOps implementations are supposed to give git-like consistency
// semantics for modification operations; they will be visible to
// other clients immediately after the remote-sync operations succeed,
// if and only if there was no other intervening modification to the
// same folder. If not, the change will be sync'd to the server in a
// special per-device "unmerged" area before the operation succeeds.
// In this case, the modification will not be visible to other clients
// until the KBFS code on this device performs automatic conflict
// resolution in the background.
//
// All methods take a Context (see https://blog.golang.org/context),
// and if that context is cancelled during the operation, KBFSOps will
// abort any blocking calls and return ctx.Err(). Any notifications
// resulting from an operation will also include this ctx (or a
// Context derived from it), allowing the caller to determine whether
// the notification is a result of their own action or an external
// action.
type KBFSOps interface {
// GetFavorites returns the logged-in user's list of favorite
// top-level folders. This is a remote-access operation.
GetFavorites(ctx context.Context) ([]Favorite, error)
// RefreshCachedFavorites tells the instances to forget any cached
// favorites list and fetch a new list from the server. The
// effects are asychronous; if there's an error refreshing the
// favorites, the cached favorites will become empty.
RefreshCachedFavorites(ctx context.Context)
// AddFavorite adds the favorite to both the server and
// the local cache.
AddFavorite(ctx context.Context, fav Favorite) error
// DeleteFavorite deletes the favorite from both the server and
// the local cache. Idempotent, so it succeeds even if the folder
// isn't favorited.
DeleteFavorite(ctx context.Context, fav Favorite) error
// GetTLFCryptKeys gets crypt key of all generations as well as
// TLF ID for tlfHandle. The returned keys (the keys slice) are ordered by
// generation, starting with the key for FirstValidKeyGen.
GetTLFCryptKeys(ctx context.Context, tlfHandle *TlfHandle) (
keys []kbfscrypto.TLFCryptKey, id tlf.ID, err error)
// GetTLFID gets the TLF ID for tlfHandle.
GetTLFID(ctx context.Context, tlfHandle *TlfHandle) (tlf.ID, error)
// GetOrCreateRootNode returns the root node and root entry
// info associated with the given TLF handle and branch, if
// the logged-in user has read permissions to the top-level
// folder. It creates the folder if one doesn't exist yet (and
// branch == MasterBranch), and the logged-in user has write
// permissions to the top-level folder. This is a
// remote-access operation.
GetOrCreateRootNode(
ctx context.Context, h *TlfHandle, branch BranchName) (
node Node, ei EntryInfo, err error)
// GetRootNode is like GetOrCreateRootNode but if the root node
// does not exist it will return a nil Node and not create it.
GetRootNode(
ctx context.Context, h *TlfHandle, branch BranchName) (
node Node, ei EntryInfo, err error)
// GetDirChildren returns a map of children in the directory,
// mapped to their EntryInfo, if the logged-in user has read
// permission for the top-level folder. This is a remote-access
// operation.
GetDirChildren(ctx context.Context, dir Node) (map[string]EntryInfo, error)
// Lookup returns the Node and entry info associated with a
// given name in a directory, if the logged-in user has read
// permissions to the top-level folder. The returned Node is nil
// if the name is a symlink. This is a remote-access operation.
Lookup(ctx context.Context, dir Node, name string) (Node, EntryInfo, error)
// Stat returns the entry info associated with a
// given Node, if the logged-in user has read permissions to the
// top-level folder. This is a remote-access operation.
Stat(ctx context.Context, node Node) (EntryInfo, error)
// CreateDir creates a new subdirectory under the given node, if
// the logged-in user has write permission to the top-level
// folder. Returns the new Node for the created subdirectory, and
// its new entry info. This is a remote-sync operation.
CreateDir(ctx context.Context, dir Node, name string) (
Node, EntryInfo, error)
// CreateFile creates a new file under the given node, if the
// logged-in user has write permission to the top-level folder.
// Returns the new Node for the created file, and its new
// entry info. excl (when implemented) specifies whether this is an exclusive
// create. Semantically setting excl to WithExcl is like O_CREAT|O_EXCL in a
// Unix open() call.
//
// This is a remote-sync operation.
CreateFile(ctx context.Context, dir Node, name string, isExec bool, excl Excl) (
Node, EntryInfo, error)
// CreateLink creates a new symlink under the given node, if the
// logged-in user has write permission to the top-level folder.
// Returns the new entry info for the created symlink. This
// is a remote-sync operation.
CreateLink(ctx context.Context, dir Node, fromName string, toPath string) (
EntryInfo, error)
// RemoveDir removes the subdirectory represented by the given
// node, if the logged-in user has write permission to the
// top-level folder. Will return an error if the subdirectory is
// not empty. This is a remote-sync operation.
RemoveDir(ctx context.Context, dir Node, dirName string) error
// RemoveEntry removes the directory entry represented by the
// given node, if the logged-in user has write permission to the
// top-level folder. This is a remote-sync operation.
RemoveEntry(ctx context.Context, dir Node, name string) error
// Rename performs an atomic rename operation with a given
// top-level folder if the logged-in user has write permission to
// that folder, and will return an error if nodes from different
// folders are passed in. Also returns an error if the new name
// already has an entry corresponding to an existing directory
// (only non-dir types may be renamed over). This is a
// remote-sync operation.
Rename(ctx context.Context, oldParent Node, oldName string, newParent Node,
newName string) error
// Read fills in the given buffer with data from the file at the
// given node starting at the given offset, if the logged-in user
// has read permission to the top-level folder. The read data
// reflects any outstanding writes and truncates to that file that
// have been written through this KBFSOps object, even if those
// writes have not yet been sync'd. There is no guarantee that
// Read returns all of the requested data; it will return the
// number of bytes that it wrote to the dest buffer. Reads on an
// unlinked file may or may not succeed, depending on whether or
// not the data has been cached locally. If (0, nil) is returned,
// that means EOF has been reached. This is a remote-access
// operation.
Read(ctx context.Context, file Node, dest []byte, off int64) (int64, error)
// Write modifies the file at the given node, by writing the given
// buffer at the given offset within the file, if the logged-in
// user has write permission to the top-level folder. It
// overwrites any data already there, and extends the file size as
// necessary to accomodate the new data. It guarantees to write
// the entire buffer in one operation. Writes on an unlinked file
// may or may not succeed as no-ops, depending on whether or not
// the necessary blocks have been locally cached. This is a
// remote-access operation.
Write(ctx context.Context, file Node, data []byte, off int64) error
// Truncate modifies the file at the given node, by either
// shrinking or extending its size to match the given size, if the
// logged-in user has write permission to the top-level folder.
// If extending the file, it pads the new data with 0s. Truncates
// on an unlinked file may or may not succeed as no-ops, depending
// on whether or not the necessary blocks have been locally
// cached. This is a remote-access operation.
Truncate(ctx context.Context, file Node, size uint64) error
// SetEx turns on or off the executable bit on the file
// represented by a given node, if the logged-in user has write
// permissions to the top-level folder. This is a remote-sync
// operation.
SetEx(ctx context.Context, file Node, ex bool) error
// SetMtime sets the modification time on the file represented by
// a given node, if the logged-in user has write permissions to
// the top-level folder. If mtime is nil, it is a noop. This is
// a remote-sync operation.
SetMtime(ctx context.Context, file Node, mtime *time.Time) error
// Sync flushes all outstanding writes and truncates for the given
// file to the KBFS servers, if the logged-in user has write
// permissions to the top-level folder. If done through a file
// system interface, this may include modifications done via
// multiple file handles. This is a remote-sync operation.
Sync(ctx context.Context, file Node) error
// FolderStatus returns the status of a particular folder/branch, along
// with a channel that will be closed when the status has been
// updated (to eliminate the need for polling this method).
FolderStatus(ctx context.Context, folderBranch FolderBranch) (
FolderBranchStatus, <-chan StatusUpdate, error)
// Status returns the status of KBFS, along with a channel that will be
// closed when the status has been updated (to eliminate the need for
// polling this method). KBFSStatus can be non-empty even if there is an
// error.
Status(ctx context.Context) (
KBFSStatus, <-chan StatusUpdate, error)
// UnstageForTesting clears out this device's staged state, if
// any, and fast-forwards to the current head of this
// folder-branch.
UnstageForTesting(ctx context.Context, folderBranch FolderBranch) error
// Rekey rekeys this folder.
Rekey(ctx context.Context, id tlf.ID) error
// SyncFromServerForTesting blocks until the local client has
// contacted the server and guaranteed that all known updates
// for the given top-level folder have been applied locally
// (and notifications sent out to any observers). It returns
// an error if this folder-branch is currently unmerged or
// dirty locally.
SyncFromServerForTesting(ctx context.Context, folderBranch FolderBranch) error
// GetUpdateHistory returns a complete history of all the merged
// updates of the given folder, in a data structure that's
// suitable for encoding directly into JSON. This is an expensive
// operation, and should only be used for ocassional debugging.
// Note that the history does not include any unmerged changes or
// outstanding writes from the local device.
GetUpdateHistory(ctx context.Context, folderBranch FolderBranch) (
history TLFUpdateHistory, err error)
// GetEditHistory returns a clustered list of the most recent file
// edits by each of the valid writers of the given folder. users
// looking to get updates to this list can register as an observer
// for the folder.
GetEditHistory(ctx context.Context, folderBranch FolderBranch) (
edits TlfWriterEdits, err error)
// GetNodeMetadata gets metadata associated with a Node.
GetNodeMetadata(ctx context.Context, node Node) (NodeMetadata, error)
// Shutdown is called to clean up any resources associated with
// this KBFSOps instance.
Shutdown(ctx context.Context) error
// PushConnectionStatusChange updates the status of a service for
// human readable connection status tracking.
PushConnectionStatusChange(service string, newStatus error)
// PushStatusChange causes Status listeners to be notified via closing
// the status channel.
PushStatusChange()
}
// KeybaseService is an interface for communicating with the keybase
// service.
type KeybaseService interface {
// Resolve, given an assertion, resolves it to a username/UID
// pair. The username <-> UID mapping is trusted and
// immutable, so it can be cached. If the assertion is just
// the username or a UID assertion, then the resolution can
// also be trusted. If the returned pair is equal to that of
// the current session, then it can also be
// trusted. Otherwise, Identify() needs to be called on the
// assertion before the assertion -> (username, UID) mapping
// can be trusted.
Resolve(ctx context.Context, assertion string) (
libkb.NormalizedUsername, keybase1.UID, error)
// Identify, given an assertion, returns a UserInfo struct
// with the user that matches that assertion, or an error
// otherwise. The reason string is displayed on any tracker
// popups spawned.
Identify(ctx context.Context, assertion, reason string) (UserInfo, error)
// LoadUserPlusKeys returns a UserInfo struct for a
// user with the specified UID.
// If you have the UID for a user and don't require Identify to
// validate an assertion or the identity of a user, use this to
// get UserInfo structs as it is much cheaper than Identify.
LoadUserPlusKeys(ctx context.Context, uid keybase1.UID) (UserInfo, error)
// LoadUnverifiedKeys returns a list of unverified public keys. They are the union
// of all known public keys associated with the account and the currently verified
// keys currently part of the user's sigchain.
LoadUnverifiedKeys(ctx context.Context, uid keybase1.UID) (
[]keybase1.PublicKey, error)
// CurrentSession returns a SessionInfo struct with all the
// information for the current session, or an error otherwise.
CurrentSession(ctx context.Context, sessionID int) (SessionInfo, error)
// FavoriteAdd adds the given folder to the list of favorites.
FavoriteAdd(ctx context.Context, folder keybase1.Folder) error
// FavoriteAdd removes the given folder from the list of
// favorites.
FavoriteDelete(ctx context.Context, folder keybase1.Folder) error
// FavoriteList returns the current list of favorites.
FavoriteList(ctx context.Context, sessionID int) ([]keybase1.Folder, error)
// Notify sends a filesystem notification.
Notify(ctx context.Context, notification *keybase1.FSNotification) error
// NotifySyncStatus sends a sync status notification.
NotifySyncStatus(ctx context.Context,
status *keybase1.FSPathSyncStatus) error
// FlushUserFromLocalCache instructs this layer to clear any
// KBFS-side, locally-cached information about the given user.
// This does NOT involve communication with the daemon, this is
// just to force future calls loading this user to fall through to
// the daemon itself, rather than being served from the cache.
FlushUserFromLocalCache(ctx context.Context, uid keybase1.UID)
// FlushUserUnverifiedKeysFromLocalCache instructs this layer to clear any
// KBFS-side, locally-cached unverified keys for the given user.
FlushUserUnverifiedKeysFromLocalCache(ctx context.Context, uid keybase1.UID)
// TODO: Add CryptoClient methods, too.
// EstablishMountDir asks the service for the current mount path
// and sets it if not established.
EstablishMountDir(ctx context.Context) (string, error)
// Shutdown frees any resources associated with this
// instance. No other methods may be called after this is
// called.
Shutdown()
}
// KeybaseServiceCn defines methods needed to construct KeybaseService
// and Crypto implementations.
type KeybaseServiceCn interface {
NewKeybaseService(config Config, params InitParams, ctx Context, log logger.Logger) (KeybaseService, error)
NewCrypto(config Config, params InitParams, ctx Context, log logger.Logger) (Crypto, error)
}
type resolver interface {
// Resolve, given an assertion, resolves it to a username/UID
// pair. The username <-> UID mapping is trusted and
// immutable, so it can be cached. If the assertion is just
// the username or a UID assertion, then the resolution can
// also be trusted. If the returned pair is equal to that of
// the current session, then it can also be
// trusted. Otherwise, Identify() needs to be called on the
// assertion before the assertion -> (username, UID) mapping
// can be trusted.
Resolve(ctx context.Context, assertion string) (
libkb.NormalizedUsername, keybase1.UID, error)
}
type identifier interface {
// Identify resolves an assertion (which could also be a
// username) to a UserInfo struct, spawning tracker popups if
// necessary. The reason string is displayed on any tracker
// popups spawned.
Identify(ctx context.Context, assertion, reason string) (UserInfo, error)
}
type normalizedUsernameGetter interface {
// GetNormalizedUsername returns the normalized username
// corresponding to the given UID.
GetNormalizedUsername(ctx context.Context, uid keybase1.UID) (libkb.NormalizedUsername, error)
}
type currentInfoGetter interface {
// GetCurrentToken gets the current keybase session token.
GetCurrentToken(ctx context.Context) (string, error)
// GetCurrentUserInfo gets the name and UID of the current
// logged-in user.
GetCurrentUserInfo(ctx context.Context) (
libkb.NormalizedUsername, keybase1.UID, error)
// GetCurrentCryptPublicKey gets the crypt public key for the
// currently-active device.
GetCurrentCryptPublicKey(ctx context.Context) (
kbfscrypto.CryptPublicKey, error)
// GetCurrentVerifyingKey gets the public key used for signing for the
// currently-active device.
GetCurrentVerifyingKey(ctx context.Context) (
kbfscrypto.VerifyingKey, error)
}
// KBPKI interacts with the Keybase daemon to fetch user info.
type KBPKI interface {
currentInfoGetter
resolver
identifier
normalizedUsernameGetter
// HasVerifyingKey returns nil if the given user has the given
// VerifyingKey, and an error otherwise.
HasVerifyingKey(ctx context.Context, uid keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey,
atServerTime time.Time) error
// HasUnverifiedVerifyingKey returns nil if the given user has the given
// unverified VerifyingKey, and an error otherwise. Note that any match
// is with a key not verified to be currently connected to the user via
// their sigchain. This is currently only used to verify finalized or
// reset TLFs. Further note that unverified keys is a super set of
// verified keys.
HasUnverifiedVerifyingKey(ctx context.Context, uid keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey) error
// GetCryptPublicKeys gets all of a user's crypt public keys (including
// paper keys).
GetCryptPublicKeys(ctx context.Context, uid keybase1.UID) (
[]kbfscrypto.CryptPublicKey, error)
// TODO: Split the methods below off into a separate
// FavoriteOps interface.
// FavoriteAdd adds folder to the list of the logged in user's
// favorite folders. It is idempotent.
FavoriteAdd(ctx context.Context, folder keybase1.Folder) error
// FavoriteDelete deletes folder from the list of the logged in user's
// favorite folders. It is idempotent.
FavoriteDelete(ctx context.Context, folder keybase1.Folder) error
// FavoriteList returns the list of all favorite folders for
// the logged in user.
FavoriteList(ctx context.Context) ([]keybase1.Folder, error)
// Notify sends a filesystem notification.
Notify(ctx context.Context, notification *keybase1.FSNotification) error
}
// KeyMetadata is an interface for something that holds key
// information. This is usually implemented by RootMetadata.
type KeyMetadata interface {
// TlfID returns the ID of the TLF for which this object holds
// key info.
TlfID() tlf.ID
// LatestKeyGeneration returns the most recent key generation
// with key data in this object, or PublicKeyGen if this TLF
// is public.
LatestKeyGeneration() KeyGen
// GetTlfHandle returns the handle for the TLF. It must not
// return nil.
//
// TODO: Remove the need for this function in this interface,
// so that BareRootMetadata can implement this interface
// fully.
GetTlfHandle() *TlfHandle
// HasKeyForUser returns whether or not the given user has
// keys for at least one device at the given key
// generation. Returns false if the TLF is public, or if the
// given key generation is invalid.
HasKeyForUser(keyGen KeyGen, user keybase1.UID) bool
// GetTLFCryptKeyParams returns all the necessary info to
// construct the TLF crypt key for the given key generation,
// user, and device (identified by its crypt public key), or
// false if not found. This returns an error if the TLF is
// public.
GetTLFCryptKeyParams(
keyGen KeyGen, user keybase1.UID,
key kbfscrypto.CryptPublicKey) (
kbfscrypto.TLFEphemeralPublicKey,
EncryptedTLFCryptKeyClientHalf,
TLFCryptKeyServerHalfID, bool, error)
// StoresHistoricTLFCryptKeys returns whether or not history keys are
// symmetrically encrypted; if not, they're encrypted per-device.
StoresHistoricTLFCryptKeys() bool
// GetHistoricTLFCryptKey attempts to symmetrically decrypt the key at the given
// generation using the current generation's TLFCryptKey.
GetHistoricTLFCryptKey(c cryptoPure, keyGen KeyGen,
currentKey kbfscrypto.TLFCryptKey) (
kbfscrypto.TLFCryptKey, error)
}
type encryptionKeyGetter interface {
// GetTLFCryptKeyForEncryption gets the crypt key to use for
// encryption (i.e., with the latest key generation) for the
// TLF with the given metadata.
GetTLFCryptKeyForEncryption(ctx context.Context, kmd KeyMetadata) (
kbfscrypto.TLFCryptKey, error)
}
type mdDecryptionKeyGetter interface {
// GetTLFCryptKeyForMDDecryption gets the crypt key to use for the
// TLF with the given metadata to decrypt the private portion of
// the metadata. It finds the appropriate key from mdWithKeys
// (which in most cases is the same as mdToDecrypt) if it's not
// already cached.
GetTLFCryptKeyForMDDecryption(ctx context.Context,
kmdToDecrypt, kmdWithKeys KeyMetadata) (
kbfscrypto.TLFCryptKey, error)
}
type blockDecryptionKeyGetter interface {
// GetTLFCryptKeyForBlockDecryption gets the crypt key to use
// for the TLF with the given metadata to decrypt the block
// pointed to by the given pointer.
GetTLFCryptKeyForBlockDecryption(ctx context.Context, kmd KeyMetadata,
blockPtr BlockPointer) (kbfscrypto.TLFCryptKey, error)
}
type blockKeyGetter interface {
encryptionKeyGetter
blockDecryptionKeyGetter
}
// KeyManager fetches and constructs the keys needed for KBFS file
// operations.
type KeyManager interface {
blockKeyGetter
mdDecryptionKeyGetter
// GetTLFCryptKeyOfAllGenerations gets the crypt keys of all generations
// for current devices. keys contains crypt keys from all generations, in
// order, starting from FirstValidKeyGen.
GetTLFCryptKeyOfAllGenerations(ctx context.Context, kmd KeyMetadata) (
keys []kbfscrypto.TLFCryptKey, err error)
// Rekey checks the given MD object, if it is a private TLF,
// against the current set of device keys for all valid
// readers and writers. If there are any new devices, it
// updates all existing key generations to include the new
// devices. If there are devices that have been removed, it
// creates a new epoch of keys for the TLF. If there was an
// error, or the RootMetadata wasn't changed, it returns false.
// Otherwise, it returns true. If a new key generation is
// added the second return value points to this new key. This
// is to allow for caching of the TLF crypt key only after a
// successful merged write of the metadata. Otherwise we could
// prematurely pollute the key cache.
//
// If the given MD object is a public TLF, it simply updates
// the TLF's handle with any newly-resolved writers.
//
// If promptPaper is set, prompts for any unlocked paper keys.
// promptPaper shouldn't be set if md is for a public TLF.
Rekey(ctx context.Context, md *RootMetadata, promptPaper bool) (
bool, *kbfscrypto.TLFCryptKey, error)
}
// Reporter exports events (asynchronously) to any number of sinks
type Reporter interface {
// ReportErr records that a given error happened.
ReportErr(ctx context.Context, tlfName CanonicalTlfName, public bool,
mode ErrorModeType, err error)
// AllKnownErrors returns all errors known to this Reporter.
AllKnownErrors() []ReportedError
// Notify sends the given notification to any sink.
Notify(ctx context.Context, notification *keybase1.FSNotification)
// NotifySyncStatus sends the given path sync status to any sink.
NotifySyncStatus(ctx context.Context, status *keybase1.FSPathSyncStatus)
// Shutdown frees any resources allocated by a Reporter.
Shutdown()
}
// MDCache gets and puts plaintext top-level metadata into the cache.
type MDCache interface {
// Get gets the metadata object associated with the given TLF ID,
// revision number, and branch ID (NullBranchID for merged MD).
Get(tlf tlf.ID, rev MetadataRevision, bid BranchID) (ImmutableRootMetadata, error)
// Put stores the metadata object.
Put(md ImmutableRootMetadata) error
// Delete removes the given metadata object from the cache if it exists.
Delete(tlf tlf.ID, rev MetadataRevision, bid BranchID)
// Replace replaces the entry matching the md under the old branch
// ID with the new one. If the old entry doesn't exist, this is
// equivalent to a Put.
Replace(newRmd ImmutableRootMetadata, oldBID BranchID) error
}
// KeyCache handles caching for both TLFCryptKeys and BlockCryptKeys.
type KeyCache interface {
// GetTLFCryptKey gets the crypt key for the given TLF.
GetTLFCryptKey(tlf.ID, KeyGen) (kbfscrypto.TLFCryptKey, error)
// PutTLFCryptKey stores the crypt key for the given TLF.
PutTLFCryptKey(tlf.ID, KeyGen, kbfscrypto.TLFCryptKey) error
}
// BlockCacheLifetime denotes the lifetime of an entry in BlockCache.
type BlockCacheLifetime int
const (
// NoCacheEntry means that the entry will not be cached.
NoCacheEntry BlockCacheLifetime = iota
// TransientEntry means that the cache entry may be evicted at
// any time.
TransientEntry
// PermanentEntry means that the cache entry must remain until
// explicitly removed from the cache.
PermanentEntry
)
// BlockCacheSimple gets and puts plaintext dir blocks and file blocks into
// a cache. These blocks are immutable and identified by their
// content hash.
type BlockCacheSimple interface {
// Get gets the block associated with the given block ID.
Get(ptr BlockPointer) (Block, error)
// Put stores the final (content-addressable) block associated
// with the given block ID. If lifetime is TransientEntry,
// then it is assumed that the block exists on the server and
// the entry may be evicted from the cache at any time. If
// lifetime is PermanentEntry, then it is assumed that the
// block doesn't exist on the server and must remain in the
// cache until explicitly removed. As an intermediary state,
// as when a block is being sent to the server, the block may
// be put into the cache both with TransientEntry and
// PermanentEntry -- these are two separate entries. This is
// fine, since the block should be the same.
Put(ptr BlockPointer, tlf tlf.ID, block Block,
lifetime BlockCacheLifetime) error
}
// BlockCache specifies the interface of BlockCacheSimple, and also more
// advanced and internal methods.
type BlockCache interface {
BlockCacheSimple
// CheckForKnownPtr sees whether this cache has a transient
// entry for the given file block, which must be a direct file
// block containing data). Returns the full BlockPointer
// associated with that ID, including key and data versions.
// If no ID is known, return an uninitialized BlockPointer and
// a nil error.
CheckForKnownPtr(tlf tlf.ID, block *FileBlock) (BlockPointer, error)
// DeleteTransient removes the transient entry for the given
// pointer from the cache, as well as any cached IDs so the block
// won't be reused.
DeleteTransient(ptr BlockPointer, tlf tlf.ID) error
// Delete removes the permanent entry for the non-dirty block
// associated with the given block ID from the cache. No
// error is returned if no block exists for the given ID.
DeletePermanent(id kbfsblock.ID) error
// DeleteKnownPtr removes the cached ID for the given file
// block. It does not remove the block itself.
DeleteKnownPtr(tlf tlf.ID, block *FileBlock) error
// GetWithPrefetch retrieves a block from the cache, along with whether or
// not it has triggered a prefetch.
GetWithPrefetch(ptr BlockPointer) (
block Block, hasPrefetched bool, err error)
// PutWithPrefetch puts a block into the cache, along with whether or not
// it has triggered a prefetch.
PutWithPrefetch(ptr BlockPointer, tlf tlf.ID, block Block,
lifetime BlockCacheLifetime, hasPrefetched bool) error
// SetCleanBytesCapacity atomically sets clean bytes capacity for block
// cache.
SetCleanBytesCapacity(capacity uint64)
// GetCleanBytesCapacity atomically gets clean bytes capacity for block
// cache.
GetCleanBytesCapacity() (capacity uint64)
}
// DirtyPermChan is a channel that gets closed when the holder has
// permission to write. We are forced to define it as a type due to a
// bug in mockgen that can't handle return values with a chan
// struct{}.
type DirtyPermChan <-chan struct{}
// DirtyBlockCache gets and puts plaintext dir blocks and file blocks
// into a cache, which have been modified by the application and not
// yet committed on the KBFS servers. They are identified by a
// (potentially random) ID that may not have any relationship with
// their context, along with a Branch in case the same TLF is being
// modified via multiple branches. Dirty blocks are never evicted,
// they must be deleted explicitly.
type DirtyBlockCache interface {
// Get gets the block associated with the given block ID. Returns
// the dirty block for the given ID, if one exists.
Get(tlfID tlf.ID, ptr BlockPointer, branch BranchName) (Block, error)
// Put stores a dirty block currently identified by the
// given block pointer and branch name.
Put(tlfID tlf.ID, ptr BlockPointer, branch BranchName, block Block) error
// Delete removes the dirty block associated with the given block
// pointer and branch from the cache. No error is returned if no
// block exists for the given ID.
Delete(tlfID tlf.ID, ptr BlockPointer, branch BranchName) error
// IsDirty states whether or not the block associated with the
// given block pointer and branch name is dirty in this cache.
IsDirty(tlfID tlf.ID, ptr BlockPointer, branch BranchName) bool
// IsAnyDirty returns whether there are any dirty blocks in the
// cache. tlfID may be ignored.
IsAnyDirty(tlfID tlf.ID) bool
// RequestPermissionToDirty is called whenever a user wants to
// write data to a file. The caller provides an estimated number
// of bytes that will become dirty -- this is difficult to know
// exactly without pre-fetching all the blocks involved, but in
// practice we can just use the number of bytes sent in via the
// Write. It returns a channel that blocks until the cache is
// ready to receive more dirty data, at which point the channel is
// closed. The user must call
// `UpdateUnsyncedBytes(-estimatedDirtyBytes)` once it has
// completed its write and called `UpdateUnsyncedBytes` for all
// the exact dirty block sizes.
RequestPermissionToDirty(ctx context.Context, tlfID tlf.ID,
estimatedDirtyBytes int64) (DirtyPermChan, error)
// UpdateUnsyncedBytes is called by a user, who has already been
// granted permission to write, with the delta in block sizes that
// were dirtied as part of the write. So for example, if a
// newly-dirtied block of 20 bytes was extended by 5 bytes, they
// should send 25. If on the next write (before any syncs), bytes
// 10-15 of that same block were overwritten, they should send 0
// over the channel because there were no new bytes. If an
// already-dirtied block is truncated, or if previously requested
// bytes have now been updated more accurately in previous
// requests, newUnsyncedBytes may be negative. wasSyncing should
// be true if `BlockSyncStarted` has already been called for this
// block.
UpdateUnsyncedBytes(tlfID tlf.ID, newUnsyncedBytes int64, wasSyncing bool)
// UpdateSyncingBytes is called when a particular block has
// started syncing, or with a negative number when a block is no
// longer syncing due to an error (and BlockSyncFinished will
// never be called).
UpdateSyncingBytes(tlfID tlf.ID, size int64)
// BlockSyncFinished is called when a particular block has
// finished syncing, though the overall sync might not yet be
// complete. This lets the cache know it might be able to grant
// more permission to writers.
BlockSyncFinished(tlfID tlf.ID, size int64)
// SyncFinished is called when a complete sync has completed and
// its dirty blocks have been removed from the cache. This lets
// the cache know it might be able to grant more permission to
// writers.
SyncFinished(tlfID tlf.ID, size int64)
// ShouldForceSync returns true if the sync buffer is full enough
// to force all callers to sync their data immediately.
ShouldForceSync(tlfID tlf.ID) bool
// Shutdown frees any resources associated with this instance. It
// returns an error if there are any unsynced blocks.
Shutdown() error
}
// cryptoPure contains all methods of Crypto that don't depend on
// implicit state, i.e. they're pure functions of the input.
type cryptoPure interface {
// MakeRandomTlfID generates a dir ID using a CSPRNG.
MakeRandomTlfID(isPublic bool) (tlf.ID, error)
// MakeRandomBranchID generates a per-device branch ID using a
// CSPRNG. It will not return LocalSquashBranchID or
// NullBranchID.
MakeRandomBranchID() (BranchID, error)
// MakeMdID computes the MD ID of a RootMetadata object.
// TODO: This should move to BareRootMetadata. Note though, that some mock tests
// rely on it being part of the config and crypto_measured.go uses it to keep
// statistics on time spent hashing.
MakeMdID(md BareRootMetadata) (MdID, error)
// MakeMerkleHash computes the hash of a RootMetadataSigned object
// for inclusion into the KBFS Merkle tree.
MakeMerkleHash(md *RootMetadataSigned) (MerkleHash, error)
// MakeTemporaryBlockID generates a temporary block ID using a
// CSPRNG. This is used for indirect blocks before they're
// committed to the server.
MakeTemporaryBlockID() (kbfsblock.ID, error)
// MakeRefNonce generates a block reference nonce using a
// CSPRNG. This is used for distinguishing different references to
// the same BlockID.
MakeBlockRefNonce() (kbfsblock.RefNonce, error)
// MakeRandomTLFEphemeralKeys generates ephemeral keys using a
// CSPRNG for a TLF. These keys can then be used to key/rekey
// the TLF.
MakeRandomTLFEphemeralKeys() (kbfscrypto.TLFEphemeralPublicKey,
kbfscrypto.TLFEphemeralPrivateKey, error)
// MakeRandomTLFKeys generates keys using a CSPRNG for a
// single key generation of TLF.
MakeRandomTLFKeys() (kbfscrypto.TLFPublicKey,
kbfscrypto.TLFPrivateKey, kbfscrypto.TLFCryptKey, error)
// MakeRandomTLFCryptKeyServerHalf generates the server-side of a
// top-level folder crypt key.
MakeRandomTLFCryptKeyServerHalf() (
kbfscrypto.TLFCryptKeyServerHalf, error)
// MakeRandomBlockCryptKeyServerHalf generates the server-side of
// a block crypt key.
MakeRandomBlockCryptKeyServerHalf() (
kbfscrypto.BlockCryptKeyServerHalf, error)
// EncryptTLFCryptKeyClientHalf encrypts a TLFCryptKeyClientHalf
// using both a TLF's ephemeral private key and a device pubkey.
EncryptTLFCryptKeyClientHalf(
privateKey kbfscrypto.TLFEphemeralPrivateKey,
publicKey kbfscrypto.CryptPublicKey,
clientHalf kbfscrypto.TLFCryptKeyClientHalf) (
EncryptedTLFCryptKeyClientHalf, error)
// EncryptPrivateMetadata encrypts a PrivateMetadata object.
EncryptPrivateMetadata(
pmd PrivateMetadata, key kbfscrypto.TLFCryptKey) (
EncryptedPrivateMetadata, error)
// DecryptPrivateMetadata decrypts a PrivateMetadata object.
DecryptPrivateMetadata(
encryptedPMD EncryptedPrivateMetadata,
key kbfscrypto.TLFCryptKey) (PrivateMetadata, error)
// EncryptBlocks encrypts a block. plainSize is the size of the encoded
// block; EncryptBlock() must guarantee that plainSize <=
// len(encryptedBlock).
EncryptBlock(block Block, key kbfscrypto.BlockCryptKey) (
plainSize int, encryptedBlock EncryptedBlock, err error)
// DecryptBlock decrypts a block. Similar to EncryptBlock(),
// DecryptBlock() must guarantee that (size of the decrypted
// block) <= len(encryptedBlock).
DecryptBlock(encryptedBlock EncryptedBlock,
key kbfscrypto.BlockCryptKey, block Block) error
// GetTLFCryptKeyServerHalfID creates a unique ID for this particular
// kbfscrypto.TLFCryptKeyServerHalf.
GetTLFCryptKeyServerHalfID(
user keybase1.UID, devicePubKey kbfscrypto.CryptPublicKey,
serverHalf kbfscrypto.TLFCryptKeyServerHalf) (
TLFCryptKeyServerHalfID, error)
// VerifyTLFCryptKeyServerHalfID verifies the ID is the proper HMAC result.
VerifyTLFCryptKeyServerHalfID(serverHalfID TLFCryptKeyServerHalfID,
user keybase1.UID, deviceKID keybase1.KID,
serverHalf kbfscrypto.TLFCryptKeyServerHalf) error
// EncryptMerkleLeaf encrypts a Merkle leaf node with the TLFPublicKey.
EncryptMerkleLeaf(leaf MerkleLeaf, pubKey kbfscrypto.TLFPublicKey,
nonce *[24]byte, ePrivKey kbfscrypto.TLFEphemeralPrivateKey) (
EncryptedMerkleLeaf, error)
// DecryptMerkleLeaf decrypts a Merkle leaf node with the TLFPrivateKey.
DecryptMerkleLeaf(encryptedLeaf EncryptedMerkleLeaf,
privKey kbfscrypto.TLFPrivateKey, nonce *[24]byte,
ePubKey kbfscrypto.TLFEphemeralPublicKey) (*MerkleLeaf, error)
// MakeTLFWriterKeyBundleID hashes a TLFWriterKeyBundleV3 to create an ID.
MakeTLFWriterKeyBundleID(wkb TLFWriterKeyBundleV3) (TLFWriterKeyBundleID, error)
// MakeTLFReaderKeyBundleID hashes a TLFReaderKeyBundleV3 to create an ID.
MakeTLFReaderKeyBundleID(rkb TLFReaderKeyBundleV3) (TLFReaderKeyBundleID, error)
// EncryptTLFCryptKeys encrypts an array of historic TLFCryptKeys.
EncryptTLFCryptKeys(oldKeys []kbfscrypto.TLFCryptKey,
key kbfscrypto.TLFCryptKey) (EncryptedTLFCryptKeys, error)
// DecryptTLFCryptKeys decrypts an array of historic TLFCryptKeys.
DecryptTLFCryptKeys(
encKeys EncryptedTLFCryptKeys, key kbfscrypto.TLFCryptKey) (
[]kbfscrypto.TLFCryptKey, error)
}
// Crypto signs, verifies, encrypts, and decrypts stuff.
type Crypto interface {
cryptoPure
// Duplicate kbfscrypto.Signer here to work around gomock's
// limitations.
Sign(context.Context, []byte) (kbfscrypto.SignatureInfo, error)
SignForKBFS(context.Context, []byte) (kbfscrypto.SignatureInfo, error)
SignToString(context.Context, []byte) (string, error)
// DecryptTLFCryptKeyClientHalf decrypts a
// kbfscrypto.TLFCryptKeyClientHalf using the current device's
// private key and the TLF's ephemeral public key.
DecryptTLFCryptKeyClientHalf(ctx context.Context,
publicKey kbfscrypto.TLFEphemeralPublicKey,
encryptedClientHalf EncryptedTLFCryptKeyClientHalf) (
kbfscrypto.TLFCryptKeyClientHalf, error)
// DecryptTLFCryptKeyClientHalfAny decrypts one of the
// kbfscrypto.TLFCryptKeyClientHalf using the available
// private keys and the ephemeral public key. If promptPaper
// is true, the service will prompt the user for any unlocked
// paper keys.
DecryptTLFCryptKeyClientHalfAny(ctx context.Context,
keys []EncryptedTLFCryptKeyClientAndEphemeral,
promptPaper bool) (
kbfscrypto.TLFCryptKeyClientHalf, int, error)
// Shutdown frees any resources associated with this instance.
Shutdown()
}
// MDOps gets and puts root metadata to an MDServer. On a get, it
// verifies the metadata is signed by the metadata's signing key.
type MDOps interface {
// GetForHandle returns the current metadata object
// corresponding to the given top-level folder's handle and
// merge status, if the logged-in user has read permission on
// the folder. It creates the folder if one doesn't exist
// yet, and the logged-in user has permission to do so.
//
// If there is no returned error, then the returned ID must
// always be non-null. An empty ImmutableRootMetadata may be
// returned, but if it is non-empty, then its ID must match
// the returned ID.
GetForHandle(
ctx context.Context, handle *TlfHandle, mStatus MergeStatus) (
tlf.ID, ImmutableRootMetadata, error)
// GetForTLF returns the current metadata object
// corresponding to the given top-level folder, if the logged-in
// user has read permission on the folder.
GetForTLF(ctx context.Context, id tlf.ID) (ImmutableRootMetadata, error)
// GetUnmergedForTLF is the same as the above but for unmerged
// metadata.
GetUnmergedForTLF(ctx context.Context, id tlf.ID, bid BranchID) (
ImmutableRootMetadata, error)
// GetRange returns a range of metadata objects corresponding to
// the passed revision numbers (inclusive).
GetRange(ctx context.Context, id tlf.ID, start, stop MetadataRevision) (
[]ImmutableRootMetadata, error)
// GetUnmergedRange is the same as the above but for unmerged
// metadata history (inclusive).
GetUnmergedRange(ctx context.Context, id tlf.ID, bid BranchID,
start, stop MetadataRevision) ([]ImmutableRootMetadata, error)
// Put stores the metadata object for the given
// top-level folder.
Put(ctx context.Context, rmd *RootMetadata) (MdID, error)
// PutUnmerged is the same as the above but for unmerged
// metadata history.
PutUnmerged(ctx context.Context, rmd *RootMetadata) (MdID, error)
// PruneBranch prunes all unmerged history for the given TLF
// branch.
PruneBranch(ctx context.Context, id tlf.ID, bid BranchID) error
// ResolveBranch prunes all unmerged history for the given TLF
// branch, and also deletes any blocks in `blocksToDelete` that
// are still in the local journal. It also appends the given MD
// to the journal.
ResolveBranch(ctx context.Context, id tlf.ID, bid BranchID,
blocksToDelete []kbfsblock.ID, rmd *RootMetadata) (MdID, error)
// GetLatestHandleForTLF returns the server's idea of the latest handle for the TLF,
// which may not yet be reflected in the MD if the TLF hasn't been rekeyed since it
// entered into a conflicting state.
GetLatestHandleForTLF(ctx context.Context, id tlf.ID) (
tlf.Handle, error)
}
// KeyOps fetches server-side key halves from the key server.
type KeyOps interface {
// GetTLFCryptKeyServerHalf gets a server-side key half for a
// device given the key half ID.
GetTLFCryptKeyServerHalf(ctx context.Context,
serverHalfID TLFCryptKeyServerHalfID,
cryptPublicKey kbfscrypto.CryptPublicKey) (
kbfscrypto.TLFCryptKeyServerHalf, error)
// PutTLFCryptKeyServerHalves stores a server-side key halves for a
// set of users and devices.
PutTLFCryptKeyServerHalves(ctx context.Context,
keyServerHalves UserDeviceKeyServerHalves) error
// DeleteTLFCryptKeyServerHalf deletes a server-side key half for a
// device given the key half ID.
DeleteTLFCryptKeyServerHalf(ctx context.Context,
uid keybase1.UID, kid keybase1.KID,
serverHalfID TLFCryptKeyServerHalfID) error
}
// Prefetcher is an interface to a block prefetcher.
type Prefetcher interface {
// PrefetchBlock directs the prefetcher to prefetch a block.
PrefetchBlock(block Block, blockPtr BlockPointer, kmd KeyMetadata,
priority int) error
// PrefetchAfterBlockRetrieved allows the prefetcher to trigger prefetches
// after a block has been retrieved. Whichever component is responsible for
// retrieving blocks will call this method once it's done retrieving a
// block.
PrefetchAfterBlockRetrieved(b Block, kmd KeyMetadata, priority int,
hasPrefetched bool)
// Shutdown shuts down the prefetcher idempotently. Future calls to
// the various Prefetch* methods will return io.EOF. The returned channel
// allows upstream components to block until all pending prefetches are
// complete. This feature is mainly used for testing, but also to toggle
// the prefetcher on and off.
Shutdown() <-chan struct{}
}
// BlockOps gets and puts data blocks to a BlockServer. It performs
// the necessary crypto operations on each block.
type BlockOps interface {
// Get gets the block associated with the given block pointer
// (which belongs to the TLF with the given key metadata),
// decrypts it if necessary, and fills in the provided block
// object with its contents, if the logged-in user has read
// permission for that block. cacheLifetime controls the behavior of the
// write-through cache once a Get completes.
Get(ctx context.Context, kmd KeyMetadata, blockPtr BlockPointer,
block Block, cacheLifetime BlockCacheLifetime) error
// Ready turns the given block (which belongs to the TLF with
// the given key metadata) into encoded (and encrypted) data,
// and calculates its ID and size, so that we can do a bunch
// of block puts in parallel for every write. Ready() must
// guarantee that plainSize <= readyBlockData.QuotaSize().
Ready(ctx context.Context, kmd KeyMetadata, block Block) (
id kbfsblock.ID, plainSize int, readyBlockData ReadyBlockData, err error)
// Delete instructs the server to delete the given block references.
// It returns the number of not-yet deleted references to
// each block reference
Delete(ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) (
liveCounts map[kbfsblock.ID]int, err error)
// Archive instructs the server to mark the given block references
// as "archived"; that is, they are not being used in the current
// view of the folder, and shouldn't be served to anyone other
// than folder writers.
Archive(ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) error
// TogglePrefetcher activates or deactivates the prefetcher.
TogglePrefetcher(ctx context.Context, enable bool) error
// Prefetcher retrieves this BlockOps' Prefetcher.
Prefetcher() Prefetcher
// Shutdown shuts down all the workers performing Get operations
Shutdown()
}
// Duplicate kbfscrypto.AuthTokenRefreshHandler here to work around
// gomock's limitations.
type authTokenRefreshHandler interface {
RefreshAuthToken(context.Context)
}
// MDServer gets and puts metadata for each top-level directory. The
// instantiation should be able to fetch session/user details via KBPKI. On a
// put, the server is responsible for 1) ensuring the user has appropriate
// permissions for whatever modifications were made; 2) ensuring that
// LastModifyingWriter and LastModifyingUser are updated appropriately; and 3)
// detecting conflicting writes based on the previous root block ID (i.e., when
// it supports strict consistency). On a get, it verifies the logged-in user
// has read permissions.
//
// TODO: Add interface for searching by time
type MDServer interface {
authTokenRefreshHandler
// GetForHandle returns the current (signed/encrypted) metadata
// object corresponding to the given top-level folder's handle, if
// the logged-in user has read permission on the folder. It
// creates the folder if one doesn't exist yet, and the logged-in
// user has permission to do so.
//
// If there is no returned error, then the returned ID must
// always be non-null. A nil *RootMetadataSigned may be
// returned, but if it is non-nil, then its ID must match the
// returned ID.
GetForHandle(ctx context.Context, handle tlf.Handle,
mStatus MergeStatus) (tlf.ID, *RootMetadataSigned, error)
// GetForTLF returns the current (signed/encrypted) metadata object
// corresponding to the given top-level folder, if the logged-in
// user has read permission on the folder.
GetForTLF(ctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus) (
*RootMetadataSigned, error)
// GetRange returns a range of (signed/encrypted) metadata objects
// corresponding to the passed revision numbers (inclusive).
GetRange(ctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,
start, stop MetadataRevision) ([]*RootMetadataSigned, error)
// Put stores the (signed/encrypted) metadata object for the given
// top-level folder. Note: If the unmerged bit is set in the metadata
// block's flags bitmask it will be appended to the unmerged per-device
// history.
Put(ctx context.Context, rmds *RootMetadataSigned, extra ExtraMetadata) error
// PruneBranch prunes all unmerged history for the given TLF branch.
PruneBranch(ctx context.Context, id tlf.ID, bid BranchID) error
// RegisterForUpdate tells the MD server to inform the caller when
// there is a merged update with a revision number greater than
// currHead, which did NOT originate from this same MD server
// session. This method returns a chan which can receive only a
// single error before it's closed. If the received err is nil,
// then there is updated MD ready to fetch which didn't originate
// locally; if it is non-nil, then the previous registration
// cannot send the next notification (e.g., the connection to the
// MD server may have failed). In either case, the caller must
// re-register to get a new chan that can receive future update
// notifications.
RegisterForUpdate(ctx context.Context, id tlf.ID,
currHead MetadataRevision) (<-chan error, error)
// CheckForRekeys initiates the rekey checking process on the
// server. The server is allowed to delay this request, and so it
// returns a channel for returning the error. Actual rekey
// requests are expected to come in asynchronously.
CheckForRekeys(ctx context.Context) <-chan error
// TruncateLock attempts to take the history truncation lock for
// this folder, for a TTL defined by the server. Returns true if
// the lock was successfully taken.
TruncateLock(ctx context.Context, id tlf.ID) (bool, error)
// TruncateUnlock attempts to release the history truncation lock
// for this folder. Returns true if the lock was successfully
// released.
TruncateUnlock(ctx context.Context, id tlf.ID) (bool, error)
// DisableRekeyUpdatesForTesting disables processing rekey updates
// received from the mdserver while testing.
DisableRekeyUpdatesForTesting()
// Shutdown is called to shutdown an MDServer connection.
Shutdown()
// IsConnected returns whether the MDServer is connected.
IsConnected() bool
// GetLatestHandleForTLF returns the server's idea of the latest handle for the TLF,
// which may not yet be reflected in the MD if the TLF hasn't been rekeyed since it
// entered into a conflicting state. For the highest level of confidence, the caller
// should verify the mapping with a Merkle tree lookup.
GetLatestHandleForTLF(ctx context.Context, id tlf.ID) (
tlf.Handle, error)
// OffsetFromServerTime is the current estimate for how off our
// local clock is from the mdserver clock. Add this to any
// mdserver-provided timestamps to get the "local" time of the
// corresponding event. If the returned bool is false, then we
// don't have a current estimate for the offset.
OffsetFromServerTime() (time.Duration, bool)
// GetKeyBundles looks up the key bundles for the given key
// bundle IDs. tlfID must be non-zero but either or both wkbID
// and rkbID can be zero, in which case nil will be returned
// for the respective bundle. If a bundle cannot be found, an
// error is returned and nils are returned for both bundles.
GetKeyBundles(ctx context.Context, tlfID tlf.ID,
wkbID TLFWriterKeyBundleID, rkbID TLFReaderKeyBundleID) (
*TLFWriterKeyBundleV3, *TLFReaderKeyBundleV3, error)
}
type mdServerLocal interface {
MDServer
addNewAssertionForTest(
uid keybase1.UID, newAssertion keybase1.SocialAssertion) error
getCurrentMergedHeadRevision(ctx context.Context, id tlf.ID) (
rev MetadataRevision, err error)
isShutdown() bool
copy(config mdServerLocalConfig) mdServerLocal
}
// BlockServer gets and puts opaque data blocks. The instantiation
// should be able to fetch session/user details via KBPKI. On a
// put/delete, the server is reponsible for: 1) checking that the ID
// matches the hash of the buffer; and 2) enforcing writer quotas.
type BlockServer interface {
authTokenRefreshHandler
// Get gets the (encrypted) block data associated with the given
// block ID and context, uses the provided block key to decrypt
// the block, and fills in the provided block object with its
// contents, if the logged-in user has read permission for that
// block.
Get(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID, context kbfsblock.Context) (
[]byte, kbfscrypto.BlockCryptKeyServerHalf, error)
// Put stores the (encrypted) block data under the given ID
// and context on the server, along with the server half of
// the block key. context should contain a kbfsblock.RefNonce
// of zero. There will be an initial reference for this block
// for the given context.
//
// Put should be idempotent, although it should also return an
// error if, for a given ID, any of the other arguments differ
// from previous Put calls with the same ID.
//
// If this returns a BServerErrorOverQuota, with Throttled=false,
// the caller can treat it as informational and otherwise ignore
// the error.
Put(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID, context kbfsblock.Context,
buf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf) error
// AddBlockReference adds a new reference to the given block,
// defined by the given context (which should contain a
// non-zero kbfsblock.RefNonce). (Contexts with a
// kbfsblock.RefNonce of zero should be used when putting the
// block for the first time via Put().) Returns a
// BServerErrorBlockNonExistent if id is unknown within this
// folder.
//
// AddBlockReference should be idempotent, although it should
// also return an error if, for a given ID and refnonce, any
// of the other fields of context differ from previous
// AddBlockReference calls with the same ID and refnonce.
//
// If this returns a BServerErrorOverQuota, with Throttled=false,
// the caller can treat it as informational and otherwise ignore
// the error.
AddBlockReference(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
context kbfsblock.Context) error
// RemoveBlockReferences removes the references to the given block
// ID defined by the given contexts. If no references to the block
// remain after this call, the server is allowed to delete the
// corresponding block permanently. If the reference defined by
// the count has already been removed, the call is a no-op.
// It returns the number of remaining not-yet-deleted references after this
// reference has been removed
RemoveBlockReferences(ctx context.Context, tlfID tlf.ID,
contexts kbfsblock.ContextMap) (liveCounts map[kbfsblock.ID]int, err error)
// ArchiveBlockReferences marks the given block references as
// "archived"; that is, they are not being used in the current
// view of the folder, and shouldn't be served to anyone other
// than folder writers.
//
// For a given ID/refnonce pair, ArchiveBlockReferences should
// be idempotent, although it should also return an error if
// any of the other fields of the context differ from previous
// calls with the same ID/refnonce pair.
ArchiveBlockReferences(ctx context.Context, tlfID tlf.ID,
contexts kbfsblock.ContextMap) error
// IsUnflushed returns whether a given block is being queued
// locally for later flushing to another block server.
IsUnflushed(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID) (bool, error)
// Shutdown is called to shutdown a BlockServer connection.
Shutdown()
// GetUserQuotaInfo returns the quota for the user.
GetUserQuotaInfo(ctx context.Context) (info *kbfsblock.UserQuotaInfo, err error)
}
// blockServerLocal is the interface for BlockServer implementations
// that store data locally.
type blockServerLocal interface {
BlockServer
// getAllRefsForTest returns all the known block references
// for the given TLF, and should only be used during testing.
getAllRefsForTest(ctx context.Context, tlfID tlf.ID) (
map[kbfsblock.ID]blockRefMap, error)
}
// BlockSplitter decides when a file or directory block needs to be split
type BlockSplitter interface {
// CopyUntilSplit copies data into the block until we reach the
// point where we should split, but only if writing to the end of
// the last block. If this is writing into the middle of a file,
// just copy everything that will fit into the block, and assume
// that block boundaries will be fixed later. Return how much was
// copied.
CopyUntilSplit(
block *FileBlock, lastBlock bool, data []byte, off int64) int64
// CheckSplit, given a block, figures out whether it ends at the
// right place. If so, return 0. If not, return either the
// offset in the block where it should be split, or -1 if more
// bytes from the next block should be appended.
CheckSplit(block *FileBlock) int64
// ShouldEmbedBlockChanges decides whether we should keep the
// block changes embedded in the MD or not.
ShouldEmbedBlockChanges(bc *BlockChanges) bool
}
// KeyServer fetches/writes server-side key halves from/to the key server.
type KeyServer interface {
// GetTLFCryptKeyServerHalf gets a server-side key half for a
// device given the key half ID.
GetTLFCryptKeyServerHalf(ctx context.Context,
serverHalfID TLFCryptKeyServerHalfID,
cryptPublicKey kbfscrypto.CryptPublicKey) (
kbfscrypto.TLFCryptKeyServerHalf, error)
// PutTLFCryptKeyServerHalves stores a server-side key halves for a
// set of users and devices.
PutTLFCryptKeyServerHalves(ctx context.Context,
keyServerHalves UserDeviceKeyServerHalves) error
// DeleteTLFCryptKeyServerHalf deletes a server-side key half for a
// device given the key half ID.
DeleteTLFCryptKeyServerHalf(ctx context.Context,
uid keybase1.UID, kid keybase1.KID,
serverHalfID TLFCryptKeyServerHalfID) error
// Shutdown is called to free any KeyServer resources.
Shutdown()
}
// NodeChange represents a change made to a node as part of an atomic
// file system operation.
type NodeChange struct {
Node Node
// Basenames of entries added/removed.
DirUpdated []string
FileUpdated []WriteRange
}
// Observer can be notified that there is an available update for a
// given directory. The notification callbacks should not block, or
// make any calls to the Notifier interface. Nodes passed to the
// observer should not be held past the end of the notification
// callback.
type Observer interface {
// LocalChange announces that the file at this Node has been
// updated locally, but not yet saved at the server.
LocalChange(ctx context.Context, node Node, write WriteRange)
// BatchChanges announces that the nodes have all been updated
// together atomically. Each NodeChange in changes affects the
// same top-level folder and branch.
BatchChanges(ctx context.Context, changes []NodeChange)
// TlfHandleChange announces that the handle of the corresponding
// folder branch has changed, likely due to previously-unresolved
// assertions becoming resolved. This indicates that the listener
// should switch over any cached paths for this folder-branch to
// the new name. Nodes that were acquired under the old name will
// still continue to work, but new lookups on the old name may
// either encounter alias errors or entirely new TLFs (in the case
// of conflicts).
TlfHandleChange(ctx context.Context, newHandle *TlfHandle)
}
// Notifier notifies registrants of directory changes
type Notifier interface {
// RegisterForChanges declares that the given Observer wants to
// subscribe to updates for the given top-level folders.
RegisterForChanges(folderBranches []FolderBranch, obs Observer) error
// UnregisterFromChanges declares that the given Observer no
// longer wants to subscribe to updates for the given top-level
// folders.
UnregisterFromChanges(folderBranches []FolderBranch, obs Observer) error
}
// Clock is an interface for getting the current time
type Clock interface {
// Now returns the current time.
Now() time.Time
}
// ConflictRenamer deals with names for conflicting directory entries.
type ConflictRenamer interface {
// ConflictRename returns the appropriately modified filename.
ConflictRename(ctx context.Context, op op, original string) (
string, error)
}
// Config collects all the singleton instance instantiations needed to
// run KBFS in one place. The methods below are self-explanatory and
// do not require comments.
type Config interface {
dataVersioner
logMaker
blockCacher
KBFSOps() KBFSOps
SetKBFSOps(KBFSOps)
KBPKI() KBPKI
SetKBPKI(KBPKI)
KeyManager() KeyManager
SetKeyManager(KeyManager)
Reporter() Reporter
SetReporter(Reporter)
MDCache() MDCache
SetMDCache(MDCache)
KeyCache() KeyCache
SetKeyBundleCache(KeyBundleCache)
KeyBundleCache() KeyBundleCache
SetKeyCache(KeyCache)
SetBlockCache(BlockCache)
DirtyBlockCache() DirtyBlockCache
SetDirtyBlockCache(DirtyBlockCache)
Crypto() Crypto
SetCrypto(Crypto)
Codec() kbfscodec.Codec
SetCodec(kbfscodec.Codec)
MDOps() MDOps
SetMDOps(MDOps)
KeyOps() KeyOps
SetKeyOps(KeyOps)
BlockOps() BlockOps
SetBlockOps(BlockOps)
MDServer() MDServer
SetMDServer(MDServer)
BlockServer() BlockServer
SetBlockServer(BlockServer)
KeyServer() KeyServer
SetKeyServer(KeyServer)
KeybaseService() KeybaseService
SetKeybaseService(KeybaseService)
BlockSplitter() BlockSplitter
SetBlockSplitter(BlockSplitter)
Notifier() Notifier
SetNotifier(Notifier)
Clock() Clock
SetClock(Clock)
ConflictRenamer() ConflictRenamer
SetConflictRenamer(ConflictRenamer)
MetadataVersion() MetadataVer
SetMetadataVersion(MetadataVer)
RekeyQueue() RekeyQueue
SetRekeyQueue(RekeyQueue)
// ReqsBufSize indicates the number of read or write operations
// that can be buffered per folder
ReqsBufSize() int
// MaxFileBytes indicates the maximum supported plaintext size of
// a file in bytes.
MaxFileBytes() uint64
// MaxNameBytes indicates the maximum supported size of a
// directory entry name in bytes.
MaxNameBytes() uint32
// MaxDirBytes indicates the maximum supported plaintext size of a
// directory in bytes.
MaxDirBytes() uint64
// DoBackgroundFlushes says whether we should periodically try to
// flush dirty files, even without a sync from the user. Should
// be true except for during some testing.
DoBackgroundFlushes() bool
SetDoBackgroundFlushes(bool)
// RekeyWithPromptWaitTime indicates how long to wait, after
// setting the rekey bit, before prompting for a paper key.
RekeyWithPromptWaitTime() time.Duration
SetRekeyWithPromptWaitTime(time.Duration)
// GracePeriod specifies a grace period for which a delayed cancellation
// waits before actual cancels the context. This is useful for giving
// critical portion of a slow remote operation some extra time to finish as
// an effort to avoid conflicting. Example include an O_EXCL Create call
// interrupted by ALRM signal actually makes it to the server, while
// application assumes not since EINTR is returned. A delayed cancellation
// allows us to distinguish between successful cancel (where remote operation
// didn't make to server) or failed cancel (where remote operation made to
// the server). However, the optimal value of this depends on the network
// conditions. A long grace period for really good network condition would
// just unnecessarily slow down Ctrl-C.
//
// TODO: make this adaptive and self-change over time based on network
// conditions.
DelayedCancellationGracePeriod() time.Duration
SetDelayedCancellationGracePeriod(time.Duration)
// QuotaReclamationPeriod indicates how often should each TLF
// should check for quota to reclaim. If the Duration.Seconds()
// == 0, quota reclamation should not run automatically.
QuotaReclamationPeriod() time.Duration
// QuotaReclamationMinUnrefAge indicates the minimum time a block
// must have been unreferenced before it can be reclaimed.
QuotaReclamationMinUnrefAge() time.Duration
// QuotaReclamationMinHeadAge indicates the minimum age of the
// most recently merged MD update before we can run reclamation,
// to avoid conflicting with a currently active writer.
QuotaReclamationMinHeadAge() time.Duration
// ResetCaches clears and re-initializes all data and key caches.
ResetCaches()
// MetricsRegistry may be nil, which should be interpreted as
// not using metrics at all. (i.e., as if UseNilMetrics were
// set). This differs from how go-metrics treats nil Registry
// objects, which is to use the default registry.
MetricsRegistry() metrics.Registry
SetMetricsRegistry(metrics.Registry)
// TLFValidDuration is the time TLFs are valid before identification needs to be redone.
TLFValidDuration() time.Duration
// SetTLFValidDuration sets TLFValidDuration.
SetTLFValidDuration(time.Duration)
// Shutdown is called to free config resources.
Shutdown(context.Context) error
// CheckStateOnShutdown tells the caller whether or not it is safe
// to check the state of the system on shutdown.
CheckStateOnShutdown() bool
}
// NodeCache holds Nodes, and allows libkbfs to update them when
// things change about the underlying KBFS blocks. It is probably
// most useful to instantiate this on a per-folder-branch basis, so
// that it can create a Path with the correct DirId and Branch name.
type NodeCache interface {
// GetOrCreate either makes a new Node for the given
// BlockPointer, or returns an existing one. TODO: If we ever
// support hard links, we will have to revisit the "name" and
// "parent" parameters here. name must not be empty. Returns
// an error if parent cannot be found.
GetOrCreate(ptr BlockPointer, name string, parent Node) (Node, error)
// Get returns the Node associated with the given ptr if one
// already exists. Otherwise, it returns nil.
Get(ref BlockRef) Node
// UpdatePointer updates the BlockPointer for the corresponding
// Node. NodeCache ignores this call when oldRef is not cached in
// any Node. Returns whether the pointer was updated.
UpdatePointer(oldRef BlockRef, newPtr BlockPointer) bool
// Move swaps the parent node for the corresponding Node, and
// updates the node's name. NodeCache ignores the call when ptr
// is not cached. Returns an error if newParent cannot be found.
// If newParent is nil, it treats the ptr's corresponding node as
// being unlinked from the old parent completely.
Move(ref BlockRef, newParent Node, newName string) error
// Unlink set the corresponding node's parent to nil and caches
// the provided path in case the node is still open. NodeCache
// ignores the call when ptr is not cached. The path is required
// because the caller may have made changes to the parent nodes
// already that shouldn't be reflected in the cached path.
Unlink(ref BlockRef, oldPath path)
// PathFromNode creates the path up to a given Node.
PathFromNode(node Node) path
// AllNodes returns the complete set of nodes currently in the cache.
AllNodes() []Node
}
// fileBlockDeepCopier fetches a file block, makes a deep copy of it
// (duplicating pointer for any indirect blocks) and generates a new
// random temporary block ID for it. It returns the new BlockPointer,
// and internally saves the block for future uses.
type fileBlockDeepCopier func(context.Context, string, BlockPointer) (
BlockPointer, error)
// crAction represents a specific action to take as part of the
// conflict resolution process.
type crAction interface {
// swapUnmergedBlock should be called before do(), and if it
// returns true, the caller must use the merged block
// corresponding to the returned BlockPointer instead of
// unmergedBlock when calling do(). If BlockPointer{} is zeroPtr
// (and true is returned), just swap in the regular mergedBlock.
swapUnmergedBlock(unmergedChains *crChains, mergedChains *crChains,
unmergedBlock *DirBlock) (bool, BlockPointer, error)
// do modifies the given merged block in place to resolve the
// conflict, and potential uses the provided blockCopyFetchers to
// obtain copies of other blocks (along with new BlockPointers)
// when requiring a block copy.
do(ctx context.Context, unmergedCopier fileBlockDeepCopier,
mergedCopier fileBlockDeepCopier, unmergedBlock *DirBlock,
mergedBlock *DirBlock) error
// updateOps potentially modifies, in place, the slices of
// unmerged and merged operations stored in the corresponding
// crChains for the given unmerged and merged most recent
// pointers. Eventually, the "unmerged" ops will be pushed as
// part of a MD update, and so should contain any necessarily
// operations to fully merge the unmerged data, including any
// conflict resolution. The "merged" ops will be played through
// locally, to notify any caches about the newly-obtained merged
// data (and any changes to local data that were required as part
// of conflict resolution, such as renames). A few things to note:
// * A particular action's updateOps method may be called more than
// once for different sets of chains, however it should only add
// new directory operations (like create/rm/rename) into directory
// chains.
// * updateOps doesn't necessarily result in correct BlockPointers within
// each of those ops; that must happen in a later phase.
// * mergedBlock can be nil if the chain is for a file.
updateOps(unmergedMostRecent BlockPointer, mergedMostRecent BlockPointer,
unmergedBlock *DirBlock, mergedBlock *DirBlock,
unmergedChains *crChains, mergedChains *crChains) error
// String returns a string representation for this crAction, used
// for debugging.
String() string
}
// RekeyQueue is a managed queue of folders needing some rekey action taken upon them
// by the current client.
type RekeyQueue interface {
// Enqueue enqueues a folder for rekey action.
Enqueue(tlf.ID) <-chan error
// IsRekeyPending returns true if the given folder is in the rekey queue.
IsRekeyPending(tlf.ID) bool
// GetRekeyChannel will return any rekey completion channel (if pending.)
GetRekeyChannel(id tlf.ID) <-chan error
// Clear cancels all pending rekey actions and clears the queue.
Clear()
// Waits for all queued rekeys to finish
Wait(ctx context.Context) error
}
// BareRootMetadata is a read-only interface to the bare serializeable MD that
// is signed by the reader or writer.
type BareRootMetadata interface {
// TlfID returns the ID of the TLF this BareRootMetadata is for.
TlfID() tlf.ID
// LatestKeyGeneration returns the most recent key generation in this
// BareRootMetadata, or PublicKeyGen if this TLF is public.
LatestKeyGeneration() KeyGen
// IsValidRekeyRequest returns true if the current block is a simple rekey wrt
// the passed block.
IsValidRekeyRequest(codec kbfscodec.Codec, prevMd BareRootMetadata,
user keybase1.UID, prevExtra, extra ExtraMetadata) (bool, error)
// MergedStatus returns the status of this update -- has it been
// merged into the main folder or not?
MergedStatus() MergeStatus
// IsRekeySet returns true if the rekey bit is set.
IsRekeySet() bool
// IsWriterMetadataCopiedSet returns true if the bit is set indicating
// the writer metadata was copied.
IsWriterMetadataCopiedSet() bool
// IsFinal returns true if this is the last metadata block for a given
// folder. This is only expected to be set for folder resets.
IsFinal() bool
// IsWriter returns whether or not the user+device is an authorized writer.
IsWriter(user keybase1.UID, deviceKID keybase1.KID, extra ExtraMetadata) bool
// IsReader returns whether or not the user+device is an authorized reader.
IsReader(user keybase1.UID, deviceKID keybase1.KID, extra ExtraMetadata) bool
// DeepCopy returns a deep copy of the underlying data structure.
DeepCopy(codec kbfscodec.Codec) (MutableBareRootMetadata, error)
// MakeSuccessorCopy returns a newly constructed successor
// copy to this metadata revision. It differs from DeepCopy
// in that it can perform an up conversion to a new metadata
// version. tlfCryptKeyGetter should be a function that
// returns a list of TLFCryptKeys for all key generations in
// ascending order.
MakeSuccessorCopy(codec kbfscodec.Codec, crypto cryptoPure,
extra ExtraMetadata, latestMDVer MetadataVer,
tlfCryptKeyGetter func() ([]kbfscrypto.TLFCryptKey, error),
isReadableAndWriter bool) (mdCopy MutableBareRootMetadata,
extraCopy ExtraMetadata, err error)
// CheckValidSuccessor makes sure the given BareRootMetadata is a valid
// successor to the current one, and returns an error otherwise.
CheckValidSuccessor(currID MdID, nextMd BareRootMetadata) error
// CheckValidSuccessorForServer is like CheckValidSuccessor but with
// server-specific error messages.
CheckValidSuccessorForServer(currID MdID, nextMd BareRootMetadata) error
// MakeBareTlfHandle makes a tlf.Handle for this
// BareRootMetadata. Should be used only by servers and MDOps.
MakeBareTlfHandle(extra ExtraMetadata) (tlf.Handle, error)
// TlfHandleExtensions returns a list of handle extensions associated with the TLf.
TlfHandleExtensions() (extensions []tlf.HandleExtension)
// GetDeviceKIDs returns the KIDs (of
// kbfscrypto.CryptPublicKeys) for all known devices for the
// given user at the given key generation, if any. Returns an
// error if the TLF is public, or if the given key generation
// is invalid.
GetDeviceKIDs(keyGen KeyGen, user keybase1.UID, extra ExtraMetadata) (
[]keybase1.KID, error)
// HasKeyForUser returns whether or not the given user has keys for at
// least one device at the given key generation. Returns false if the
// TLF is public, or if the given key generation is invalid. Equivalent to:
//
// kids, err := GetDeviceKIDs(keyGen, user)
// return (err == nil) && (len(kids) > 0)
HasKeyForUser(keyGen KeyGen, user keybase1.UID, extra ExtraMetadata) bool
// GetTLFCryptKeyParams returns all the necessary info to construct
// the TLF crypt key for the given key generation, user, and device
// (identified by its crypt public key), or false if not found. This
// returns an error if the TLF is public.
GetTLFCryptKeyParams(keyGen KeyGen, user keybase1.UID,
key kbfscrypto.CryptPublicKey, extra ExtraMetadata) (
kbfscrypto.TLFEphemeralPublicKey,
EncryptedTLFCryptKeyClientHalf,
TLFCryptKeyServerHalfID, bool, error)
// IsValidAndSigned verifies the BareRootMetadata, checks the
// writer signature, and returns an error if a problem was
// found. This should be the first thing checked on a BRMD
// retrieved from an untrusted source, and then the signing
// user and key should be validated, either by comparing to
// the current device key (using IsLastModifiedBy), or by
// checking with KBPKI.
IsValidAndSigned(codec kbfscodec.Codec,
crypto cryptoPure, extra ExtraMetadata) error
// IsLastModifiedBy verifies that the BareRootMetadata is
// written by the given user and device (identified by the KID
// of the device verifying key), and returns an error if not.
IsLastModifiedBy(uid keybase1.UID, key kbfscrypto.VerifyingKey) error
// LastModifyingWriter return the UID of the last user to modify the writer metadata.
LastModifyingWriter() keybase1.UID
// LastModifyingUser return the UID of the last user to modify the any of the metadata.
GetLastModifyingUser() keybase1.UID
// RefBytes returns the number of newly referenced bytes introduced by this revision of metadata.
RefBytes() uint64
// UnrefBytes returns the number of newly unreferenced bytes introduced by this revision of metadata.
UnrefBytes() uint64
// DiskUsage returns the estimated disk usage for the folder as of this revision of metadata.
DiskUsage() uint64
// RevisionNumber returns the revision number associated with this metadata structure.
RevisionNumber() MetadataRevision
// BID returns the per-device branch ID associated with this metadata revision.
BID() BranchID
// GetPrevRoot returns the hash of the previous metadata revision.
GetPrevRoot() MdID
// IsUnmergedSet returns true if the unmerged bit is set.
IsUnmergedSet() bool
// GetSerializedPrivateMetadata returns the serialized private metadata as a byte slice.
GetSerializedPrivateMetadata() []byte
// GetSerializedWriterMetadata serializes the underlying writer metadata and returns the result.
GetSerializedWriterMetadata(codec kbfscodec.Codec) ([]byte, error)
// Version returns the metadata version.
Version() MetadataVer
// GetCurrentTLFPublicKey returns the TLF public key for the
// current key generation.
GetCurrentTLFPublicKey(ExtraMetadata) (kbfscrypto.TLFPublicKey, error)
// AreKeyGenerationsEqual returns true if all key generations in the passed metadata are equal to those
// in this revision.
AreKeyGenerationsEqual(kbfscodec.Codec, BareRootMetadata) (bool, error)
// GetUnresolvedParticipants returns any unresolved readers and writers present in this revision of metadata.
GetUnresolvedParticipants() (readers, writers []keybase1.SocialAssertion)
// GetTLFWriterKeyBundleID returns the ID of the externally-stored writer key bundle, or the zero value if
// this object stores it internally.
GetTLFWriterKeyBundleID() TLFWriterKeyBundleID
// GetTLFReaderKeyBundleID returns the ID of the externally-stored reader key bundle, or the zero value if
// this object stores it internally.
GetTLFReaderKeyBundleID() TLFReaderKeyBundleID
// StoresHistoricTLFCryptKeys returns whether or not history keys are symmetrically encrypted; if not, they're
// encrypted per-device.
StoresHistoricTLFCryptKeys() bool
// GetHistoricTLFCryptKey attempts to symmetrically decrypt the key at the given
// generation using the current generation's TLFCryptKey.
GetHistoricTLFCryptKey(c cryptoPure, keyGen KeyGen,
currentKey kbfscrypto.TLFCryptKey, extra ExtraMetadata) (
kbfscrypto.TLFCryptKey, error)
// GetUserDeviceKeyInfoMaps returns copies of the given user
// device key info maps for the given key generation.
GetUserDeviceKeyInfoMaps(
codec kbfscodec.Codec, keyGen KeyGen, extra ExtraMetadata) (
readers, writers UserDeviceKeyInfoMap, err error)
}
// MutableBareRootMetadata is a mutable interface to the bare serializeable MD that is signed by the reader or writer.
type MutableBareRootMetadata interface {
BareRootMetadata
// SetRefBytes sets the number of newly referenced bytes introduced by this revision of metadata.
SetRefBytes(refBytes uint64)
// SetUnrefBytes sets the number of newly unreferenced bytes introduced by this revision of metadata.
SetUnrefBytes(unrefBytes uint64)
// SetDiskUsage sets the estimated disk usage for the folder as of this revision of metadata.
SetDiskUsage(diskUsage uint64)
// AddRefBytes increments the number of newly referenced bytes introduced by this revision of metadata.
AddRefBytes(refBytes uint64)
// AddUnrefBytes increments the number of newly unreferenced bytes introduced by this revision of metadata.
AddUnrefBytes(unrefBytes uint64)
// AddDiskUsage increments the estimated disk usage for the folder as of this revision of metadata.
AddDiskUsage(diskUsage uint64)
// ClearRekeyBit unsets any set rekey bit.
ClearRekeyBit()
// ClearWriterMetadataCopiedBit unsets any set writer metadata copied bit.
ClearWriterMetadataCopiedBit()
// ClearFinalBit unsets any final bit.
ClearFinalBit()
// SetUnmerged sets the unmerged bit.
SetUnmerged()
// SetBranchID sets the branch ID for this metadata revision.
SetBranchID(bid BranchID)
// SetPrevRoot sets the hash of the previous metadata revision.
SetPrevRoot(mdID MdID)
// SetSerializedPrivateMetadata sets the serialized private metadata.
SetSerializedPrivateMetadata(spmd []byte)
// SignWriterMetadataInternally signs the writer metadata, for
// versions that store this signature inside the metadata.
SignWriterMetadataInternally(ctx context.Context,
codec kbfscodec.Codec, signer kbfscrypto.Signer) error
// SetLastModifyingWriter sets the UID of the last user to modify the writer metadata.
SetLastModifyingWriter(user keybase1.UID)
// SetLastModifyingUser sets the UID of the last user to modify any of the metadata.
SetLastModifyingUser(user keybase1.UID)
// SetRekeyBit sets the rekey bit.
SetRekeyBit()
// SetFinalBit sets the finalized bit.
SetFinalBit()
// SetWriterMetadataCopiedBit set the writer metadata copied bit.
SetWriterMetadataCopiedBit()
// SetRevision sets the revision number of the underlying metadata.
SetRevision(revision MetadataRevision)
// SetUnresolvedReaders sets the list of unresolved readers associated with this folder.
SetUnresolvedReaders(readers []keybase1.SocialAssertion)
// SetUnresolvedWriters sets the list of unresolved writers associated with this folder.
SetUnresolvedWriters(writers []keybase1.SocialAssertion)
// SetConflictInfo sets any conflict info associated with this metadata revision.
SetConflictInfo(ci *tlf.HandleExtension)
// SetFinalizedInfo sets any finalized info associated with this metadata revision.
SetFinalizedInfo(fi *tlf.HandleExtension)
// SetWriters sets the list of writers associated with this folder.
SetWriters(writers []keybase1.UID)
// SetTlfID sets the ID of the underlying folder in the metadata structure.
SetTlfID(tlf tlf.ID)
// addKeyGenerationForTest is like AddKeyGeneration, except
// currCryptKey and nextCryptKey don't have to be zero if
// StoresHistoricTLFCryptKeys is false, and takes in
// pre-filled UserDeviceKeyInfoMaps, and also calls
// FinalizeRekey.
addKeyGenerationForTest(codec kbfscodec.Codec, crypto cryptoPure,
prevExtra ExtraMetadata,
currCryptKey, nextCryptKey kbfscrypto.TLFCryptKey,
pubKey kbfscrypto.TLFPublicKey,
wDkim, rDkim UserDeviceKeyInfoMap) ExtraMetadata
// AddKeyGeneration adds a new key generation to this revision
// of metadata. If StoresHistoricTLFCryptKeys is false, then
// currCryptKey and nextCryptKey must be zero. Otherwise,
// nextCryptKey must be non-zero, and currCryptKey must be
// zero if there are no existing key generations, and non-zero
// for otherwise.
//
// AddKeyGeneration must only be called on metadata for
// private TLFs.
AddKeyGeneration(codec kbfscodec.Codec, crypto cryptoPure,
prevExtra ExtraMetadata,
currCryptKey, nextCryptKey kbfscrypto.TLFCryptKey,
pubKey kbfscrypto.TLFPublicKey) (ExtraMetadata, error)
// UpdateKeyGeneration ensures that every device in the given
// key generation for every writer and reader in the provided
// lists has complete TLF crypt key info, and uses the new
// ephemeral key pair to generate the info if it doesn't yet
// exist.
//
// wKeys and rKeys usually contains the full maps of writers
// to per-device crypt public keys, but for reader rekey,
// wKeys will be empty and rKeys will contain only a single
// entry.
//
// UpdateKeyGeneration must only be called on metadata for
// private TLFs.
//
// TODO: Also handle reader promotion.
//
// TODO: Move the key generation handling into this function.
UpdateKeyGeneration(crypto cryptoPure, keyGen KeyGen,
extra ExtraMetadata, wKeys, rKeys UserDevicePublicKeys,
ePubKey kbfscrypto.TLFEphemeralPublicKey,
ePrivKey kbfscrypto.TLFEphemeralPrivateKey,
tlfCryptKey kbfscrypto.TLFCryptKey) (
UserDeviceKeyServerHalves, error)
// PromoteReader converts the given user from a reader to a writer.
PromoteReader(uid keybase1.UID, extra ExtraMetadata) error
// RevokeRemovedDevices removes key info for any device not in
// the given maps, and returns a corresponding map of server
// halves to delete from the server.
//
// Note: the returned server halves may not be for all key
// generations, e.g. for MDv3 it's only for the latest key
// generation.
RevokeRemovedDevices(wKeys, rKeys UserDevicePublicKeys,
extra ExtraMetadata) (ServerHalfRemovalInfo, error)
// FinalizeRekey must be called called after all rekeying work
// has been performed on the underlying metadata.
FinalizeRekey(c cryptoPure, extra ExtraMetadata) error
}
// KeyBundleCache is an interface to a key bundle cache for use with v3 metadata.
type KeyBundleCache interface {
// GetTLFReaderKeyBundle returns the TLFReaderKeyBundleV3 for
// the given TLFReaderKeyBundleID, or nil if there is none.
GetTLFReaderKeyBundle(tlf.ID, TLFReaderKeyBundleID) (*TLFReaderKeyBundleV3, error)
// GetTLFWriterKeyBundle returns the TLFWriterKeyBundleV3 for
// the given TLFWriterKeyBundleID, or nil if there is none.
GetTLFWriterKeyBundle(tlf.ID, TLFWriterKeyBundleID) (*TLFWriterKeyBundleV3, error)
// PutTLFReaderKeyBundle stores the given TLFReaderKeyBundleV3.
PutTLFReaderKeyBundle(tlf.ID, TLFReaderKeyBundleID, TLFReaderKeyBundleV3)
// PutTLFWriterKeyBundle stores the given TLFWriterKeyBundleV3.
PutTLFWriterKeyBundle(tlf.ID, TLFWriterKeyBundleID, TLFWriterKeyBundleV3)
}
| 1 | 14,849 | We maintain that each (logical) key generation has the same set of device keys, so no need to plumb through `keyGen`. | keybase-kbfs | go |
@@ -96,6 +96,7 @@ setup(
'dev': [
"Flask>=0.10.1, <0.13",
"flake8>=3.2.1, <3.4",
+ "mock>=2.0.0, <3.0",
"mypy>=0.501, <0.502",
"rstcheck>=2.2, <4.0",
"tox>=2.3, <3", | 1 | import os
import runpy
from codecs import open
from setuptools import setup, find_packages
# Based on https://github.com/pypa/sampleproject/blob/master/setup.py
# and https://python-packaging-user-guide.readthedocs.org/
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
VERSION = runpy.run_path(os.path.join(here, "mitmproxy", "version.py"))["VERSION"]
setup(
name="mitmproxy",
version=VERSION,
description="An interactive, SSL-capable, man-in-the-middle HTTP proxy for penetration testers and software developers.",
long_description=long_description,
url="http://mitmproxy.org",
author="Aldo Cortesi",
author_email="aldo@corte.si",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Environment :: Console :: Curses",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Security",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: Proxy Servers",
"Topic :: Software Development :: Testing"
],
packages=find_packages(include=[
"mitmproxy", "mitmproxy.*",
"pathod", "pathod.*",
]),
include_package_data=True,
entry_points={
'console_scripts': [
"mitmproxy = mitmproxy.tools.main:mitmproxy",
"mitmdump = mitmproxy.tools.main:mitmdump",
"mitmweb = mitmproxy.tools.main:mitmweb",
"pathod = pathod.pathod_cmdline:go_pathod",
"pathoc = pathod.pathoc_cmdline:go_pathoc"
]
},
# https://packaging.python.org/en/latest/requirements/#install-requires
# It is not considered best practice to use install_requires to pin dependencies to specific versions.
install_requires=[
"blinker>=1.4, <1.5",
"click>=6.2, <7",
"certifi>=2015.11.20.1", # no semver here - this should always be on the last release!
"construct>=2.8, <2.9",
"cryptography>=1.4, <1.9",
"cssutils>=1.0.1, <1.1",
"h2>=3.0, <4",
"html2text>=2016.1.8, <=2016.9.19",
"hyperframe>=5.0, <6",
"jsbeautifier>=1.6.3, <1.7",
"kaitaistruct>=0.7, <0.8",
"ldap3>=2.2.0, <=2.2.3",
"passlib>=1.6.5, <1.8",
"pyasn1>=0.1.9, <0.3",
"pyOpenSSL>=16.0, <17.1",
"pyparsing>=2.1.3, <2.3",
"pyperclip>=1.5.22, <1.6",
"requests>=2.9.1, <3",
"ruamel.yaml>=0.13.2, <0.15",
"tornado>=4.3, <4.6",
"urwid>=1.3.1, <1.4",
"brotlipy>=0.5.1, <0.7",
"sortedcontainers>=1.5.4, <1.6",
# transitive from cryptography, we just blacklist here.
# https://github.com/pypa/setuptools/issues/861
"setuptools>=11.3, !=29.0.0",
],
extras_require={
':sys_platform == "win32"': [
"pydivert>=2.0.3, <2.1",
],
':sys_platform != "win32"': [
],
'dev': [
"Flask>=0.10.1, <0.13",
"flake8>=3.2.1, <3.4",
"mypy>=0.501, <0.502",
"rstcheck>=2.2, <4.0",
"tox>=2.3, <3",
"pytest>=3, <3.1",
"pytest-cov>=2.2.1, <3",
"pytest-timeout>=1.0.0, <2",
"pytest-xdist>=1.14, <2",
"pytest-faulthandler>=1.3.0, <2",
"sphinx>=1.3.5, <1.6",
"sphinx-autobuild>=0.5.2, <0.7",
"sphinxcontrib-documentedlist>=0.5.0, <0.7",
"sphinx_rtd_theme>=0.1.9, <0.3",
],
'contentviews': [
],
'examples': [
"beautifulsoup4>=4.4.1, <4.6",
"Pillow>=3.2, <4.2",
]
}
)
| 1 | 13,222 | Please use `from unittest import mock` instead of this package. | mitmproxy-mitmproxy | py |
@@ -405,6 +405,11 @@ Aggregate.prototype.exec = function (callback) {
prepareDiscriminatorPipeline(this);
+ if (this.options.cursor)
+ return this._model
+ .collection
+ .aggregate(this._pipeline, this.options || {});
+
this._model
.collection
.aggregate(this._pipeline, this.options || {}, promise.resolve.bind(promise)); | 1 | /*!
* Module dependencies
*/
var Promise = require('./promise')
, util = require('util')
, utils = require('./utils')
, Query = require('./query')
, read = Query.prototype.read
/**
* Aggregate constructor used for building aggregation pipelines.
*
* ####Example:
*
* new Aggregate();
* new Aggregate({ $project: { a: 1, b: 1 } });
* new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 });
* new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]);
*
* Returned when calling Model.aggregate().
*
* ####Example:
*
* Model
* .aggregate({ $match: { age: { $gte: 21 }}})
* .unwind('tags')
* .exec(callback)
*
* ####Note:
*
* - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
* - Requires MongoDB >= 2.1
*
* @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
* @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate
* @param {Object|Array} [ops] aggregation operator(s) or operator array
* @api public
*/
function Aggregate () {
this._pipeline = [];
this._model = undefined;
this.options = undefined;
if (1 === arguments.length && util.isArray(arguments[0])) {
this.append.apply(this, arguments[0]);
} else {
this.append.apply(this, arguments);
}
}
/**
* Binds this aggregate to a model.
*
* @param {Model} model the model to which the aggregate is to be bound
* @return {Aggregate}
* @api private
*/
Aggregate.prototype.bind = function (model) {
this._model = model;
return this;
}
/**
* Appends new operators to this aggregate pipeline
*
* ####Examples:
*
* aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
*
* // or pass an array
* var pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
* aggregate.append(pipeline);
*
* @param {Object} ops operator(s) to append
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.append = function () {
var args = utils.args(arguments)
, arg;
if (!args.every(isOperator)) {
throw new Error("Arguments must be aggregate pipeline operators");
}
this._pipeline = this._pipeline.concat(args);
return this;
}
/**
* Appends a new $project operator to this aggregate pipeline.
*
* Mongoose query [selection syntax](#query_Query-select) is also supported.
*
* ####Examples:
*
* // include a, include b, exclude _id
* aggregate.project("a b -_id");
*
* // or you may use object notation, useful when
* // you have keys already prefixed with a "-"
* aggregate.project({a: 1, b: 1, _id: 0});
*
* // reshaping documents
* aggregate.project({
* newField: '$b.nested'
* , plusTen: { $add: ['$val', 10]}
* , sub: {
* name: '$a'
* }
* })
*
* // etc
* aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
*
* @param {Object|String} arg field specification
* @see projection http://docs.mongodb.org/manual/reference/aggregation/project/
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.project = function (arg) {
var fields = {};
if ('object' === typeof arg && !util.isArray(arg)) {
Object.keys(arg).forEach(function (field) {
fields[field] = arg[field];
});
} else if (1 === arguments.length && 'string' === typeof arg) {
arg.split(/\s+/).forEach(function (field) {
if (!field) return;
var include = '-' == field[0] ? 0 : 1;
if (include === 0) field = field.substring(1);
fields[field] = include;
});
} else {
throw new Error("Invalid project() argument. Must be string or object");
}
return this.append({ $project: fields });
}
/**
* Appends a new custom $group operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.group({ _id: "$department" });
*
* @see $group http://docs.mongodb.org/manual/reference/aggregation/group/
* @method group
* @memberOf Aggregate
* @param {Object} arg $group operator contents
* @return {Aggregate}
* @api public
*/
/**
* Appends a new custom $match operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.match({ department: { $in: [ "sales", "engineering" } } });
*
* @see $match http://docs.mongodb.org/manual/reference/aggregation/match/
* @method match
* @memberOf Aggregate
* @param {Object} arg $match operator contents
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $skip operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.skip(10);
*
* @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/
* @method skip
* @memberOf Aggregate
* @param {Number} num number of records to skip before next stage
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $limit operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.limit(10);
*
* @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/
* @method limit
* @memberOf Aggregate
* @param {Number} num maximum number of records to pass to the next stage
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $geoNear operator to this aggregate pipeline.
*
* ####NOTE:
*
* **MUST** be used as the first operator in the pipeline.
*
* ####Examples:
*
* aggregate.near({
* near: [40.724, -73.997],
* distanceField: "dist.calculated", // required
* maxDistance: 0.008,
* query: { type: "public" },
* includeLocs: "dist.location",
* uniqueDocs: true,
* num: 5
* });
*
* @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/
* @method near
* @memberOf Aggregate
* @param {Object} parameters
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.near = function (arg) {
var op = {};
op.$geoNear = arg;
return this.append(op);
};
/*!
* define methods
*/
'group match skip limit out'.split(' ').forEach(function ($operator) {
Aggregate.prototype[$operator] = function (arg) {
var op = {};
op['$' + $operator] = arg;
return this.append(op);
};
});
/**
* Appends new custom $unwind operator(s) to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.unwind("tags");
* aggregate.unwind("a", "b", "c");
*
* @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/
* @param {String} fields the field(s) to unwind
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.unwind = function () {
var args = utils.args(arguments);
return this.append.apply(this, args.map(function (arg) {
return { $unwind: '$' + arg };
}));
}
/**
* Appends a new $sort operator to this aggregate pipeline.
*
* If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
*
* If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
*
* ####Examples:
*
* // these are equivalent
* aggregate.sort({ field: 'asc', test: -1 });
* aggregate.sort('field -test');
*
* @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/
* @param {Object|String} arg
* @return {Aggregate} this
* @api public
*/
Aggregate.prototype.sort = function (arg) {
// TODO refactor to reuse the query builder logic
var sort = {};
if ('Object' === arg.constructor.name) {
var desc = ['desc', 'descending', -1];
Object.keys(arg).forEach(function (field) {
sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
});
} else if (1 === arguments.length && 'string' == typeof arg) {
arg.split(/\s+/).forEach(function (field) {
if (!field) return;
var ascend = '-' == field[0] ? -1 : 1;
if (ascend === -1) field = field.substring(1);
sort[field] = ascend;
});
} else {
throw new TypeError('Invalid sort() argument. Must be a string or object.');
}
return this.append({ $sort: sort });
}
/**
* Sets the readPreference option for the aggregation query.
*
* ####Example:
*
* Model.aggregate(..).read('primaryPreferred').exec(callback)
*
* @param {String} pref one of the listed preference options or their aliases
* @param {Array} [tags] optional tags for this query
* @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
* @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
*/
Aggregate.prototype.read = function (pref) {
if (!this.options) this.options = {};
read.apply(this, arguments);
return this;
};
/**
* Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)
*
* ####Example:
*
* Model.aggregate(..).allowDiskUse(true).exec(callback)
*
* @param {Boolean} value Should tell server it can use hard drive to store data during aggregation.
* @param {Array} [tags] optional tags for this query
* @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
*/
Aggregate.prototype.allowDiskUse = function(value) {
if (!this.options) this.options = {};
this.options.allowDiskUse = value;
return this;
};
/**
* Sets the cursor option option for the aggregation query (ignored for < 2.6.0)
*
* ####Example:
*
* Model.aggregate(..).cursor({ batchSize: 1000 }).exec(callback)
*
* @param {Object} options set the cursor batch size
* @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
*/
Aggregate.prototype.cursor = function(options) {
if (!this.options) this.options = {};
this.options.cursor = options;
return this;
};
/**
* Executes the aggregate pipeline on the currently bound Model.
*
* ####Example:
*
* aggregate.exec(callback);
*
* // Because a promise is returned, the `callback` is optional.
* var promise = aggregate.exec();
* promise.then(..);
*
* @see Promise #promise_Promise
* @param {Function} [callback]
* @return {Promise}
* @api public
*/
Aggregate.prototype.exec = function (callback) {
var promise = new Promise();
if (callback) {
promise.addBack(callback);
}
if (!this._pipeline.length) {
promise.error(new Error("Aggregate has empty pipeline"));
return promise;
}
if (!this._model) {
promise.error(new Error("Aggregate not bound to any Model"));
return promise;
}
prepareDiscriminatorPipeline(this);
this._model
.collection
.aggregate(this._pipeline, this.options || {}, promise.resolve.bind(promise));
return promise;
};
/*!
* Helpers
*/
/**
* Checks whether an object is likely a pipeline operator
*
* @param {Object} obj object to check
* @return {Boolean}
* @api private
*/
function isOperator (obj) {
var k;
if ('object' !== typeof obj) {
return false;
}
k = Object.keys(obj);
return 1 === k.length && k.some(function (key) {
return '$' === key[0];
});
}
/*!
* Adds the appropriate `$match` pipeline step to the top of an aggregate's
* pipeline, should it's model is a non-root discriminator type. This is
* analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`.
*
* @param {Aggregate} aggregate Aggregate to prepare
*/
function prepareDiscriminatorPipeline (aggregate) {
var schema = aggregate._model.schema,
discriminatorMapping = schema && schema.discriminatorMapping;
if (discriminatorMapping && !discriminatorMapping.isRoot) {
var originalPipeline = aggregate._pipeline,
discriminatorKey = discriminatorMapping.key,
discriminatorValue = discriminatorMapping.value;
// If the first pipeline stage is a match and it doesn't specify a `__t`
// key, add the discriminator key to it. This allows for potential
// aggregation query optimizations not to be disturbed by this feature.
if (originalPipeline[0] && originalPipeline[0].$match &&
!originalPipeline[0].$match[discriminatorKey]) {
originalPipeline[0].$match[discriminatorKey] = discriminatorValue;
// `originalPipeline` is a ref, so there's no need for
// aggregate._pipeline = originalPipeline
} else {
var match = {};
match[discriminatorKey] = discriminatorValue;
aggregate._pipeline = [{ $match: match }].concat(originalPipeline);
}
}
}
/*!
* Exports
*/
module.exports = Aggregate;
| 1 | 12,625 | Should be `if (this.options && this.options.cursor) {`. Options may be undefined. Also, going forward, mongoose will always use curly braces around if blocks. | Automattic-mongoose | js |
@@ -68,7 +68,7 @@ Rails.application.configure do
config.action_mailer.raise_delivery_errors = false
# config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :letter_opener_web
- config.action_mailer.smtp_settings = { address: 'mailrelay.blackducksoftware.com',
+ config.action_mailer.smtp_settings = { address: 'mailhost.synopsys.com',
openssl_verify_mode: OpenSSL::SSL::VERIFY_NONE }
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to | 1 | # frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in
# config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_files = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to
# config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use
# secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to
# raise delivery errors.
config.action_mailer.raise_delivery_errors = false
# config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :letter_opener_web
config.action_mailer.smtp_settings = { address: 'mailrelay.blackducksoftware.com',
openssl_verify_mode: OpenSSL::SSL::VERIFY_NONE }
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
SqlTracker::Config.enabled = ENV['SQL_TRACKER'].eql?('enabled')
SqlTracker::Config.tracked_sql_command = %w[sloc_metrics]
SqlTracker::Config.output_path = File.join(ENV['SQL_TRACER_TEMP_PATH'] || '/tmp', 'sql_tracker')
end
| 1 | 9,503 | This should remain as mailrelay.blackducksoftware.com for staging. Not sure this will be valid, but it shouldn't go through the production mail server. | blackducksoftware-ohloh-ui | rb |
@@ -74,6 +74,9 @@ namespace Microsoft.AspNet.Server.Kestrel.Infrastructure
/// </summary>
public MemoryPoolBlock2 Next { get; set; }
+#if DEBUG
+ // See http://www.philosophicalgeek.com/2014/09/29/digging-into-net-object-allocation-fundamentals/
+ // for the cost of including a finalizer
~MemoryPoolBlock2()
{
Debug.Assert(!_pinHandle.IsAllocated, "Ad-hoc memory block wasn't unpinned"); | 1 | using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.AspNet.Server.Kestrel.Infrastructure
{
/// <summary>
/// Block tracking object used by the byte buffer memory pool. A slab is a large allocation which is divided into smaller blocks. The
/// individual blocks are then treated as independant array segments.
/// </summary>
public class MemoryPoolBlock2
{
/// <summary>
/// If this block represents a one-time-use memory object, this GCHandle will hold that memory object at a fixed address
/// so it can be used in native operations.
/// </summary>
private GCHandle _pinHandle;
/// <summary>
/// Native address of the first byte of this block's Data memory. It is null for one-time-use memory, or copied from
/// the Slab's ArrayPtr for a slab-block segment. The byte it points to corresponds to Data.Array[0], and in practice you will always
/// use the _dataArrayPtr + Start or _dataArrayPtr + End, which point to the start of "active" bytes, or point to just after the "active" bytes.
/// </summary>
private IntPtr _dataArrayPtr;
/// <summary>
/// The array segment describing the range of memory this block is tracking. The caller which has leased this block may only read and
/// modify the memory in this range.
/// </summary>
public ArraySegment<byte> Data;
/// <summary>
/// This object cannot be instantiated outside of the static Create method
/// </summary>
protected MemoryPoolBlock2()
{
}
/// <summary>
/// Back-reference to the memory pool which this block was allocated from. It may only be returned to this pool.
/// </summary>
public MemoryPool2 Pool { get; private set; }
/// <summary>
/// Back-reference to the slab from which this block was taken, or null if it is one-time-use memory.
/// </summary>
public MemoryPoolSlab2 Slab { get; private set; }
/// <summary>
/// Convenience accessor
/// </summary>
public byte[] Array => Data.Array;
/// <summary>
/// The Start represents the offset into Array where the range of "active" bytes begins. At the point when the block is leased
/// the Start is guaranteed to be equal to Array.Offset. The value of Start may be assigned anywhere between Data.Offset and
/// Data.Offset + Data.Count, and must be equal to or less than End.
/// </summary>
public int Start { get; set; }
/// <summary>
/// The End represents the offset into Array where the range of "active" bytes ends. At the point when the block is leased
/// the End is guaranteed to be equal to Array.Offset. The value of Start may be assigned anywhere between Data.Offset and
/// Data.Offset + Data.Count, and must be equal to or less than End.
/// </summary>
public int End { get; set; }
/// <summary>
/// Reference to the next block of data when the overall "active" bytes spans multiple blocks. At the point when the block is
/// leased Next is guaranteed to be null. Start, End, and Next are used together in order to create a linked-list of discontiguous
/// working memory. The "active" memory is grown when bytes are copied in, End is increased, and Next is assigned. The "active"
/// memory is shrunk when bytes are consumed, Start is increased, and blocks are returned to the pool.
/// </summary>
public MemoryPoolBlock2 Next { get; set; }
~MemoryPoolBlock2()
{
Debug.Assert(!_pinHandle.IsAllocated, "Ad-hoc memory block wasn't unpinned");
// Debug.Assert(Slab == null || !Slab.IsActive, "Block being garbage collected instead of returned to pool");
if (_pinHandle.IsAllocated)
{
// if this is a one-time-use block, ensure that the GCHandle does not leak
_pinHandle.Free();
}
if (Slab != null && Slab.IsActive)
{
Pool.Return(new MemoryPoolBlock2
{
_dataArrayPtr = _dataArrayPtr,
Data = Data,
Pool = Pool,
Slab = Slab,
});
}
}
/// <summary>
/// Called to ensure that a block is pinned, and return the pointer to native memory just after
/// the range of "active" bytes. This is where arriving data is read into.
/// </summary>
/// <returns></returns>
public IntPtr Pin()
{
Debug.Assert(!_pinHandle.IsAllocated);
if (_dataArrayPtr != IntPtr.Zero)
{
// this is a slab managed block - use the native address of the slab which is always locked
return _dataArrayPtr + End;
}
else
{
// this is one-time-use memory - lock the managed memory until Unpin is called
_pinHandle = GCHandle.Alloc(Data.Array, GCHandleType.Pinned);
return _pinHandle.AddrOfPinnedObject() + End;
}
}
public void Unpin()
{
if (_dataArrayPtr == IntPtr.Zero)
{
// this is one-time-use memory - unlock the managed memory
Debug.Assert(_pinHandle.IsAllocated);
_pinHandle.Free();
}
}
public static MemoryPoolBlock2 Create(
ArraySegment<byte> data,
IntPtr dataPtr,
MemoryPool2 pool,
MemoryPoolSlab2 slab)
{
return new MemoryPoolBlock2
{
Data = data,
_dataArrayPtr = dataPtr,
Pool = pool,
Slab = slab,
Start = data.Offset,
End = data.Offset,
};
}
/// <summary>
/// called when the block is returned to the pool. mutable values are re-assigned to their guaranteed initialized state.
/// </summary>
public void Reset()
{
Next = null;
Start = Data.Offset;
End = Data.Offset;
}
/// <summary>
/// ToString overridden for debugger convenience. This displays the "active" byte information in this block as ASCII characters.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Encoding.ASCII.GetString(Array, Start, End - Start);
}
/// <summary>
/// acquires a cursor pointing into this block at the Start of "active" byte information
/// </summary>
/// <returns></returns>
public MemoryPoolIterator2 GetIterator()
{
return new MemoryPoolIterator2(this);
}
}
}
| 1 | 6,907 | Maybe we should have a Debug.Assert for when `Slab != null` to ensure that we are always returning the block (in our tests at least). | aspnet-KestrelHttpServer | .cs |
@@ -106,10 +106,9 @@ options.vnode = vnode => {
if (typeof type != 'function') {
// Apply defaultValue to value
if (props.defaultValue) {
- if (!props.value && props.value !== 0) {
+ if (props.value == null && props.value !== 0) {
props.value = props.defaultValue;
}
- delete props.defaultValue;
}
// Add support for array select values: <select value={[]} /> | 1 | import {
render as preactRender,
hydrate as preactHydrate,
options,
toChildArray,
Component
} from 'preact';
import { applyEventNormalization } from './events';
const CAMEL_PROPS = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|fill|flood|font|glyph(?!R)|horiz|marker(?!H|W|U)|overline|paint|stop|strikethrough|stroke|text(?!L)|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/;
// Some libraries like `react-virtualized` explicitly check for this.
Component.prototype.isReactComponent = {};
export const REACT_ELEMENT_TYPE =
(typeof Symbol !== 'undefined' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
/**
* Proxy render() since React returns a Component reference.
* @param {import('./internal').VNode} vnode VNode tree to render
* @param {import('./internal').PreactElement} parent DOM node to render vnode tree into
* @param {() => void} [callback] Optional callback that will be called after rendering
* @returns {import('./internal').Component | null} The root component reference or null
*/
export function render(vnode, parent, callback) {
// React destroys any existing DOM nodes, see #1727
// ...but only on the first render, see #1828
if (parent._children == null) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
preactRender(vnode, parent);
if (typeof callback === 'function') callback();
return vnode ? vnode._component : null;
}
export function hydrate(vnode, parent, callback) {
preactHydrate(vnode, parent);
if (typeof callback === 'function') callback();
return vnode ? vnode._component : null;
}
let oldEventHook = options.event;
options.event = e => {
if (oldEventHook) e = oldEventHook(e);
e.persist = () => {};
e.isDefaultPrevented = () => e.defaultPrevented;
const normalStopPropagation = e.stopPropagation;
let stoppedPropagating = false;
e.stopPropagation = function() {
stoppedPropagating = true;
normalStopPropagation.call(this);
};
e.isPropagationStopped = () => stoppedPropagating;
return (e.nativeEvent = e);
};
// Patch in `UNSAFE_*` lifecycle hooks
function setSafeDescriptor(proto, key) {
if (proto['UNSAFE_' + key] && !proto[key]) {
Object.defineProperty(proto, key, {
configurable: false,
get() {
return this['UNSAFE_' + key];
},
// This `set` is only used if a user sets a lifecycle like cWU
// after setting a lifecycle like UNSAFE_cWU. I doubt anyone
// actually does this in practice so not testing it
/* istanbul ignore next */
set(v) {
this['UNSAFE_' + key] = v;
}
});
}
}
let classNameDescriptor = {
configurable: true,
get() {
return this.class;
}
};
let oldVNodeHook = options.vnode;
options.vnode = vnode => {
vnode.$$typeof = REACT_ELEMENT_TYPE;
let type = vnode.type;
let props = vnode.props;
// Alias `class` prop to `className` if available
if (props.class != props.className) {
classNameDescriptor.enumerable = 'className' in props;
if (props.className != null) props.class = props.className;
Object.defineProperty(props, 'className', classNameDescriptor);
}
// Apply DOM VNode compat
if (typeof type != 'function') {
// Apply defaultValue to value
if (props.defaultValue) {
if (!props.value && props.value !== 0) {
props.value = props.defaultValue;
}
delete props.defaultValue;
}
// Add support for array select values: <select value={[]} />
if (Array.isArray(props.value) && props.multiple && type === 'select') {
toChildArray(props.children).forEach(child => {
if (props.value.indexOf(child.props.value) != -1) {
child.props.selected = true;
}
});
delete props.value;
}
// Normalize DOM vnode properties.
let shouldSanitize, attrs, i;
for (i in props) if ((shouldSanitize = CAMEL_PROPS.test(i))) break;
if (shouldSanitize) {
attrs = vnode.props = {};
for (i in props) {
attrs[
CAMEL_PROPS.test(i) ? i.replace(/([A-Z0-9])/, '-$1').toLowerCase() : i
] = props[i];
}
}
}
// Events
applyEventNormalization(vnode);
// Component base class compat
// We can't just patch the base component class, because components that use
// inheritance and are transpiled down to ES5 will overwrite our patched
// getters and setters. See #1941
if (
typeof type === 'function' &&
!type._patchedLifecycles &&
type.prototype
) {
setSafeDescriptor(type.prototype, 'componentWillMount');
setSafeDescriptor(type.prototype, 'componentWillReceiveProps');
setSafeDescriptor(type.prototype, 'componentWillUpdate');
type._patchedLifecycles = true;
}
if (oldVNodeHook) oldVNodeHook(vnode);
};
| 1 | 15,433 | Okay sorry about this I was really confused on how to support uncontrolled in this case, so what we want to do is apply `defaultValue` when `props.value` is falsy but not undefined, right? In the case of us seeing it is controlled (value & onChange present) we apply defaultValue to `props.value` (and delete props.defaultValue) In the case of uncontrolled we shouldn't enter this branch at all and go for full native dom behavior | preactjs-preact | js |
@@ -25,9 +25,12 @@ import { getTimeInSeconds, numberFormat } from 'GoogleUtil';
import { getDataTableFromData, TableOverflowContainer } from 'GoogleComponents/data-table';
import PreviewTable from 'GoogleComponents/preview-table';
-const { __, sprintf } = wp.i18n;
-const { map } = lodash;
-const { Component } = wp.element;
+/**
+ * WordPress dependencies
+ */
+import { __, sprintf } from '@wordpress/i18n';
+import { map } from 'lodash';
+import { Component } from '@wordpress/element';
class SearchConsoleDashboardWidgetKeywordTable extends Component {
render() { | 1 | /**
* SearchConsoleDashboardWidgetKeywordTable component.
*
* Site Kit by Google, Copyright 2019 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import withData from 'GoogleComponents/higherorder/withdata';
import { TYPE_MODULES } from 'GoogleComponents/data';
import { getTimeInSeconds, numberFormat } from 'GoogleUtil';
import { getDataTableFromData, TableOverflowContainer } from 'GoogleComponents/data-table';
import PreviewTable from 'GoogleComponents/preview-table';
const { __, sprintf } = wp.i18n;
const { map } = lodash;
const { Component } = wp.element;
class SearchConsoleDashboardWidgetKeywordTable extends Component {
render() {
const { data } = this.props;
if ( ! data || ! data.length ) {
return null;
}
const headers = [
{
title: __( 'Keyword', 'google-site-kit' ),
tooltip: __( 'Most searched for keywords related to your content', 'google-site-kit' ),
},
{
title: __( 'Clicks', 'google-site-kit' ),
tooltip: __( 'Number of times users clicked on your content in search results', 'google-site-kit' ),
},
{
title: __( 'Impressions', 'google-site-kit' ),
tooltip: __( 'Counted each time your content appears in search results', 'google-site-kit' ),
},
];
const domain = googlesitekit.admin.siteURL;
const links = [];
const dataMapped = map( data, ( row, i ) => {
const query = row.keys[ 0 ];
links[ i ] = sprintf(
'https://search.google.com/search-console/performance/search-analytics?resource_id=%s&query=!%s&num_of_days=28',
domain,
query
);
return [
query,
numberFormat( row.clicks ),
numberFormat( row.impressions ),
];
} );
const options = {
hideHeader: false,
chartsEnabled: false,
links,
};
const dataTable = getDataTableFromData( dataMapped, headers, options );
return (
<TableOverflowContainer>
{ dataTable }
</TableOverflowContainer>
);
}
}
export default withData(
SearchConsoleDashboardWidgetKeywordTable,
[
{
type: TYPE_MODULES,
identifier: 'search-console',
datapoint: 'searchanalytics',
data: {
url: googlesitekit.permaLink,
dimensions: 'query',
limit: 10,
},
priority: 1,
maxAge: getTimeInSeconds( 'day' ),
context: [ 'Single', 'Dashboard' ],
},
],
<PreviewTable padding />,
{ createGrid: true }
);
| 1 | 24,753 | `lodash` shouldn't be grouped under WordPress dependencies | google-site-kit-wp | js |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.