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 |
---|---|---|---|---|---|---|---|
@@ -11,8 +11,12 @@ var Parser = imports.Parser || require('./util/BinaryParser');
var Step = imports.Step || require('step');
var buffertools = imports.buffertools || require('buffertools');
var error = imports.error || require('./util/error');
+var networks = imports.networks || require('./networks');
+var WalletKey = imports.WalletKey || require('./WalletKey');
+var PrivateKey = imports.PrivateKey || require('./PrivateKey');
var COINBASE_OP = Buffer.concat([util.NULL_HASH, new Buffer('FFFFFFFF', 'hex')]);
+var DEFAULT_FEE = 0.0001;
function TransactionIn(data) {
if ("object" !== typeof data) { | 1 | var imports = require('soop').imports();
var config = imports.config || require('./config');
var log = imports.log || require('./util/log');
var Address = imports.Address || require('./Address');
var Script = imports.Script || require('./Script');
var ScriptInterpreter = imports.ScriptInterpreter || require('./ScriptInterpreter');
var util = imports.util || require('./util/util');
var bignum = imports.bignum || require('bignum');
var Put = imports.Put || require('bufferput');
var Parser = imports.Parser || require('./util/BinaryParser');
var Step = imports.Step || require('step');
var buffertools = imports.buffertools || require('buffertools');
var error = imports.error || require('./util/error');
var COINBASE_OP = Buffer.concat([util.NULL_HASH, new Buffer('FFFFFFFF', 'hex')]);
function TransactionIn(data) {
if ("object" !== typeof data) {
data = {};
}
if (data.o) {
this.o = data.o;
} else {
if (data.oTxHash && typeof data.oIndex !== 'undefined' && data.oIndex >= 0) {
var hash = new Buffer(data.oTxHash, 'hex');
hash = buffertools.reverse(hash);
var voutBuf = new Buffer(4);
voutBuf.writeUInt32LE(data.oIndex, 0);
this.o = Buffer.concat([hash, voutBuf]);
}
}
this.s = Buffer.isBuffer(data.s) ? data.s :
Buffer.isBuffer(data.script) ? data.script : util.EMPTY_BUFFER;
this.q = data.q ? data.q : data.sequence;
}
TransactionIn.prototype.getScript = function getScript() {
return new Script(this.s);
};
TransactionIn.prototype.isCoinBase = function isCoinBase() {
return buffertools.compare(this.o, COINBASE_OP) === 0;
};
TransactionIn.prototype.serialize = function serialize() {
var slen = util.varIntBuf(this.s.length);
var qbuf = new Buffer(4);
qbuf.writeUInt32LE(this.q, 0);
var ret = Buffer.concat([this.o, slen, this.s, qbuf]);
return ret;
};
TransactionIn.prototype.getOutpointHash = function getOutpointHash() {
if ("undefined" !== typeof this.o.outHashCache) {
return this.o.outHashCache;
}
return this.o.outHashCache = this.o.slice(0, 32);
};
TransactionIn.prototype.getOutpointIndex = function getOutpointIndex() {
return (this.o[32] ) +
(this.o[33] << 8) +
(this.o[34] << 16) +
(this.o[35] << 24);
};
TransactionIn.prototype.setOutpointIndex = function setOutpointIndex(n) {
this.o[32] = n & 0xff;
this.o[33] = n >> 8 & 0xff;
this.o[34] = n >> 16 & 0xff;
this.o[35] = n >> 24 & 0xff;
};
function TransactionOut(data) {
if ("object" !== typeof data) {
data = {};
}
this.v = data.v ? data.v : data.value;
this.s = data.s ? data.s : data.script;
};
TransactionOut.prototype.getValue = function getValue() {
return new Parser(this.v).word64lu();
};
TransactionOut.prototype.getScript = function getScript() {
return new Script(this.s);
};
TransactionOut.prototype.serialize = function serialize() {
var slen = util.varIntBuf(this.s.length);
return Buffer.concat([this.v, slen, this.s]);
};
function Transaction(data) {
if ("object" !== typeof data) {
data = {};
}
this.hash = data.hash || null;
this.version = data.version;
this.lock_time = data.lock_time;
this.ins = Array.isArray(data.ins) ? data.ins.map(function (data) {
var txin = new TransactionIn();
txin.s = data.s;
txin.q = data.q;
txin.o = data.o;
return txin;
}) : [];
this.outs = Array.isArray(data.outs) ? data.outs.map(function (data) {
var txout = new TransactionOut();
txout.v = data.v;
txout.s = data.s;
return txout;
}) : [];
if (data.buffer) this._buffer = data.buffer;
};
this.class = Transaction;
Transaction.In = TransactionIn;
Transaction.Out = TransactionOut;
Transaction.prototype.isCoinBase = function () {
return this.ins.length == 1 && this.ins[0].isCoinBase();
};
Transaction.prototype.isStandard = function isStandard() {
var i;
for (i = 0; i < this.ins.length; i++) {
if (this.ins[i].getScript().getInType() == "Strange") {
return false;
}
}
for (i = 0; i < this.outs.length; i++) {
if (this.outs[i].getScript().getOutType() == "Strange") {
return false;
}
}
return true;
};
Transaction.prototype.serialize = function serialize() {
var bufs = [];
var buf = new Buffer(4);
buf.writeUInt32LE(this.version, 0);
bufs.push(buf);
bufs.push(util.varIntBuf(this.ins.length));
this.ins.forEach(function (txin) {
bufs.push(txin.serialize());
});
bufs.push(util.varIntBuf(this.outs.length));
this.outs.forEach(function (txout) {
bufs.push(txout.serialize());
});
var buf = new Buffer(4);
buf.writeUInt32LE(this.lock_time, 0);
bufs.push(buf);
this._buffer = Buffer.concat(bufs);
return this._buffer;
};
Transaction.prototype.getBuffer = function getBuffer() {
if (this._buffer) return this._buffer;
return this.serialize();
};
Transaction.prototype.calcHash = function calcHash() {
this.hash = util.twoSha256(this.getBuffer());
return this.hash;
};
Transaction.prototype.checkHash = function checkHash() {
if (!this.hash || !this.hash.length) return false;
return buffertools.compare(this.calcHash(), this.hash) === 0;
};
Transaction.prototype.getHash = function getHash() {
if (!this.hash || !this.hash.length) {
this.hash = this.calcHash();
}
return this.hash;
};
// convert encoded list of inputs to easy-to-use JS list-of-lists
Transaction.prototype.inputs = function inputs() {
var res = [];
for (var i = 0; i < this.ins.length; i++) {
var txin = this.ins[i];
var outHash = txin.getOutpointHash();
var outIndex = txin.getOutpointIndex();
res.push([outHash, outIndex]);
}
return res;
}
/**
* Load and cache transaction inputs.
*
* This function will try to load the inputs for a transaction.
*
* @param {BlockChain} blockChain A reference to the BlockChain object.
* @param {TransactionMap|null} txStore Additional transactions to consider.
* @param {Boolean} wait Whether to keep trying until the dependencies are
* met (or a timeout occurs.)
* @param {Function} callback Function to call on completion.
*/
Transaction.prototype.cacheInputs =
function cacheInputs(blockChain, txStore, wait, callback) {
var self = this;
var txCache = new TransactionInputsCache(this);
txCache.buffer(blockChain, txStore, wait, callback);
};
Transaction.prototype.verify = function verify(txCache, blockChain, callback) {
var self = this;
var txIndex = txCache.txIndex;
var outpoints = [];
var valueIn = bignum(0);
var valueOut = bignum(0);
function getTxOut(txin, n) {
var outHash = txin.getOutpointHash();
var outIndex = txin.getOutpointIndex();
var outHashBase64 = outHash.toString('base64');
var fromTxOuts = txIndex[outHashBase64];
if (!fromTxOuts) {
throw new MissingSourceError(
"Source tx " + util.formatHash(outHash) +
" for inputs " + n + " not found",
// We store the hash of the missing tx in the error
// so that the txStore can watch out for it.
outHash.toString('base64')
);
}
var txout = fromTxOuts[outIndex];
if (!txout) {
throw new Error("Source output index "+outIndex+
" for input "+n+" out of bounds");
}
return txout;
};
Step(
function verifyInputs() {
var group = this.group();
if (self.isCoinBase()) {
throw new Error("Coinbase tx are invalid unless part of a block");
}
self.ins.forEach(function (txin, n) {
var txout = getTxOut(txin, n);
// TODO: Verify coinbase maturity
valueIn = valueIn.add(util.valueToBigInt(txout.v));
outpoints.push(txin.o);
self.verifyInput(n, txout.getScript(), group());
});
},
function verifyInputsResults(err, results) {
if (err) throw err;
for (var i = 0, l = results.length; i < l; i++) {
if (!results[i]) {
var txout = getTxOut(self.ins[i]);
log.debug('Script evaluated to false');
log.debug('|- scriptSig', ""+self.ins[i].getScript());
log.debug('`- scriptPubKey', ""+txout.getScript());
throw new VerificationError('Script for input '+i+' evaluated to false');
}
}
this();
},
function queryConflicts(err) {
if (err) throw err;
// Make sure there are no other transactions spending the same outs
blockChain.countConflictingTransactions(outpoints, this);
},
function checkConflicts(err, count) {
if (err) throw err;
self.outs.forEach(function (txout) {
valueOut = valueOut.add(util.valueToBigInt(txout.v));
});
if (valueIn.cmp(valueOut) < 0) {
var outValue = util.formatValue(valueOut);
var inValue = util.formatValue(valueIn);
throw new Error("Tx output value (BTC "+outValue+") "+
"exceeds input value (BTC "+inValue+")");
}
var fees = valueIn.sub(valueOut);
if (count) {
// Spent output detected, retrieve transaction that spends it
blockChain.getConflictingTransactions(outpoints, function (err, results) {
if (results.length) {
if (buffertools.compare(results[0].getHash(), self.getHash()) === 0) {
log.warn("Detected tx re-add (recoverable db corruption): "
+ util.formatHashAlt(results[0].getHash()));
// TODO: Needs to return an error for the memory pool case?
callback(null, fees);
} else {
callback(new Error("At least one referenced output has"
+ " already been spent in tx "
+ util.formatHashAlt(results[0].getHash())));
}
} else {
callback(new Error("Outputs of this transaction are spent, but "+
"the transaction(s) that spend them are not "+
"available. This probably means you need to "+
"reset your database."));
}
});
return;
}
// Success
this(null, fees);
},
callback
);
};
Transaction.prototype.verifyInput = function verifyInput(n, scriptPubKey, callback) {
return ScriptInterpreter.verify(this.ins[n].getScript(),
scriptPubKey,
this, n, 0,
callback);
};
/**
* Returns an object containing all pubkey hashes affected by this transaction.
*
* The return object contains the base64-encoded pubKeyHash values as keys
* and the original pubKeyHash buffers as values.
*/
Transaction.prototype.getAffectedKeys = function getAffectedKeys(txCache) {
// TODO: Function won't consider results cached if there are no affected
// accounts.
if (!(this.affects && this.affects.length)) {
this.affects = [];
// Index any pubkeys affected by the outputs of this transaction
for (var i = 0, l = this.outs.length; i < l; i++) {
try {
var txout = this.outs[i];
var script = txout.getScript();
var outPubKey = script.simpleOutPubKeyHash();
if (outPubKey) {
this.affects.push(outPubKey);
}
} catch (err) {
// It's not our job to validate, so we just ignore any errors and issue
// a very low level log message.
log.debug("Unable to determine affected pubkeys: " +
(err.stack ? err.stack : ""+err));
}
};
// Index any pubkeys affected by the inputs of this transaction
var txIndex = txCache.txIndex;
for (var i = 0, l = this.ins.length; i < l; i++) {
try {
var txin = this.ins[i];
if (txin.isCoinBase()) continue;
// In the case of coinbase or IP transactions, the txin doesn't
// actually contain the pubkey, so we look at the referenced txout
// instead.
var outHash = txin.getOutpointHash();
var outIndex = txin.getOutpointIndex();
var outHashBase64 = outHash.toString('base64');
var fromTxOuts = txIndex[outHashBase64];
if (!fromTxOuts) {
throw new Error("Input not found!");
}
var txout = fromTxOuts[outIndex];
var script = txout.getScript();
var outPubKey = script.simpleOutPubKeyHash();
if (outPubKey) {
this.affects.push(outPubKey);
}
} catch (err) {
// It's not our job to validate, so we just ignore any errors and issue
// a very low level log message.
log.debug("Unable to determine affected pubkeys: " +
(err.stack ? err.stack : ""+err));
}
}
}
var affectedKeys = {};
this.affects.forEach(function (pubKeyHash) {
affectedKeys[pubKeyHash.toString('base64')] = pubKeyHash;
});
return affectedKeys;
};
var OP_CODESEPARATOR = 171;
var SIGHASH_ALL = 1;
var SIGHASH_NONE = 2;
var SIGHASH_SINGLE = 3;
var SIGHASH_ANYONECANPAY = 80;
Transaction.SIGHASH_ALL=SIGHASH_ALL;
Transaction.SIGHASH_NONE=SIGHASH_NONE;
Transaction.SIGHASH_SINGLE=SIGHASH_SINGLE;
Transaction.SIGHASH_ANYONECANPAY=SIGHASH_ANYONECANPAY;
Transaction.prototype.hashForSignature =
function hashForSignature(script, inIndex, hashType) {
if (+inIndex !== inIndex ||
inIndex < 0 || inIndex >= this.ins.length) {
throw new Error("Input index '"+inIndex+"' invalid or out of bounds "+
"("+this.ins.length+" inputs)");
}
// Clone transaction
var txTmp = new Transaction();
this.ins.forEach(function (txin, i) {
txTmp.ins.push(new TransactionIn(txin));
});
this.outs.forEach(function (txout) {
txTmp.outs.push(new TransactionOut(txout));
});
txTmp.version = this.version;
txTmp.lock_time = this.lock_time;
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible
// incompatibilities.
script.findAndDelete(OP_CODESEPARATOR);
// Get mode portion of hashtype
var hashTypeMode = hashType & 0x1f;
// Generate modified transaction data for hash
var bytes = (new Put());
bytes.word32le(this.version);
// Serialize inputs
if (hashType & SIGHASH_ANYONECANPAY) {
// Blank out all inputs except current one, not recommended for open
// transactions.
bytes.varint(1);
bytes.put(this.ins[inIndex].o);
bytes.varint(script.buffer.length);
bytes.put(script.buffer);
bytes.word32le(this.ins[inIndex].q);
} else {
bytes.varint(this.ins.length);
for (var i = 0, l = this.ins.length; i < l; i++) {
var txin = this.ins[i];
bytes.put(this.ins[i].o);
// Current input's script gets set to the script to be signed, all others
// get blanked.
if (inIndex === i) {
bytes.varint(script.buffer.length);
bytes.put(script.buffer);
} else {
bytes.varint(0);
}
if (hashTypeMode === SIGHASH_NONE && inIndex !== i) {
bytes.word32le(0);
} else {
bytes.word32le(this.ins[i].q);
}
}
}
// Serialize outputs
if (hashTypeMode === SIGHASH_NONE) {
bytes.varint(0);
} else {
var outsLen;
if (hashTypeMode === SIGHASH_SINGLE) {
// TODO: Untested
if (inIndex >= txTmp.outs.length) {
throw new Error("Transaction.hashForSignature(): SIGHASH_SINGLE " +
"no corresponding txout found - out of bounds");
}
outsLen = inIndex + 1;
} else {
outsLen = this.outs.length;
}
// TODO: If hashTypeMode !== SIGHASH_SINGLE, we could memcpy this whole
// section from the original transaction as is.
bytes.varint(outsLen);
for (var i = 0; i < outsLen; i++) {
if (hashTypeMode === SIGHASH_SINGLE && i !== inIndex) {
// Zero all outs except the one we want to keep
bytes.put(util.INT64_MAX);
bytes.varint(0);
} else {
bytes.put(this.outs[i].v);
bytes.varint(this.outs[i].s.length);
bytes.put(this.outs[i].s);
}
}
}
bytes.word32le(this.lock_time);
var buffer = bytes.buffer();
// Append hashType
buffer = Buffer.concat([buffer, new Buffer([parseInt(hashType), 0, 0, 0])]);
return util.twoSha256(buffer);
};
/**
* Returns an object with the same field names as jgarzik's getblock patch.
*/
Transaction.prototype.getStandardizedObject = function getStandardizedObject() {
var tx = {
hash: util.formatHashFull(this.getHash()),
version: this.version,
lock_time: this.lock_time
};
var totalSize = 8; // version + lock_time
totalSize += util.getVarIntSize(this.ins.length); // tx_in count
var ins = this.ins.map(function (txin) {
var txinObj = {
prev_out: {
hash: buffertools.reverse(new Buffer(txin.getOutpointHash())).toString('hex'),
n: txin.getOutpointIndex()
}
};
if (txin.isCoinBase()) {
txinObj.coinbase = txin.s.toString('hex');
} else {
txinObj.scriptSig = new Script(txin.s).getStringContent(false, 0);
}
totalSize += 36 + util.getVarIntSize(txin.s.length) +
txin.s.length + 4; // outpoint + script_len + script + sequence
return txinObj;
});
totalSize += util.getVarIntSize(this.outs.length);
var outs = this.outs.map(function (txout) {
totalSize += util.getVarIntSize(txout.s.length) +
txout.s.length + 8; // script_len + script + value
return {
value: util.formatValue(txout.v),
scriptPubKey: new Script(txout.s).getStringContent(false, 0)
};
});
tx.size = totalSize;
tx["in"] = ins;
tx["out"] = outs;
return tx;
};
// Add some Mongoose compatibility functions to the plain object
Transaction.prototype.toObject = function toObject() {
return this;
};
Transaction.prototype.fromObj = function fromObj(obj) {
var txobj = {};
txobj.version = obj.version || 1;
txobj.lock_time = obj.lock_time || 0;
txobj.ins = [];
txobj.outs = [];
obj.inputs.forEach(function(inputobj) {
var txin = new TransactionIn();
txin.s = util.EMPTY_BUFFER;
txin.q = 0xffffffff;
var hash = new Buffer(inputobj.txid, 'hex');
hash = buffertools.reverse(hash);
var vout = parseInt(inputobj.vout);
var voutBuf = new Buffer(4);
voutBuf.writeUInt32LE(vout, 0);
txin.o = Buffer.concat([hash, voutBuf]);
txobj.ins.push(txin);
});
var keys = Object.keys(obj.outputs);
keys.forEach(function(addrStr) {
var addr = new Address(addrStr);
var script = Script.createPubKeyHashOut(addr.payload());
var valueNum = bignum(obj.outputs[addrStr]);
var value = util.bigIntToValue(valueNum);
var txout = new TransactionOut();
txout.v = value;
txout.s = script.getBuffer();
txobj.outs.push(txout);
});
this.lock_time = txobj.lock_time;
this.version = txobj.version;
this.ins = txobj.ins;
this.outs = txobj.outs;
}
Transaction.prototype.parse = function (parser) {
if (Buffer.isBuffer(parser)) {
this._buffer = parser;
parser = new Parser(parser);
}
var i, sLen, startPos = parser.pos;
this.version = parser.word32le();
var txinCount = parser.varInt();
this.ins = [];
for (j = 0; j < txinCount; j++) {
var txin = new TransactionIn();
txin.o = parser.buffer(36); // outpoint
sLen = parser.varInt(); // script_len
txin.s = parser.buffer(sLen); // script
txin.q = parser.word32le(); // sequence
this.ins.push(txin);
}
var txoutCount = parser.varInt();
this.outs = [];
for (j = 0; j < txoutCount; j++) {
var txout = new TransactionOut();
txout.v = parser.buffer(8); // value
sLen = parser.varInt(); // script_len
txout.s = parser.buffer(sLen); // script
this.outs.push(txout);
}
this.lock_time = parser.word32le();
this.calcHash();
};
var TransactionInputsCache = exports.TransactionInputsCache =
function TransactionInputsCache(tx)
{
var txList = [];
var txList64 = [];
var reqOuts = {};
// Get list of transactions required for verification
tx.ins.forEach(function (txin) {
if (txin.isCoinBase()) return;
var hash = txin.o.slice(0, 32);
var hash64 = hash.toString('base64');
if (txList64.indexOf(hash64) == -1) {
txList.push(hash);
txList64.push(hash64);
}
if (!reqOuts[hash64]) {
reqOuts[hash64] = [];
}
reqOuts[hash64][txin.getOutpointIndex()] = true;
});
this.tx = tx;
this.txList = txList;
this.txList64 = txList64;
this.txIndex = {};
this.requiredOuts = reqOuts;
this.callbacks = [];
};
TransactionInputsCache.prototype.buffer = function buffer(blockChain, txStore, wait, callback)
{
var self = this;
var complete = false;
if ("function" === typeof callback) {
self.callbacks.push(callback);
}
var missingTx = {};
self.txList64.forEach(function (hash64) {
missingTx[hash64] = true;
});
// A utility function to create the index object from the txs result lists
function indexTxs(err, txs) {
if (err) throw err;
// Index memory transactions
txs.forEach(function (tx) {
var hash64 = tx.getHash().toString('base64');
var obj = {};
Object.keys(self.requiredOuts[hash64]).forEach(function (o) {
obj[+o] = tx.outs[+o];
});
self.txIndex[hash64] = obj;
delete missingTx[hash64];
});
this(null);
};
Step(
// First find and index memory transactions (if a txStore was provided)
function findMemTx() {
if (txStore) {
txStore.find(self.txList64, this);
} else {
this(null, []);
}
},
indexTxs,
// Second find and index persistent transactions
function findBlockChainTx(err) {
if (err) throw err;
// TODO: Major speedup should be possible if we load only the outs and not
// whole transactions.
var callback = this;
blockChain.getOutputsByHashes(self.txList, function (err, result) {
callback(err, result);
});
},
indexTxs,
function saveTxCache(err) {
if (err) throw err;
var missingTxDbg = '';
if (Object.keys(missingTx).length) {
missingTxDbg = Object.keys(missingTx).map(function (hash64) {
return util.formatHash(new Buffer(hash64, 'base64'));
}).join(',');
}
if (wait && Object.keys(missingTx).length) {
// TODO: This might no longer be needed now that saveTransactions uses
// the safe=true option.
setTimeout(function () {
var missingHashes = Object.keys(missingTx);
if (missingHashes.length) {
self.callback(new Error('Missing inputs (timeout while searching): '
+ missingTxDbg));
} else if (!complete) {
self.callback(new Error('Callback failed to trigger'));
}
}, 10000);
} else {
complete = true;
this(null, self);
}
},
self.callback.bind(self)
);
};
TransactionInputsCache.prototype.callback = function callback(err)
{
var args = Array.prototype.slice.apply(arguments);
// Empty the callback array first (because downstream functions could add new
// callbacks or otherwise interfere if were not in a consistent state.)
var cbs = this.callbacks;
this.callbacks = [];
try {
cbs.forEach(function (cb) {
cb.apply(null, args);
});
} catch (err) {
log.err("Callback error after connecting tx inputs: "+
(err.stack ? err.stack : err.toString()));
}
};
module.exports = require('soop')(Transaction);
| 1 | 12,321 | I'm not totally sure I like the idea of putting a default fee here, but I guess so long as we make sure to track the default fee of bitcoin core, we're good. We should really also take a look at the byte size of the transaction, and use that to determine what the fee should be. But that could also be a different PR. | bitpay-bitcore | js |
@@ -17,13 +17,13 @@
* </thead>
* <tbody>
* <tr><td>{@linkplain javaslang.collection.Array}</td><td><small>const</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td></tr>
- * <tr><td>{@linkplain javaslang.collection.CharSeq}</td><td><small>const</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>linear</small></td></tr>
- * <tr><td><em>{@linkplain javaslang.collection.Iterator}</em></td><td><small>const</small></td><td><small>const</small></td><td>—</td><td>—</td><td>—</td><td>—</td></tr>
+ * <tr><td>{@linkplain javaslang.collection.CharSeq}</td><td><small>const</small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td></tr>
+ * <tr><td>{@linkplain javaslang.collection.Iterator}</td><td><small>const</small></td><td><small>const</small></td><td>—</td><td>—</td><td>—</td><td>—</td></tr>
* <tr><td>{@linkplain javaslang.collection.List}</td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>linear</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.Queue}</td><td><small>const</small></td><td><small>const<sup>a</sup></small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>const</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.PriorityQueue}</td><td><small>log</small></td><td><small>log</small></td><td><small>—</small></td><td><small>—</small></td><td><small>log</small></td><td><small>log</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.Stream}</td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const<sup>lazy</sup></small></td><td><small>const<sup>lazy</sup></small></td></tr>
- * <tr><td>{@linkplain javaslang.collection.Vector}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td></tr>
+ * <tr><td>{@linkplain javaslang.collection.Vector}</td><td><small>const</small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td></tr>
* </tbody>
* </table>
* <br> | 1 | /**
* Purely functional collections based on {@linkplain javaslang.collection.Traversable}.
*
* <h2>Performance Characteristics of Javaslang Collections</h2>
* <table cellpadding="5" cellspacing="0" border="1" style="border-collapse: collapse">
* <caption>Time Complexity of Sequential Operations</caption>
* <thead>
* <tr>
* <th> </th>
* <th>head()</th>
* <th>tail()</th>
* <th>get(int)</th>
* <th>update(int, T)</th>
* <th>prepend(T)</th>
* <th>append(T)</th>
* </tr>
* </thead>
* <tbody>
* <tr><td>{@linkplain javaslang.collection.Array}</td><td><small>const</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.CharSeq}</td><td><small>const</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>linear</small></td></tr>
* <tr><td><em>{@linkplain javaslang.collection.Iterator}</em></td><td><small>const</small></td><td><small>const</small></td><td>—</td><td>—</td><td>—</td><td>—</td></tr>
* <tr><td>{@linkplain javaslang.collection.List}</td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>linear</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.Queue}</td><td><small>const</small></td><td><small>const<sup>a</sup></small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>const</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.PriorityQueue}</td><td><small>log</small></td><td><small>log</small></td><td><small>—</small></td><td><small>—</small></td><td><small>log</small></td><td><small>log</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.Stream}</td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const<sup>lazy</sup></small></td><td><small>const<sup>lazy</sup></small></td></tr>
* <tr><td>{@linkplain javaslang.collection.Vector}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td></tr>
* </tbody>
* </table>
* <br>
* <table cellpadding="5" cellspacing="0" border="1" style="border-collapse: collapse">
* <caption>Time Complexity of Map/Set Operations</caption>
* <thead>
* <tr>
* <th> </th>
* <th>contains/Key</th>
* <th>add/put</th>
* <th>remove</th>
* <th>min</th>
* </tr>
* </thead>
* <tbody>
* <tr><td>{@linkplain javaslang.collection.HashMap}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>linear</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.HashSet}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>linear</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.LinkedHashMap}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>linear</small></td><td><small>linear</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.LinkedHashSet}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>linear</small></td><td><small>linear</small></td></tr>
* <tr><td><em>{@linkplain javaslang.collection.Tree}</em></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.TreeMap}</td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td></tr>
* <tr><td>{@linkplain javaslang.collection.TreeSet}</td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td></tr>
* </tbody>
* </table>
* <br>
* <ul>
* <li><small>const</small> · constant time</li>
* <li><small>const<sup>a</sup></small> · amotized constant time, few operations may take longer</li>
* <li><small>const<sup>eff</sup></small> · effectively constant time, depending on assumptions like distribution of hash keys</li>
* <li><small>const<sup>lazy</sup></small> · lazy constant time, the operation is deferred</li>
* <li><small>log</small> · logarithmic time</li>
* <li><small>linear</small> · linear time</li>
* </ul>
*
* @since 1.1.0
*/
package javaslang.collection;
| 1 | 9,243 | oh yeah, `tail`, `update`, `prepend`, `append`, `subSequence`, `trim` just became effectively constant (without memory leak) :) | vavr-io-vavr | java |
@@ -232,15 +232,12 @@ class ResourceTags extends Gateway
*
* @return void
*/
- public function destroyLinks($resource, $user, $list = null, $tag = null)
+ public function destroyResourceLinks($resource, $user, $list = null, $tag = null)
{
$callback = function ($select) use ($resource, $user, $list, $tag) {
$select->where->equalTo('user_id', $user);
if (null !== $resource) {
- if (!is_array($resource)) {
- $resource = [$resource];
- }
- $select->where->in('resource_id', $resource);
+ $select->where->in('resource_id', (array)$resource);
}
if (null !== $list) {
if (true === $list) { | 1 | <?php
/**
* Table Definition for resource_tags
*
* PHP version 7
*
* Copyright (C) Villanova University 2010.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Db_Table
* @author Demian Katz <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
namespace VuFind\Db\Table;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Sql\Expression;
use VuFind\Db\Row\RowGateway;
/**
* Table Definition for resource_tags
*
* @category VuFind
* @package Db_Table
* @author Demian Katz <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
class ResourceTags extends Gateway
{
/**
* Are tags case sensitive?
*
* @var bool
*/
protected $caseSensitive;
/**
* Constructor
*
* @param Adapter $adapter Database adapter
* @param PluginManager $tm Table manager
* @param array $cfg Laminas configuration
* @param RowGateway $rowObj Row prototype object (null for default)
* @param bool $caseSensitive Are tags case sensitive?
* @param string $table Name of database table to interface with
*/
public function __construct(Adapter $adapter, PluginManager $tm, $cfg,
RowGateway $rowObj = null, $caseSensitive = false, $table = 'resource_tags'
) {
$this->caseSensitive = $caseSensitive;
parent::__construct($adapter, $tm, $cfg, $rowObj, $table);
}
/**
* Look up a row for the specified resource.
*
* @param string $resource ID of resource to link up
* @param string $tag ID of tag to link up
* @param string $user ID of user creating link (optional but recommended)
* @param string $list ID of list to link up (optional)
* @param string $posted Posted date (optional -- omit for current)
*
* @return void
*/
public function createLink($resource, $tag, $user = null, $list = null,
$posted = null
) {
$callback = function ($select) use ($resource, $tag, $user, $list) {
$select->where->equalTo('resource_id', $resource)
->equalTo('tag_id', $tag);
if (null !== $list) {
$select->where->equalTo('list_id', $list);
} else {
$select->where->isNull('list_id');
}
if (null !== $user) {
$select->where->equalTo('user_id', $user);
} else {
$select->where->isNull('user_id');
}
};
$result = $this->select($callback)->current();
// Only create row if it does not already exist:
if (empty($result)) {
$result = $this->createRow();
$result->resource_id = $resource;
$result->tag_id = $tag;
if (null !== $list) {
$result->list_id = $list;
}
if (null !== $user) {
$result->user_id = $user;
}
if (null !== $posted) {
$result->posted = $posted;
}
$result->save();
}
}
/**
* Check whether or not the specified tags are present in the table.
*
* @param array $ids IDs to check.
*
* @return array Associative array with two keys: present and missing
*/
public function checkForTags($ids)
{
// Set up return arrays:
$retVal = ['present' => [], 'missing' => []];
// Look up IDs in the table:
$callback = function ($select) use ($ids) {
$select->where->in('tag_id', $ids);
};
$results = $this->select($callback);
// Record all IDs that are present:
foreach ($results as $current) {
$retVal['present'][] = $current->tag_id;
}
$retVal['present'] = array_unique($retVal['present']);
// Detect missing IDs:
foreach ($ids as $current) {
if (!in_array($current, $retVal['present'])) {
$retVal['missing'][] = $current;
}
}
// Send back the results:
return $retVal;
}
/**
* Get resources associated with a particular tag.
*
* @param string $tag Tag to match
* @param string $userId ID of user owning favorite list
* @param string $listId ID of list to retrieve (null for all favorites)
*
* @return \Laminas\Db\ResultSet\AbstractResultSet
*/
public function getResourcesForTag($tag, $userId, $listId = null)
{
$callback = function ($select) use ($tag, $userId, $listId) {
$select->columns(
[
'resource_id' => new Expression(
'DISTINCT(?)', ['resource_tags.resource_id'],
[Expression::TYPE_IDENTIFIER]
), '*'
]
);
$select->join(
['t' => 'tags'], 'resource_tags.tag_id = t.id', []
);
if ($this->caseSensitive) {
$select->where->equalTo('t.tag', $tag);
} else {
$select->where->literal('lower(t.tag) = lower(?)', [$tag]);
}
$select->where->equalTo('resource_tags.user_id', $userId);
if (null !== $listId) {
$select->where->equalTo('resource_tags.list_id', $listId);
}
};
return $this->select($callback);
}
/**
* Get statistics on use of tags.
*
* @param bool $extended Include extended (unique/anonymous) stats.
*
* @return array
*/
public function getStatistics($extended = false)
{
$select = $this->sql->select();
$select->columns(
[
'users' => new Expression(
'COUNT(DISTINCT(?))', ['user_id'],
[Expression::TYPE_IDENTIFIER]
),
'resources' => new Expression(
'COUNT(DISTINCT(?))', ['resource_id'],
[Expression::TYPE_IDENTIFIER]
),
'total' => new Expression('COUNT(*)')
]
);
$statement = $this->sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$stats = (array)$result->current();
if ($extended) {
$stats['unique'] = count($this->getUniqueTags());
$stats['anonymous'] = $this->getAnonymousCount();
}
return $stats;
}
/**
* Unlink rows for the specified resource.
*
* @param string|array $resource ID (or array of IDs) of resource(s) to
* unlink (null for ALL matching resources)
* @param string $user ID of user removing links
* @param string $list ID of list to unlink (null for ALL matching
* tags, 'none' for tags not in a list, true for tags only found in a list)
* @param string|array $tag ID or array of IDs of tag(s) to unlink (null
* for ALL matching tags)
*
* @return void
*/
public function destroyLinks($resource, $user, $list = null, $tag = null)
{
$callback = function ($select) use ($resource, $user, $list, $tag) {
$select->where->equalTo('user_id', $user);
if (null !== $resource) {
if (!is_array($resource)) {
$resource = [$resource];
}
$select->where->in('resource_id', $resource);
}
if (null !== $list) {
if (true === $list) {
// special case -- if $list is set to boolean true, we
// want to only delete tags that are associated with lists.
$select->where->isNotNull('list_id');
} elseif ('none' === $list) {
// special case -- if $list is set to the string "none", we
// want to delete tags that are not associated with lists.
$select->where->isNull('list_id');
} else {
$select->where->equalTo('list_id', $list);
}
}
if (null !== $tag) {
if (is_array($tag)) {
$select->where->in('tag_id', $tag);
} else {
$select->where->equalTo('tag_id', $tag);
}
}
};
// Get a list of all tag IDs being deleted; we'll use these for
// orphan-checking:
$potentialOrphans = $this->select($callback);
// Now delete the unwanted rows:
$this->delete($callback);
// Check for orphans:
if (count($potentialOrphans) > 0) {
$ids = [];
foreach ($potentialOrphans as $current) {
$ids[] = $current->tag_id;
}
$checkResults = $this->checkForTags(array_unique($ids));
if (count($checkResults['missing']) > 0) {
$tagTable = $this->getDbTable('Tags');
$tagTable->deleteByIdArray($checkResults['missing']);
}
}
}
/**
* Get count of anonymous tags
*
* @return int count
*/
public function getAnonymousCount()
{
$callback = function ($select) {
$select->where->isNull('user_id');
};
return count($this->select($callback));
}
/**
* Assign anonymous tags to the specified user ID.
*
* @param int $id User ID to own anonymous tags.
*
* @return void
*/
public function assignAnonymousTags($id)
{
$callback = function ($select) {
$select->where->isNull('user_id');
};
$this->update(['user_id' => $id], $callback);
}
/**
* Gets unique resources from the table
*
* @param string $userId ID of user
* @param string $resourceId ID of the resource
* @param string $tagId ID of the tag
*
* @return \Laminas\Db\ResultSet\AbstractResultSet
*/
public function getUniqueResources(
$userId = null, $resourceId = null, $tagId = null
) {
$callback = function ($select) use ($userId, $resourceId, $tagId) {
$select->columns(
[
'resource_id' => new Expression(
'MAX(?)', ['resource_tags.resource_id'],
[Expression::TYPE_IDENTIFIER]
),
'tag_id' => new Expression(
'MAX(?)', ['resource_tags.tag_id'],
[Expression::TYPE_IDENTIFIER]
),
'list_id' => new Expression(
'MAX(?)', ['resource_tags.list_id'],
[Expression::TYPE_IDENTIFIER]
),
'user_id' => new Expression(
'MAX(?)', ['resource_tags.user_id'],
[Expression::TYPE_IDENTIFIER]
),
'id' => new Expression(
'MAX(?)', ['resource_tags.id'],
[Expression::TYPE_IDENTIFIER]
)
]
);
$select->join(
['r' => 'resource'],
'resource_tags.resource_id = r.id',
["title" => "title"]
);
if (null !== $userId) {
$select->where->equalTo('resource_tags.user_id', $userId);
}
if (null !== $resourceId) {
$select->where->equalTo('resource_tags.resource_id', $resourceId);
}
if (null !== $tagId) {
$select->where->equalTo('resource_tags.tag_id', $tagId);
}
$select->group(['resource_id', 'title']);
$select->order(['title']);
};
return $this->select($callback);
}
/**
* Gets unique tags from the table
*
* @param string $userId ID of user
* @param string $resourceId ID of the resource
* @param string $tagId ID of the tag
*
* @return \Laminas\Db\ResultSet\AbstractResultSet
*/
public function getUniqueTags($userId = null, $resourceId = null, $tagId = null)
{
$callback = function ($select) use ($userId, $resourceId, $tagId) {
$select->columns(
[
'resource_id' => new Expression(
'MAX(?)', ['resource_tags.resource_id'],
[Expression::TYPE_IDENTIFIER]
),
'tag_id' => new Expression(
'MAX(?)', ['resource_tags.tag_id'],
[Expression::TYPE_IDENTIFIER]
),
'list_id' => new Expression(
'MAX(?)', ['resource_tags.list_id'],
[Expression::TYPE_IDENTIFIER]
),
'user_id' => new Expression(
'MAX(?)', ['resource_tags.user_id'],
[Expression::TYPE_IDENTIFIER]
),
'id' => new Expression(
'MAX(?)', ['resource_tags.id'],
[Expression::TYPE_IDENTIFIER]
)
]
);
$select->join(
['t' => 'tags'],
'resource_tags.tag_id = t.id',
[
'tag' =>
$this->caseSensitive ? 'tag' : new Expression('lower(tag)')
]
);
if (null !== $userId) {
$select->where->equalTo('resource_tags.user_id', $userId);
}
if (null !== $resourceId) {
$select->where->equalTo('resource_tags.resource_id', $resourceId);
}
if (null !== $tagId) {
$select->where->equalTo('resource_tags.tag_id', $tagId);
}
$select->group(['tag_id', 'tag']);
$select->order([new Expression('lower(tag)')]);
};
return $this->select($callback);
}
/**
* Gets unique users from the table
*
* @param string $userId ID of user
* @param string $resourceId ID of the resource
* @param string $tagId ID of the tag
*
* @return \Laminas\Db\ResultSet\AbstractResultSet
*/
public function getUniqueUsers($userId = null, $resourceId = null, $tagId = null)
{
$callback = function ($select) use ($userId, $resourceId, $tagId) {
$select->columns(
[
'resource_id' => new Expression(
'MAX(?)', ['resource_tags.resource_id'],
[Expression::TYPE_IDENTIFIER]
),
'tag_id' => new Expression(
'MAX(?)', ['resource_tags.tag_id'],
[Expression::TYPE_IDENTIFIER]
),
'list_id' => new Expression(
'MAX(?)', ['resource_tags.list_id'],
[Expression::TYPE_IDENTIFIER]
),
'user_id' => new Expression(
'MAX(?)', ['resource_tags.user_id'],
[Expression::TYPE_IDENTIFIER]
),
'id' => new Expression(
'MAX(?)', ['resource_tags.id'],
[Expression::TYPE_IDENTIFIER]
)
]
);
$select->join(
['u' => 'user'],
'resource_tags.user_id = u.id',
["username" => "username"]
);
if (null !== $userId) {
$select->where->equalTo('resource_tags.user_id', $userId);
}
if (null !== $resourceId) {
$select->where->equalTo('resource_tags.resource_id', $resourceId);
}
if (null !== $tagId) {
$select->where->equalTo('resource_tags.tag_id', $tagId);
}
$select->group(['user_id', 'username']);
$select->order(['username']);
};
return $this->select($callback);
}
/**
* Given an array for sorting database results, make sure the tag field is
* sorted in a case-insensitive fashion.
*
* @param array $order Order settings
*
* @return array
*/
protected function formatTagOrder($order)
{
if (empty($order)) {
return $order;
}
$newOrder = [];
foreach ((array)$order as $current) {
$newOrder[] = $current == 'tag'
? new Expression('lower(tag)') : $current;
}
return $newOrder;
}
/**
* Get Resource Tags
*
* @param string $userId ID of user
* @param string $resourceId ID of the resource
* @param string $tagId ID of the tag
* @param string $order The order in which to return the data
* @param string $page The page number to select
* @param string $limit The number of items to fetch
*
* @return \Laminas\Paginator\Paginator
*/
public function getResourceTags(
$userId = null, $resourceId = null, $tagId = null,
$order = null, $page = null, $limit = 20
) {
$order = (null !== $order)
? [$order]
: ["username", "tag", "title"];
$sql = $this->getSql();
$select = $sql->select();
$select->join(
['t' => 'tags'],
'resource_tags.tag_id = t.id',
[
'tag' =>
$this->caseSensitive ? 'tag' : new Expression('lower(tag)')
]
);
$select->join(
['u' => 'user'],
'resource_tags.user_id = u.id',
["username" => "username"]
);
$select->join(
['r' => 'resource'],
'resource_tags.resource_id = r.id',
["title" => "title"]
);
if (null !== $userId) {
$select->where->equalTo('resource_tags.user_id', $userId);
}
if (null !== $resourceId) {
$select->where->equalTo('resource_tags.resource_id', $resourceId);
}
if (null !== $tagId) {
$select->where->equalTo('resource_tags.tag_id', $tagId);
}
$select->order($this->formatTagOrder($order));
if (null !== $page) {
$select->limit($limit);
$select->offset($limit * ($page - 1));
}
$adapter = new \Laminas\Paginator\Adapter\DbSelect($select, $sql);
$paginator = new \Laminas\Paginator\Paginator($adapter);
$paginator->setItemCountPerPage($limit);
if (null !== $page) {
$paginator->setCurrentPageNumber($page);
}
return $paginator;
}
/**
* Delete a group of tags.
*
* @param array $ids IDs of tags to delete.
*
* @return int Count of $ids
*/
public function deleteByIdArray($ids)
{
// Do nothing if we have no IDs to delete!
if (empty($ids)) {
return;
}
$callback = function ($select) use ($ids) {
$select->where->in('id', $ids);
};
$this->delete($callback);
return count($ids);
}
/**
* Get a list of duplicate rows (this sometimes happens after merging IDs,
* for example after a Summon resource ID changes).
*
* @return mixed
*/
public function getDuplicates()
{
$callback = function ($select) {
$select->columns(
[
'resource_id' => new Expression(
'MIN(?)', ['resource_id'], [Expression::TYPE_IDENTIFIER]
),
'tag_id' => new Expression(
'MIN(?)', ['tag_id'], [Expression::TYPE_IDENTIFIER]
),
'list_id' => new Expression(
'MIN(?)', ['list_id'], [Expression::TYPE_IDENTIFIER]
),
'user_id' => new Expression(
'MIN(?)', ['user_id'], [Expression::TYPE_IDENTIFIER]
),
'cnt' => new Expression(
'COUNT(?)', ['resource_id'], [Expression::TYPE_IDENTIFIER]
),
'id' => new Expression(
'MIN(?)', ['id'], [Expression::TYPE_IDENTIFIER]
)
]
);
$select->group(['resource_id', 'tag_id', 'list_id', 'user_id']);
$select->having('COUNT(resource_id) > 1');
};
return $this->select($callback);
}
/**
* Deduplicate rows (sometimes necessary after merging foreign key IDs).
*
* @return void
*/
public function deduplicate()
{
foreach ($this->getDuplicates() as $dupe) {
$callback = function ($select) use ($dupe) {
// match on all relevant IDs in duplicate group
$select->where(
[
'resource_id' => $dupe['resource_id'],
'tag_id' => $dupe['tag_id'],
'list_id' => $dupe['list_id'],
'user_id' => $dupe['user_id'],
]
);
// getDuplicates returns the minimum id in the set, so we want to
// delete all of the duplicates with a higher id value.
$select->where->greaterThan('id', $dupe['id']);
};
$this->delete($callback);
}
}
}
| 1 | 29,688 | Can you add back a deprecated `destroyLinks` method for backward compatibility? It can simply proxy `destroyResourceLinks`, and we can remove it in the next major release. | vufind-org-vufind | php |
@@ -43,6 +43,7 @@ func init() {
RegisterGlobalOption("local_certs", parseOptTrue)
RegisterGlobalOption("key_type", parseOptSingleString)
RegisterGlobalOption("auto_https", parseOptAutoHTTPS)
+ RegisterGlobalOption("servers", parseServerOptions)
}
func parseOptTrue(d *caddyfile.Dispenser) (interface{}, error) { | 1 | // Copyright 2015 Matthew Holt and The Caddy 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 httpcaddyfile
import (
"strconv"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/modules/caddytls"
"github.com/caddyserver/certmagic"
"github.com/mholt/acmez/acme"
)
func init() {
RegisterGlobalOption("debug", parseOptTrue)
RegisterGlobalOption("http_port", parseOptHTTPPort)
RegisterGlobalOption("https_port", parseOptHTTPSPort)
RegisterGlobalOption("default_sni", parseOptSingleString)
RegisterGlobalOption("order", parseOptOrder)
RegisterGlobalOption("experimental_http3", parseOptTrue)
RegisterGlobalOption("storage", parseOptStorage)
RegisterGlobalOption("acme_ca", parseOptSingleString)
RegisterGlobalOption("acme_ca_root", parseOptSingleString)
RegisterGlobalOption("acme_dns", parseOptSingleString)
RegisterGlobalOption("acme_eab", parseOptACMEEAB)
RegisterGlobalOption("cert_issuer", parseOptCertIssuer)
RegisterGlobalOption("email", parseOptSingleString)
RegisterGlobalOption("admin", parseOptAdmin)
RegisterGlobalOption("on_demand_tls", parseOptOnDemand)
RegisterGlobalOption("local_certs", parseOptTrue)
RegisterGlobalOption("key_type", parseOptSingleString)
RegisterGlobalOption("auto_https", parseOptAutoHTTPS)
}
func parseOptTrue(d *caddyfile.Dispenser) (interface{}, error) {
return true, nil
}
func parseOptHTTPPort(d *caddyfile.Dispenser) (interface{}, error) {
var httpPort int
for d.Next() {
var httpPortStr string
if !d.AllArgs(&httpPortStr) {
return 0, d.ArgErr()
}
var err error
httpPort, err = strconv.Atoi(httpPortStr)
if err != nil {
return 0, d.Errf("converting port '%s' to integer value: %v", httpPortStr, err)
}
}
return httpPort, nil
}
func parseOptHTTPSPort(d *caddyfile.Dispenser) (interface{}, error) {
var httpsPort int
for d.Next() {
var httpsPortStr string
if !d.AllArgs(&httpsPortStr) {
return 0, d.ArgErr()
}
var err error
httpsPort, err = strconv.Atoi(httpsPortStr)
if err != nil {
return 0, d.Errf("converting port '%s' to integer value: %v", httpsPortStr, err)
}
}
return httpsPort, nil
}
func parseOptOrder(d *caddyfile.Dispenser) (interface{}, error) {
newOrder := directiveOrder
for d.Next() {
// get directive name
if !d.Next() {
return nil, d.ArgErr()
}
dirName := d.Val()
if _, ok := registeredDirectives[dirName]; !ok {
return nil, d.Errf("%s is not a registered directive", dirName)
}
// get positional token
if !d.Next() {
return nil, d.ArgErr()
}
pos := d.Val()
// if directive exists, first remove it
for i, d := range newOrder {
if d == dirName {
newOrder = append(newOrder[:i], newOrder[i+1:]...)
break
}
}
// act on the positional
switch pos {
case "first":
newOrder = append([]string{dirName}, newOrder...)
if d.NextArg() {
return nil, d.ArgErr()
}
directiveOrder = newOrder
return newOrder, nil
case "last":
newOrder = append(newOrder, dirName)
if d.NextArg() {
return nil, d.ArgErr()
}
directiveOrder = newOrder
return newOrder, nil
case "before":
case "after":
default:
return nil, d.Errf("unknown positional '%s'", pos)
}
// get name of other directive
if !d.NextArg() {
return nil, d.ArgErr()
}
otherDir := d.Val()
if d.NextArg() {
return nil, d.ArgErr()
}
// insert directive into proper position
for i, d := range newOrder {
if d == otherDir {
if pos == "before" {
newOrder = append(newOrder[:i], append([]string{dirName}, newOrder[i:]...)...)
} else if pos == "after" {
newOrder = append(newOrder[:i+1], append([]string{dirName}, newOrder[i+1:]...)...)
}
break
}
}
}
directiveOrder = newOrder
return newOrder, nil
}
func parseOptStorage(d *caddyfile.Dispenser) (interface{}, error) {
if !d.Next() { // consume option name
return nil, d.ArgErr()
}
if !d.Next() { // get storage module name
return nil, d.ArgErr()
}
modName := d.Val()
mod, err := caddy.GetModule("caddy.storage." + modName)
if err != nil {
return nil, d.Errf("getting storage module '%s': %v", modName, err)
}
unm, ok := mod.New().(caddyfile.Unmarshaler)
if !ok {
return nil, d.Errf("storage module '%s' is not a Caddyfile unmarshaler", mod.ID)
}
err = unm.UnmarshalCaddyfile(d.NewFromNextSegment())
if err != nil {
return nil, err
}
storage, ok := unm.(caddy.StorageConverter)
if !ok {
return nil, d.Errf("module %s is not a StorageConverter", mod.ID)
}
return storage, nil
}
func parseOptACMEEAB(d *caddyfile.Dispenser) (interface{}, error) {
eab := new(acme.EAB)
for d.Next() {
if d.NextArg() {
return nil, d.ArgErr()
}
for nesting := d.Nesting(); d.NextBlock(nesting); {
switch d.Val() {
case "key_id":
if !d.NextArg() {
return nil, d.ArgErr()
}
eab.KeyID = d.Val()
case "mac_key":
if !d.NextArg() {
return nil, d.ArgErr()
}
eab.MACKey = d.Val()
default:
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
}
}
}
return eab, nil
}
func parseOptCertIssuer(d *caddyfile.Dispenser) (interface{}, error) {
if !d.Next() { // consume option name
return nil, d.ArgErr()
}
if !d.Next() { // get issuer module name
return nil, d.ArgErr()
}
modName := d.Val()
mod, err := caddy.GetModule("tls.issuance." + modName)
if err != nil {
return nil, d.Errf("getting issuer module '%s': %v", modName, err)
}
unm, ok := mod.New().(caddyfile.Unmarshaler)
if !ok {
return nil, d.Errf("issuer module '%s' is not a Caddyfile unmarshaler", mod.ID)
}
err = unm.UnmarshalCaddyfile(d.NewFromNextSegment())
if err != nil {
return nil, err
}
iss, ok := unm.(certmagic.Issuer)
if !ok {
return nil, d.Errf("module %s is not a certmagic.Issuer", mod.ID)
}
return iss, nil
}
func parseOptSingleString(d *caddyfile.Dispenser) (interface{}, error) {
d.Next() // consume parameter name
if !d.Next() {
return "", d.ArgErr()
}
val := d.Val()
if d.Next() {
return "", d.ArgErr()
}
return val, nil
}
func parseOptAdmin(d *caddyfile.Dispenser) (interface{}, error) {
adminCfg := new(caddy.AdminConfig)
for d.Next() {
if d.NextArg() {
listenAddress := d.Val()
if listenAddress == "off" {
adminCfg.Disabled = true
if d.Next() { // Do not accept any remaining options including block
return nil, d.Err("No more option is allowed after turning off admin config")
}
} else {
adminCfg.Listen = listenAddress
if d.NextArg() { // At most 1 arg is allowed
return nil, d.ArgErr()
}
}
}
for nesting := d.Nesting(); d.NextBlock(nesting); {
switch d.Val() {
case "enforce_origin":
adminCfg.EnforceOrigin = true
case "origins":
adminCfg.Origins = d.RemainingArgs()
default:
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
}
}
}
if adminCfg.Listen == "" && !adminCfg.Disabled {
adminCfg.Listen = caddy.DefaultAdminListen
}
return adminCfg, nil
}
func parseOptOnDemand(d *caddyfile.Dispenser) (interface{}, error) {
var ond *caddytls.OnDemandConfig
for d.Next() {
if d.NextArg() {
return nil, d.ArgErr()
}
for nesting := d.Nesting(); d.NextBlock(nesting); {
switch d.Val() {
case "ask":
if !d.NextArg() {
return nil, d.ArgErr()
}
if ond == nil {
ond = new(caddytls.OnDemandConfig)
}
ond.Ask = d.Val()
case "interval":
if !d.NextArg() {
return nil, d.ArgErr()
}
dur, err := caddy.ParseDuration(d.Val())
if err != nil {
return nil, err
}
if ond == nil {
ond = new(caddytls.OnDemandConfig)
}
if ond.RateLimit == nil {
ond.RateLimit = new(caddytls.RateLimit)
}
ond.RateLimit.Interval = caddy.Duration(dur)
case "burst":
if !d.NextArg() {
return nil, d.ArgErr()
}
burst, err := strconv.Atoi(d.Val())
if err != nil {
return nil, err
}
if ond == nil {
ond = new(caddytls.OnDemandConfig)
}
if ond.RateLimit == nil {
ond.RateLimit = new(caddytls.RateLimit)
}
ond.RateLimit.Burst = burst
default:
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
}
}
}
if ond == nil {
return nil, d.Err("expected at least one config parameter for on_demand_tls")
}
return ond, nil
}
func parseOptAutoHTTPS(d *caddyfile.Dispenser) (interface{}, error) {
d.Next() // consume parameter name
if !d.Next() {
return "", d.ArgErr()
}
val := d.Val()
if d.Next() {
return "", d.ArgErr()
}
if val != "off" && val != "disable_redirects" {
return "", d.Errf("auto_https must be either 'off' or 'disable_redirects'")
}
return val, nil
}
| 1 | 15,872 | A reminder that we should discuss whether to rename this to "sockets" or "listeners". | caddyserver-caddy | go |
@@ -39,6 +39,7 @@ using eprosima::fastdds::dds::Log;
using eprosima::fastrtps::rtps::RTPSDomain;
using eprosima::fastrtps::rtps::RTPSParticipant;
+using eprosima::fastrtps::rtps::RTPSParticipantAttributes;
namespace eprosima {
namespace fastdds { | 1 | // Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file DomainParticipantFactory.cpp
*
*/
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/rtps/RTPSDomain.h>
#include <fastdds/rtps/participant/RTPSParticipant.h>
#include <fastdds/dds/domain/DomainParticipant.hpp>
#include <fastdds/domain/DomainParticipantImpl.hpp>
#include <fastdds/dds/log/Log.hpp>
#include <fastrtps/xmlparser/XMLProfileManager.h>
#include <fastrtps/types/DynamicTypeBuilderFactory.h>
#include <fastrtps/types/DynamicDataFactory.h>
#include <fastrtps/types/TypeObjectFactory.h>
using namespace eprosima::fastrtps::xmlparser;
using eprosima::fastrtps::ParticipantAttributes;
using eprosima::fastdds::dds::Log;
using eprosima::fastrtps::rtps::RTPSDomain;
using eprosima::fastrtps::rtps::RTPSParticipant;
namespace eprosima {
namespace fastdds {
namespace dds {
static void set_qos_from_attributes(
DomainParticipantQos& qos,
const eprosima::fastrtps::rtps::RTPSParticipantAttributes& attr)
{
qos.user_data().setValue(attr.userData);
qos.allocation() = attr.allocation;
qos.properties() = attr.properties;
qos.wire_protocol().prefix = attr.prefix;
qos.wire_protocol().participant_id = attr.participantID;
qos.wire_protocol().builtin = attr.builtin;
qos.wire_protocol().port = attr.port;
qos.wire_protocol().throughput_controller = attr.throughputController;
qos.wire_protocol().default_unicast_locator_list = attr.defaultUnicastLocatorList;
qos.wire_protocol().default_multicast_locator_list = attr.defaultMulticastLocatorList;
qos.transport().user_transports = attr.userTransports;
qos.transport().use_builtin_transports = attr.useBuiltinTransports;
qos.transport().send_socket_buffer_size = attr.sendSocketBufferSize;
qos.transport().listen_socket_buffer_size = attr.listenSocketBufferSize;
qos.name() = attr.getName();
}
DomainParticipantFactory::DomainParticipantFactory()
: default_xml_profiles_loaded(false)
, default_participant_qos_(PARTICIPANT_QOS_DEFAULT)
{
}
DomainParticipantFactory::~DomainParticipantFactory()
{
{
std::lock_guard<std::mutex> guard(mtx_participants_);
for (auto it : participants_)
{
for (auto pit : it.second)
{
pit->disable();
delete pit;
}
}
participants_.clear();
}
// Deletes DynamicTypes and TypeObject factories
fastrtps::types::DynamicTypeBuilderFactory::delete_instance();
fastrtps::types::DynamicDataFactory::delete_instance();
fastrtps::types::TypeObjectFactory::delete_instance();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
eprosima::fastdds::dds::Log::KillThread();
}
DomainParticipantFactory* DomainParticipantFactory::get_instance()
{
static DomainParticipantFactory instance;
return &instance;
}
ReturnCode_t DomainParticipantFactory::delete_participant(
DomainParticipant* part)
{
using PartVectorIt = std::vector<DomainParticipantImpl*>::iterator;
using VectorIt = std::map<DomainId_t, std::vector<DomainParticipantImpl*> >::iterator;
if (part != nullptr)
{
if (part->has_active_entities())
{
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
std::lock_guard<std::mutex> guard(mtx_participants_);
VectorIt vit = participants_.find(part->get_domain_id());
if (vit != participants_.end())
{
for (PartVectorIt pit = vit->second.begin(); pit != vit->second.end();)
{
if ((*pit)->get_participant() == part
|| (*pit)->get_participant()->guid() == part->guid())
{
(*pit)->disable();
delete (*pit);
PartVectorIt next_it = vit->second.erase(pit);
pit = next_it;
break;
}
else
{
++pit;
}
}
if (vit->second.empty())
{
participants_.erase(vit);
}
return ReturnCode_t::RETCODE_OK;
}
}
return ReturnCode_t::RETCODE_ERROR;
}
DomainParticipant* DomainParticipantFactory::create_participant(
DomainId_t did,
const DomainParticipantQos& qos,
DomainParticipantListener* listen,
const StatusMask& mask)
{
load_profiles();
const DomainParticipantQos& pqos = (&qos == &PARTICIPANT_QOS_DEFAULT) ? default_participant_qos_ : qos;
DomainParticipant* dom_part = new DomainParticipant(mask);
DomainParticipantImpl* dom_part_impl = new DomainParticipantImpl(dom_part, did, pqos, listen);
{
std::lock_guard<std::mutex> guard(mtx_participants_);
using VectorIt = std::map<DomainId_t, std::vector<DomainParticipantImpl*> >::iterator;
VectorIt vector_it = participants_.find(did);
if (vector_it == participants_.end())
{
// Insert the vector
std::vector<DomainParticipantImpl*> new_vector;
auto pair_it = participants_.insert(std::make_pair(did, std::move(new_vector)));
vector_it = pair_it.first;
}
vector_it->second.push_back(dom_part_impl);
}
if (factory_qos_.entity_factory().autoenable_created_entities)
{
if (ReturnCode_t::RETCODE_OK != dom_part->enable())
{
delete_participant(dom_part);
return nullptr;
}
}
return dom_part;
}
DomainParticipant* DomainParticipantFactory::create_participant_with_profile(
DomainId_t did,
const std::string& profile_name,
DomainParticipantListener* listen,
const StatusMask& mask)
{
load_profiles();
// TODO (Miguel C): Change when we have full XML support for DDS QoS profiles
ParticipantAttributes attr;
if (XMLP_ret::XML_OK == XMLProfileManager::fillParticipantAttributes(profile_name, attr))
{
DomainParticipantQos qos = default_participant_qos_;
set_qos_from_attributes(qos, attr.rtps);
return create_participant(did, qos, listen, mask);
}
return nullptr;
}
DomainParticipant* DomainParticipantFactory::create_participant_with_profile(
const std::string& profile_name,
DomainParticipantListener* listen,
const StatusMask& mask)
{
load_profiles();
// TODO (Miguel C): Change when we have full XML support for DDS QoS profiles
ParticipantAttributes attr;
if (XMLP_ret::XML_OK == XMLProfileManager::fillParticipantAttributes(profile_name, attr))
{
DomainParticipantQos qos = default_participant_qos_;
set_qos_from_attributes(qos, attr.rtps);
return create_participant(attr.domainId, qos, listen, mask);
}
return nullptr;
}
DomainParticipant* DomainParticipantFactory::lookup_participant(
DomainId_t domain_id) const
{
std::lock_guard<std::mutex> guard(mtx_participants_);
auto it = participants_.find(domain_id);
if (it != participants_.end() && it->second.size() > 0)
{
return it->second.front()->get_participant();
}
return nullptr;
}
std::vector<DomainParticipant*> DomainParticipantFactory::lookup_participants(
DomainId_t domain_id) const
{
std::lock_guard<std::mutex> guard(mtx_participants_);
std::vector<DomainParticipant*> result;
auto it = participants_.find(domain_id);
if (it != participants_.end())
{
const std::vector<DomainParticipantImpl*>& v = it->second;
for (auto pit = v.begin(); pit != v.end(); ++pit)
{
result.push_back((*pit)->get_participant());
}
}
return result;
}
ReturnCode_t DomainParticipantFactory::get_default_participant_qos(
DomainParticipantQos& qos) const
{
qos = default_participant_qos_;
return ReturnCode_t::RETCODE_OK;
}
const DomainParticipantQos& DomainParticipantFactory::get_default_participant_qos() const
{
return default_participant_qos_;
}
ReturnCode_t DomainParticipantFactory::set_default_participant_qos(
const DomainParticipantQos& qos)
{
if (&qos == &PARTICIPANT_QOS_DEFAULT)
{
reset_default_participant_qos();
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t ret_val = DomainParticipantImpl::check_qos(qos);
if (!ret_val)
{
return ret_val;
}
DomainParticipantImpl::set_qos(default_participant_qos_, qos, true);
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::load_profiles()
{
if (false == default_xml_profiles_loaded)
{
XMLProfileManager::loadDefaultXMLFile();
// Only load profile once
default_xml_profiles_loaded = true;
// Only change default participant qos when not explicitly set by the user
if (default_participant_qos_ == PARTICIPANT_QOS_DEFAULT)
{
reset_default_participant_qos();
}
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::load_XML_profiles_file(
const std::string& xml_profile_file)
{
if (XMLP_ret::XML_ERROR == XMLProfileManager::loadXMLFile(xml_profile_file))
{
logError(DOMAIN, "Problem loading XML file '" << xml_profile_file << "'");
return ReturnCode_t::RETCODE_ERROR;
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::get_qos(
DomainParticipantFactoryQos& qos) const
{
qos = factory_qos_;
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::set_qos(
const DomainParticipantFactoryQos& qos)
{
ReturnCode_t ret_val = check_qos(qos);
if (!ret_val)
{
return ret_val;
}
if (!can_qos_be_updated(factory_qos_, qos))
{
return ReturnCode_t::RETCODE_IMMUTABLE_POLICY;
}
set_qos(factory_qos_, qos, false);
return ReturnCode_t::RETCODE_OK;
}
void DomainParticipantFactory::reset_default_participant_qos()
{
// TODO (Miguel C): Change when we have full XML support for DDS QoS profiles
DomainParticipantImpl::set_qos(default_participant_qos_, PARTICIPANT_QOS_DEFAULT, true);
if (true == default_xml_profiles_loaded)
{
eprosima::fastrtps::ParticipantAttributes attr;
XMLProfileManager::getDefaultParticipantAttributes(attr);
set_qos_from_attributes(default_participant_qos_, attr.rtps);
}
}
void DomainParticipantFactory::set_qos(
DomainParticipantFactoryQos& to,
const DomainParticipantFactoryQos& from,
bool first_time)
{
(void) first_time;
//As all the Qos can always be updated and none of them need to be sent
to = from;
}
ReturnCode_t DomainParticipantFactory::check_qos(
const DomainParticipantFactoryQos& qos)
{
(void) qos;
//There is no restriction by the moment with the contained Qos
return ReturnCode_t::RETCODE_OK;
}
bool DomainParticipantFactory::can_qos_be_updated(
const DomainParticipantFactoryQos& to,
const DomainParticipantFactoryQos& from)
{
(void) to;
(void) from;
//All the DomainParticipantFactoryQos can be updated
return true;
}
void DomainParticipantFactory::participant_has_been_deleted(
DomainParticipantImpl* part)
{
std::lock_guard<std::mutex> guard(mtx_participants_);
auto it = participants_.find(part->get_domain_id());
if (it != participants_.end())
{
for (auto pit = it->second.begin(); pit != it->second.end();)
{
if ((*pit) == part || (*pit)->guid() == part->guid())
{
pit = it->second.erase(pit);
}
else
{
++pit;
}
}
if (it->second.empty())
{
participants_.erase(it);
}
}
}
} /* namespace dds */
} /* namespace fastdds */
} /* namespace eprosima */
| 1 | 20,110 | Why do you need to include this using declaration? | eProsima-Fast-DDS | cpp |
@@ -59,7 +59,7 @@ namespace Microsoft.AspNet.Server.Kestrel.GeneratedCode
{
ulong mask = 0;
ulong comp = 0;
- for (var scan = 0; scan != count; ++scan)
+ for (var scan = 0; scan < count; scan++)
{
var ch = (byte)name[offset + count - scan - 1];
var isAlpha = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); | 1 | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Dnx.Compilation.CSharp;
namespace Microsoft.AspNet.Server.Kestrel.GeneratedCode
{
// This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class KnownHeaders : ICompileModule
{
static string Each<T>(IEnumerable<T> values, Func<T, string> formatter)
{
return values.Select(formatter).Aggregate((a, b) => a + b);
}
class KnownHeader
{
public string Name { get; set; }
public int Index { get; set; }
public string Identifier => Name.Replace("-", "");
public string TestBit() => $"((_bits & {1L << Index}L) != 0)";
public string SetBit() => $"_bits |= {1L << Index}L";
public string ClearBit() => $"_bits &= ~{1L << Index}L";
public string EqualIgnoreCaseBytes()
{
var result = "";
var delim = "";
var index = 0;
while (index != Name.Length)
{
if (Name.Length - index >= 8)
{
result += delim + Term(Name, index, 8, "pUL", "uL");
index += 8;
}
else if (Name.Length - index >= 4)
{
result += delim + Term(Name, index, 4, "pUI", "u");
index += 4;
}
else if (Name.Length - index >= 2)
{
result += delim + Term(Name, index, 2, "pUS", "u");
index += 2;
}
else
{
result += delim + Term(Name, index, 1, "pUB", "u");
index += 1;
}
delim = " && ";
}
return $"({result})";
}
protected string Term(string name, int offset, int count, string array, string suffix)
{
ulong mask = 0;
ulong comp = 0;
for (var scan = 0; scan != count; ++scan)
{
var ch = (byte)name[offset + count - scan - 1];
var isAlpha = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
comp = (comp << 8) + (ch & (isAlpha ? 0xdfu : 0xffu));
mask = (mask << 8) + (isAlpha ? 0xdfu : 0xffu);
}
return $"(({array}[{offset / count}] & {mask}{suffix}) == {comp}{suffix})";
}
}
public virtual void BeforeCompile(BeforeCompileContext context)
{
var syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(GeneratedFile());
context.Compilation = context.Compilation.AddSyntaxTrees(syntaxTree);
}
public static string GeneratedFile()
{
var commonHeaders = new[]
{
"Cache-Control",
"Connection",
"Date",
"Keep-Alive",
"Pragma",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Via",
"Warning",
"Allow",
"Content-Length",
"Content-Type",
"Content-Encoding",
"Content-Language",
"Content-Location",
"Content-MD5",
"Content-Range",
"Expires",
"Last-Modified"
};
var requestHeaders = commonHeaders.Concat(new[]
{
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Cookie",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Max-Forwards",
"Proxy-Authorization",
"Referer",
"Range",
"TE",
"Translate",
"User-Agent",
}).Select((header, index) => new KnownHeader
{
Name = header,
Index = index
});
var responseHeaders = commonHeaders.Concat(new[]
{
"Accept-Ranges",
"Age",
"ETag",
"Location",
"Proxy-Autheticate",
"Retry-After",
"Server",
"Set-Cookie",
"Vary",
"WWW-Authenticate",
}).Select((header, index) => new KnownHeader
{
Name = header,
Index = index
});
var loops = new[]
{
new
{
Headers = requestHeaders,
HeadersByLength = requestHeaders.GroupBy(x => x.Name.Length),
ClassName = "FrameRequestHeaders"
},
new
{
Headers = responseHeaders,
HeadersByLength = responseHeaders.GroupBy(x => x.Name.Length),
ClassName = "FrameResponseHeaders"
}
};
return $@"
using System;
using System.Collections.Generic;
using Microsoft.Framework.Primitives;
namespace Microsoft.AspNet.Server.Kestrel.Http
{{
{Each(loops, loop => $@"
public partial class {loop.ClassName}
{{
private long _bits = 0;
{Each(loop.Headers, header => @"
private StringValues _" + header.Identifier + ";")}
{Each(loop.Headers, header => $@"
public StringValues Header{header.Identifier}
{{
get
{{
return _{header.Identifier};
}}
set
{{
{header.SetBit()};
_{header.Identifier} = value;
}}
}}
")}
protected override int GetCountFast()
{{
var count = MaybeUnknown?.Count ?? 0;
{Each(loop.Headers, header => $@"
if ({header.TestBit()})
{{
++count;
}}
")}
return count;
}}
protected override StringValues GetValueFast(string key)
{{
switch(key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{
if ({header.TestBit()})
{{
return _{header.Identifier};
}}
else
{{
throw new System.Collections.Generic.KeyNotFoundException();
}}
}}
")}}}
break;
")}}}
if (MaybeUnknown == null)
{{
throw new System.Collections.Generic.KeyNotFoundException();
}}
return MaybeUnknown[key];
}}
protected override bool TryGetValueFast(string key, out StringValues value)
{{
switch(key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{
if ({header.TestBit()})
{{
value = _{header.Identifier};
return true;
}}
else
{{
value = StringValues.Empty;
return false;
}}
}}
")}}}
break;
")}}}
value = StringValues.Empty;
return MaybeUnknown?.TryGetValue(key, out value) ?? false;
}}
protected override void SetValueFast(string key, StringValues value)
{{
switch(key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{
{header.SetBit()};
_{header.Identifier} = value;
return;
}}
")}}}
break;
")}}}
Unknown[key] = value;
}}
protected override void AddValueFast(string key, StringValues value)
{{
switch(key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{
if ({header.TestBit()})
{{
throw new ArgumentException(""An item with the same key has already been added."");
}}
{header.SetBit()};
_{header.Identifier} = value;
return;
}}
")}}}
break;
")}}}
Unknown.Add(key, value);
}}
protected override bool RemoveFast(string key)
{{
switch(key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{
if ({header.TestBit()})
{{
{header.ClearBit()};
_{header.Identifier} = StringValues.Empty;
return true;
}}
else
{{
return false;
}}
}}
")}}}
break;
")}}}
return MaybeUnknown?.Remove(key) ?? false;
}}
protected override void ClearFast()
{{
_bits = 0;
{Each(loop.Headers, header => $@"
_{header.Identifier} = StringValues.Empty;")}
MaybeUnknown?.Clear();
}}
protected override void CopyToFast(KeyValuePair<string, StringValues>[] array, int arrayIndex)
{{
if (arrayIndex < 0)
{{
throw new ArgumentException();
}}
{Each(loop.Headers, header => $@"
if ({header.TestBit()})
{{
if (arrayIndex == array.Length)
{{
throw new ArgumentException();
}}
array[arrayIndex] = new KeyValuePair<string, StringValues>(""{header.Name}"", _{header.Identifier});
++arrayIndex;
}}
")}
((ICollection<KeyValuePair<string, StringValues>>)MaybeUnknown)?.CopyTo(array, arrayIndex);
}}
public unsafe void Append(byte[] keyBytes, int keyOffset, int keyLength, string value)
{{
fixed(byte* ptr = keyBytes) {{ var pUB = ptr + keyOffset; var pUL = (ulong*)pUB; var pUI = (uint*)pUB; var pUS = (ushort*)pUB;
switch(keyLength)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if ({header.EqualIgnoreCaseBytes()})
{{
if ({header.TestBit()})
{{
_{header.Identifier} = AppendValue(_{header.Identifier}, value);
}}
else
{{
{header.SetBit()};
_{header.Identifier} = new[] {{value}};
}}
return;
}}
")}}}
break;
")}}}}}
var key = System.Text.Encoding.ASCII.GetString(keyBytes, keyOffset, keyLength);
StringValues existing;
Unknown.TryGetValue(key, out existing);
Unknown[key] = AppendValue(existing, value);
}}
public partial struct Enumerator
{{
public bool MoveNext()
{{
switch (_state)
{{
{Each(loop.Headers, header => $@"
case {header.Index}:
goto state{header.Index};
")}
default:
goto state_default;
}}
{Each(loop.Headers, header => $@"
state{header.Index}:
if ({header.TestBit()})
{{
_current = new KeyValuePair<string, StringValues>(""{header.Name}"", _collection._{header.Identifier});
_state = {header.Index + 1};
return true;
}}
")}
state_default:
if (!_hasUnknown || !_unknownEnumerator.MoveNext())
{{
_current = default(KeyValuePair<string, StringValues>);
return false;
}}
_current = _unknownEnumerator.Current;
return true;
}}
}}
}}
")}}}
";
}
public virtual void AfterCompile(AfterCompileContext context)
{
}
}
}
| 1 | 6,018 | @halter73 where is this file generated from? | aspnet-KestrelHttpServer | .cs |
@@ -19,6 +19,7 @@ namespace Datadog.Trace.ClrProfiler.IntegrationTests
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:Elements must be separated by blank line", Justification = "This is an auto-generated file.")]
public class PackageVersions
{
+#if TRUE
public static IEnumerable<object[]> MongoDB =>
new List<object[]> | 1 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by the GeneratePackageVersions tool. To safely
// modify this file, edit PackageVersionsGeneratorDefinitions.json and
// re-run the GeneratePackageVersions project in Visual Studio. See the
// launchSettings.json for the project if you would like to run the tool
// with the correct arguments outside of Visual Studio.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Datadog.Trace.ClrProfiler.IntegrationTests
{
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:Elements must be separated by blank line", Justification = "This is an auto-generated file.")]
public class PackageVersions
{
public static IEnumerable<object[]> MongoDB =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "2.0.0" },
new object[] { "2.0.1" },
new object[] { "2.0.2" },
new object[] { "2.1.0" },
new object[] { "2.1.1" },
new object[] { "2.2.0" },
new object[] { "2.2.1" },
new object[] { "2.2.2" },
new object[] { "2.2.3" },
new object[] { "2.2.4" },
new object[] { "2.3.0" },
new object[] { "2.4.0" },
new object[] { "2.4.1" },
new object[] { "2.4.2" },
new object[] { "2.4.3" },
new object[] { "2.4.4" },
new object[] { "2.5.0" },
new object[] { "2.5.1" },
new object[] { "2.6.0" },
new object[] { "2.6.1" },
new object[] { "2.7.0" },
new object[] { "2.7.1" },
new object[] { "2.7.2" },
new object[] { "2.7.3" },
new object[] { "2.8.0" },
new object[] { "2.8.1" },
new object[] { "2.9.0" },
new object[] { "2.9.1" },
#endif
};
public static IEnumerable<object[]> ElasticSearch6 =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "6.0.0" },
new object[] { "6.0.1" },
new object[] { "6.0.2" },
new object[] { "6.1.0" },
new object[] { "6.2.0" },
new object[] { "6.3.0" },
new object[] { "6.3.1" },
new object[] { "6.4.0" },
new object[] { "6.4.1" },
new object[] { "6.4.2" },
new object[] { "6.5.0" },
new object[] { "6.5.1" },
new object[] { "6.6.0" },
new object[] { "6.7.0" },
new object[] { "6.8.0" },
new object[] { "6.8.1" },
new object[] { "6.8.2" },
#endif
};
public static IEnumerable<object[]> ElasticSearch5 =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "5.3.0" },
new object[] { "5.3.1" },
new object[] { "5.4.0" },
new object[] { "5.5.0" },
new object[] { "5.6.0" },
new object[] { "5.6.1" },
new object[] { "5.6.2" },
new object[] { "5.6.3" },
new object[] { "5.6.4" },
new object[] { "5.6.5" },
new object[] { "5.6.6" },
#endif
};
public static IEnumerable<object[]> Npgsql =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "4.0.0" },
new object[] { "4.0.1" },
new object[] { "4.0.2" },
new object[] { "4.0.3" },
new object[] { "4.0.4" },
new object[] { "4.0.5" },
new object[] { "4.0.6" },
new object[] { "4.0.7" },
new object[] { "4.0.8" },
new object[] { "4.0.9" },
#endif
};
public static IEnumerable<object[]> SqlServer =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "2.0.0" },
new object[] { "2.0.1" },
new object[] { "2.0.2" },
new object[] { "2.0.3" },
new object[] { "2.1.0" },
new object[] { "2.1.1" },
new object[] { "2.1.2" },
new object[] { "2.1.3" },
new object[] { "2.1.4" },
new object[] { "2.1.8" },
new object[] { "2.1.11" },
new object[] { "2.2.0" },
new object[] { "2.2.1" },
new object[] { "2.2.2" },
new object[] { "2.2.3" },
new object[] { "2.2.4" },
new object[] { "2.2.6" },
#endif
};
public static IEnumerable<object[]> StackExchangeRedis =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "1.0.187" },
new object[] { "1.0.190" },
new object[] { "1.0.206" },
new object[] { "1.0.207" },
new object[] { "1.0.208" },
new object[] { "1.0.209" },
new object[] { "1.0.210" },
new object[] { "1.0.214" },
new object[] { "1.0.219" },
new object[] { "1.0.221" },
new object[] { "1.0.223" },
new object[] { "1.0.228" },
new object[] { "1.0.231" },
new object[] { "1.0.233" },
new object[] { "1.0.236" },
new object[] { "1.0.238" },
new object[] { "1.0.240" },
new object[] { "1.0.241" },
new object[] { "1.0.242" },
new object[] { "1.0.243" },
new object[] { "1.0.245" },
new object[] { "1.0.247" },
new object[] { "1.0.266" },
new object[] { "1.0.270" },
new object[] { "1.0.273" },
new object[] { "1.0.278" },
new object[] { "1.0.281" },
new object[] { "1.0.289" },
new object[] { "1.0.297" },
new object[] { "1.0.309" },
new object[] { "1.0.312" },
new object[] { "1.0.320" },
new object[] { "1.0.321" },
new object[] { "1.0.322" },
new object[] { "1.0.328" },
new object[] { "1.0.329" },
new object[] { "1.0.330" },
new object[] { "1.0.331" },
new object[] { "1.0.333" },
new object[] { "1.0.371" },
new object[] { "1.0.394" },
new object[] { "1.0.414" },
new object[] { "1.0.450" },
new object[] { "1.0.479" },
new object[] { "1.0.481" },
new object[] { "1.0.488" },
new object[] { "1.1.553" },
new object[] { "1.1.572" },
new object[] { "1.1.603" },
new object[] { "1.1.605" },
new object[] { "1.1.606" },
new object[] { "1.1.607" },
new object[] { "1.1.608" },
new object[] { "1.2.0" },
new object[] { "1.2.1" },
new object[] { "1.2.2" },
new object[] { "1.2.3" },
new object[] { "1.2.4" },
new object[] { "1.2.5" },
new object[] { "1.2.6" },
#endif
};
public static IEnumerable<object[]> ServiceStackRedis =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "4.0.48" },
new object[] { "4.0.50" },
new object[] { "4.0.52" },
new object[] { "4.0.54" },
new object[] { "4.0.56" },
new object[] { "4.0.58" },
new object[] { "4.0.60" },
new object[] { "4.0.62" },
new object[] { "4.5.0" },
new object[] { "4.5.2" },
new object[] { "4.5.4" },
new object[] { "4.5.6" },
new object[] { "4.5.8" },
new object[] { "4.5.10" },
new object[] { "4.5.12" },
new object[] { "4.5.14" },
new object[] { "5.0.0" },
new object[] { "5.0.2" },
new object[] { "5.1.0" },
new object[] { "5.2.0" },
new object[] { "5.4.0" },
new object[] { "5.5.0" },
new object[] { "5.6.0" },
#endif
};
public static IEnumerable<object[]> AspNetCoreMvc2 =>
new List<object[]>
{
#if DEFAULT_SAMPLES
new object[] { string.Empty },
#else
new object[] { "2.0.0" },
new object[] { "2.0.1" },
new object[] { "2.0.2" },
new object[] { "2.0.3" },
new object[] { "2.0.4" },
new object[] { "2.1.0" },
new object[] { "2.1.1" },
new object[] { "2.1.2" },
new object[] { "2.1.3" },
new object[] { "2.2.0" },
#endif
};
}
}
| 1 | 15,818 | What do these `#if TRUE` accomplish? | DataDog-dd-trace-dotnet | .cs |
@@ -39,6 +39,11 @@ namespace OpenTelemetry.Instrumentation
public void OnNext(KeyValuePair<string, object> value)
{
+ if (Sdk.SuppressInstrumentation)
+ {
+ return;
+ }
+
if (!this.handler.SupportsNullActivity && Activity.Current == null)
{
InstrumentationEventSource.Log.NullActivity(value.Key); | 1 | // <copyright file="DiagnosticSourceListener.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>
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace OpenTelemetry.Instrumentation
{
internal class DiagnosticSourceListener : IObserver<KeyValuePair<string, object>>
{
private readonly ListenerHandler handler;
public DiagnosticSourceListener(ListenerHandler handler)
{
this.handler = handler ?? throw new ArgumentNullException(nameof(handler));
}
public void OnCompleted()
{
}
public void OnError(Exception error)
{
}
public void OnNext(KeyValuePair<string, object> value)
{
if (!this.handler.SupportsNullActivity && Activity.Current == null)
{
InstrumentationEventSource.Log.NullActivity(value.Key);
return;
}
try
{
if (value.Key.EndsWith("Start"))
{
this.handler.OnStartActivity(Activity.Current, value.Value);
}
else if (value.Key.EndsWith("Stop"))
{
this.handler.OnStopActivity(Activity.Current, value.Value);
}
else if (value.Key.EndsWith("Exception"))
{
this.handler.OnException(Activity.Current, value.Value);
}
else
{
this.handler.OnCustom(value.Key, Activity.Current, value.Value);
}
}
catch (Exception ex)
{
InstrumentationEventSource.Log.UnknownErrorProcessingEvent(this.handler?.SourceName, value.Key, ex);
}
}
}
}
| 1 | 16,228 | Probably a good optimization to have this, but I don't think it's strictly required. For "legacy" Activity flows we pass them through an ActivitySource for sampling. So the logic below should also catch these? | open-telemetry-opentelemetry-dotnet | .cs |
@@ -1,6 +1,6 @@
<%= @activity %>
-<%= t("mailer.proposal_link_text",
- proposal_url: proposal_url(@proposal)) %>
+<%= t("mailer.view_request_cta") %>
+<%= proposal_url(@proposal) %>
<%= t("mailer.footer", feedback_url: feedback_url) %> | 1 | <%= @activity %>
<%= t("mailer.proposal_link_text",
proposal_url: proposal_url(@proposal)) %>
<%= t("mailer.footer", feedback_url: feedback_url) %>
| 1 | 16,842 | @jessieay Intentionally moving away from passing a param? | 18F-C2 | rb |
@@ -1378,13 +1378,12 @@ class PAIA extends DAIA
$lastname = $nameArr[0];
} else {
$nameArr = explode(' ', $username);
- $firstname = $nameArr[0];
- $lastname = '';
- array_shift($nameArr);
+ $firstname = '';
+ $lastname = array_pop($nameArr);
foreach ($nameArr as $value) {
- $lastname .= ' ' . $value;
+ $firstname .= ' ' . $value;
}
- $lastname = trim($lastname);
+ $firstname = trim($firstname);
}
// TODO: implement parsing of user details according to types set | 1 | <?php
/**
* PAIA ILS Driver for VuFind to get patron information
*
* PHP version 7
*
* Copyright (C) Oliver Goldschmidt, Magda Roos, Till Kinstler, André Lahmann 2013,
* 2014, 2015.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package ILS_Drivers
* @author Oliver Goldschmidt <[email protected]>
* @author Magdalena Roos <[email protected]>
* @author Till Kinstler <[email protected]>
* @author André Lahmann <[email protected]>
* @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 VuFind\Exception\Auth as AuthException;
use VuFind\Exception\Forbidden as ForbiddenException;
use VuFind\Exception\ILS as ILSException;
/**
* PAIA ILS Driver for VuFind to get patron information
*
* Holding information is obtained by DAIA, so it's not necessary to implement those
* functions here; we just need to extend the DAIA driver.
*
* @category VuFind
* @package ILS_Drivers
* @author Oliver Goldschmidt <[email protected]>
* @author Magdalena Roos <[email protected]>
* @author Till Kinstler <[email protected]>
* @author André Lahmann <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
class PAIA extends DAIA
{
/**
* URL of PAIA service
*
* @var string
*/
protected $paiaURL;
/**
* Timeout in seconds to be used for PAIA http requests
*
* @var int
*/
protected $paiaTimeout = null;
/**
* Flag to switch on/off caching for PAIA items
*
* @var bool
*/
protected $paiaCacheEnabled = false;
/**
* Session containing PAIA login information
*
* @var \Laminas\Session\Container
*/
protected $session;
/**
* SessionManager
*
* @var \Laminas\Session\SessionManager
*/
protected $sessionManager;
/**
* PAIA status strings
*
* @var array
*/
protected static $statusStrings = [
'0' => 'no relation',
'1' => 'reserved',
'2' => 'ordered',
'3' => 'held',
'4' => 'provided',
'5' => 'rejected',
];
/**
* PAIA scopes as defined in
* http://gbv.github.io/paia/paia.html#access-tokens-and-scopes
*
* Notice: logged in users should ALWAYS have scope read_patron as the PAIA
* driver performs paiaGetUserDetails() upon each call of VuFind's patronLogin().
* That means if paiaGetUserDetails() fails (which is the case if the patron has
* NOT the scope read_patron) the patronLogin() will fail as well even though
* paiaLogin() might have succeeded. Any other scope not being available for the
* patron will be handled more or less gracefully through exception handling.
*/
public const SCOPE_READ_PATRON = 'read_patron';
public const SCOPE_UPDATE_PATRON = 'update_patron';
public const SCOPE_UPDATE_PATRON_NAME = 'update_patron_name';
public const SCOPE_UPDATE_PATRON_EMAIL = 'update_patron_email';
public const SCOPE_UPDATE_PATRON_ADDRESS = 'update_patron_address';
public const SCOPE_READ_FEES = 'read_fees';
public const SCOPE_READ_ITEMS = 'read_items';
public const SCOPE_WRITE_ITEMS = 'write_items';
public const SCOPE_CHANGE_PASSWORD = 'change_password';
public const SCOPE_READ_NOTIFICATIONS = 'read_notifications';
public const SCOPE_DELETE_NOTIFICATIONS = 'delete_notifications';
/**
* Constructor
*
* @param \VuFind\Date\Converter $converter Date converter
* @param \Laminas\Session\SessionManager $sessionManager Session Manager
*/
public function __construct(
\VuFind\Date\Converter $converter,
\Laminas\Session\SessionManager $sessionManager
) {
parent::__construct($converter);
$this->sessionManager = $sessionManager;
}
/**
* PAIA specific override of method to ensure uniform cache keys for cached
* VuFind objects.
*
* @param string|null $suffix Optional suffix that will get appended to the
* object class name calling getCacheKey()
*
* @return string
*/
protected function getCacheKey($suffix = null)
{
return $this->getBaseCacheKey(
md5($this->baseUrl . $this->paiaURL) . $suffix
);
}
/**
* Get the session container (constructing it on demand if not already present)
*
* @return SessionContainer
*/
protected function getSession()
{
// SessionContainer not defined yet? Build it now:
if (null === $this->session) {
$this->session = new \Laminas\Session\Container(
'PAIA',
$this->sessionManager
);
}
return $this->session;
}
/**
* Get the session scope
*
* @return array Array of the Session scope
*/
protected function getScope()
{
return $this->getSession()->scope;
}
/**
* Initialize the driver.
*
* Validate configuration and perform all resource-intensive tasks needed to
* make the driver active.
*
* @throws ILSException
* @return void
*/
public function init()
{
parent::init();
if (!(isset($this->config['PAIA']['baseUrl']))) {
throw new ILSException('PAIA/baseUrl configuration needs to be set.');
}
$this->paiaURL = $this->config['PAIA']['baseUrl'];
// use PAIA specific timeout setting for http requests if configured
if ((isset($this->config['PAIA']['timeout']))) {
$this->paiaTimeout = $this->config['PAIA']['timeout'];
}
// do we have caching enabled for PAIA
if (isset($this->config['PAIA']['paiaCache'])) {
$this->paiaCacheEnabled = $this->config['PAIA']['paiaCache'];
} else {
$this->debug('Caching not enabled, disabling it by default.');
}
}
// public functions implemented to satisfy Driver Interface
/*
These methods are not implemented in the PAIA driver as they are probably
not necessary in PAIA context:
- findReserves
- getCancelHoldLink
- getConsortialHoldings
- getCourses
- getDepartments
- getHoldDefaultRequiredDate
- getInstructors
- getOfflineMode
- getSuppressedAuthorityRecords
- getSuppressedRecords
- hasHoldings
- loginIsHidden
- renewMyItemsLink
- supportsMethod
*/
/**
* This method cancels a list of holds for a specific patron.
*
* @param array $cancelDetails An associative array with two keys:
* patron array returned by the driver's patronLogin method
* details an array of strings returned by the driver's
* getCancelHoldDetails method
*
* @return array Associative array containing:
* count The number of items successfully cancelled
* items Associative array where key matches one of the item_id
* values returned by getMyHolds and the value is an
* associative array with these keys:
* success Boolean true or false
* status A status message from the language file
* (required – VuFind-specific message,
* subject to translation)
* sysMessage A system supplied failure message
*/
public function cancelHolds($cancelDetails)
{
// check if user has appropriate scope (refer to scope declaration above for
// further details)
if (!$this->paiaCheckScope(self::SCOPE_WRITE_ITEMS)) {
throw new ForbiddenException(
'Exception::access_denied_write_items'
);
}
$it = $cancelDetails['details'];
$items = [];
foreach ($it as $item) {
$items[] = ['item' => stripslashes($item)];
}
$patron = $cancelDetails['patron'];
$post_data = ["doc" => $items];
try {
$array_response = $this->paiaPostAsArray(
'core/' . $patron['cat_username'] . '/cancel',
$post_data
);
} catch (\Exception $e) {
$this->debug($e->getMessage());
return [
'success' => false,
'status' => $e->getMessage(),
];
}
$details = [];
if (isset($array_response['error'])) {
$details[] = [
'success' => false,
'status' => $array_response['error_description'],
'sysMessage' => $array_response['error']
];
} else {
$count = 0;
$elements = $array_response['doc'];
foreach ($elements as $element) {
$item_id = $element['item'];
if ($element['error'] ?? false) {
$details[$item_id] = [
'success' => false,
'status' => $element['error'],
'sysMessage' => 'Cancel request rejected'
];
} else {
$details[$item_id] = [
'success' => true,
'status' => 'Success',
'sysMessage' => 'Successfully cancelled'
];
$count++;
// DAIA cache cannot be cleared for particular item as PAIA only
// operates with specific item URIs and the DAIA cache is setup
// by doc URIs (containing items with URIs)
}
}
// If caching is enabled for PAIA clear the cache as at least for one
// item cancel was successful and therefore the status changed.
// Otherwise the changed status will not be shown before the cache
// expires.
if ($this->paiaCacheEnabled) {
$this->removeCachedData($patron['cat_username']);
}
}
$returnArray = ['count' => $count, 'items' => $details];
return $returnArray;
}
/**
* Public Function which changes the password in the library system
* (not supported prior to VuFind 2.4)
*
* @param array $details Array with patron information, newPassword and
* oldPassword.
*
* @return array An array with patron information.
*/
public function changePassword($details)
{
// check if user has appropriate scope (refer to scope declaration above for
// further details)
if (!$this->paiaCheckScope(self::SCOPE_CHANGE_PASSWORD)) {
throw new ForbiddenException(
'Exception::access_denied_change_password'
);
}
$post_data = [
"patron" => $details['patron']['cat_username'],
"username" => $details['patron']['cat_username'],
"old_password" => $details['oldPassword'],
"new_password" => $details['newPassword']
];
try {
$array_response = $this->paiaPostAsArray(
'auth/change',
$post_data
);
} catch (AuthException $e) {
return [
'success' => false,
'status' => 'password_error_auth_old'
];
} catch (\Exception $e) {
$this->debug($e->getMessage());
return [
'success' => false,
'status' => $e->getMessage(),
];
}
$details = [];
if (isset($array_response['error'])) {
// on error
$details = [
'success' => false,
'status' => $array_response['error'],
'sysMessage' =>
$array_response['error'] ?? ' ' .
$array_response['error_description'] ?? ' '
];
} elseif (isset($array_response['patron'])
&& $array_response['patron'] === $post_data['patron']
) {
// on success patron_id is returned
$details = [
'success' => true,
'status' => 'Successfully changed'
];
} else {
$details = [
'success' => false,
'status' => 'Failure changing password',
'sysMessage' => serialize($array_response)
];
}
return $details;
}
/**
* This method returns a string to use as the input form value for
* cancelling each hold item. (optional, but required if you
* implement cancelHolds). Not supported prior to VuFind 1.2
*
* @param array $hold A single hold array from getMyHolds
* @param array $patron Patron information from patronLogin
*
* @return string A string to use as the input form value for cancelling
* each hold item; you can pass any data that is needed
* by your ILS to identify the hold – the output of this
* method will be used as part of the input to the
* cancelHolds method.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getCancelHoldDetails($hold, $patron = [])
{
return $hold['cancel_details'];
}
/**
* Get Default Pick Up Location
*
* @param array $patron Patron information returned by the patronLogin
* method.
* @param array $holdDetails Optional array, only passed in when getting a list
* in the context of placing a hold; contains most of the same values passed to
* placeHold, minus the patron data. May be used to limit the pickup options
* or may be ignored.
*
* @return string The default pickup location for the patron.
*/
public function getDefaultPickUpLocation($patron = null, $holdDetails = null)
{
return false;
}
/**
* Get Funds
*
* Return a list of funds which may be used to limit the getNewItems list.
*
* @return array An associative array with key = fund ID, value = fund name.
*/
public function getFunds()
{
// 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.
return [];
}
/**
* Cancel Storage Retrieval Request
*
* Attempts to Cancel a Storage Retrieval Request on a particular item. The
* data in $cancelDetails['details'] is determined by
* getCancelStorageRetrievalRequestDetails().
*
* @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 cancelStorageRetrievalRequests($cancelDetails)
{
// Not yet implemented
return [];
}
/**
* Get Cancel Storage Retrieval Request Details
*
* In order to cancel a hold, Voyager requires the patron details an item ID
* and a recall ID. This function returns the item id and recall id as a string
* separated by a pipe, which is then submitted as form data in Hold.php. This
* value is then extracted by the CancelHolds function.
*
* @param array $details An array of item data
* @param array $patron Patron information from patronLogin
*
* @return string Data for use in a form field
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getCancelStorageRetrievalRequestDetails($details, $patron)
{
// Not yet implemented
return '';
}
/**
* Get Patron ILL Requests
*
* This is responsible for retrieving all ILL requests by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return mixed Array of the patron's ILL requests
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getMyILLRequests($patron)
{
// Not yet implemented
return [];
}
/**
* Check if ILL request available
*
* This is responsible for determining if an item is requestable
*
* @param string $id The Bib ID
* @param array $data An Array of item data
* @param patron $patron An array of patron data
*
* @return bool True if request is valid, false if not
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function checkILLRequestIsValid($id, $data, $patron)
{
// Not yet implemented
return false;
}
/**
* Place ILL Request
*
* Attempts to place an ILL request on a particular item and returns
* an array with result details
*
* @param array $details 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 placeILLRequest($details)
{
// Not yet implemented
return [];
}
/**
* Get ILL Pickup Libraries
*
* This is responsible for getting information on the possible pickup libraries
*
* @param string $id Record ID
* @param array $patron Patron
*
* @return bool|array False if request not allowed, or an array of associative
* arrays with libraries.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getILLPickupLibraries($id, $patron)
{
// Not yet implemented
return false;
}
/**
* Get ILL Pickup Locations
*
* This is responsible for getting a list of possible pickup locations for a
* library
*
* @param string $id Record ID
* @param string $pickupLib Pickup library ID
* @param array $patron Patron
*
* @return bool|array False if request not allowed, or an array of locations.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getILLPickupLocations($id, $pickupLib, $patron)
{
// Not yet implemented
return false;
}
/**
* Cancel ILL Request
*
* Attempts to Cancel an ILL request on a particular item. The
* data in $cancelDetails['details'] is determined by
* getCancelILLRequestDetails().
*
* @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 cancelILLRequests($cancelDetails)
{
// Not yet implemented
return [];
}
/**
* Get Cancel ILL Request Details
*
* @param array $details An array of item data
* @param array $patron Patron information from patronLogin
*
* @return string Data for use in a form field
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getCancelILLRequestDetails($details, $patron)
{
// Not yet implemented
return '';
}
/**
* Get Patron Fines
*
* This is responsible for retrieving all fines by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return mixed Array of the patron's fines on success
*/
public function getMyFines($patron)
{
// check if user has appropriate scope (refer to scope declaration above for
// further details)
if (!$this->paiaCheckScope(self::SCOPE_READ_FEES)) {
throw new ForbiddenException('Exception::access_denied_read_fines');
}
$fees = $this->paiaGetAsArray(
'core/' . $patron['cat_username'] . '/fees'
);
// PAIA simple data type money: a monetary value with currency (format
// [0-9]+\.[0-9][0-9] [A-Z][A-Z][A-Z]), for instance 0.80 USD.
$feeConverter = function ($fee) {
$paiaCurrencyPattern = "/^([0-9]+\.[0-9][0-9]) ([A-Z][A-Z][A-Z])$/";
if (preg_match($paiaCurrencyPattern, $fee, $feeMatches)) {
// VuFind expects fees in PENNIES
return $feeMatches[1] * 100;
}
return $fee;
};
$results = [];
if (isset($fees['fee'])) {
foreach ($fees['fee'] as $fee) {
$result = [
// fee.amount 1..1 money amount of a single fee
'amount' => $feeConverter($fee['amount']),
'checkout' => '',
// fee.feetype 0..1 string textual description of the type
// of service that caused the fee
'fine' => ($fee['feetype'] ?? null),
'balance' => $feeConverter($fee['amount']),
// fee.date 0..1 date date when the fee was claimed
'createdate' => (isset($fee['date'])
? $this->convertDate($fee['date']) : null),
'duedate' => '',
// fee.edition 0..1 URI edition that caused the fee
'id' => (isset($fee['edition'])
? $this->getAlternativeItemId($fee['edition']) : ''),
];
// custom PAIA fields can get added in getAdditionalFeeData
$results[] = $result + $this->getAdditionalFeeData($fee, $patron);
}
}
return $results;
}
/**
* Gets additional array fields for the item.
* Override this method in your custom PAIA driver if necessary.
*
* @param array $fee The fee array from PAIA
* @param array $patron The patron array from patronLogin
*
* @return array Additional fee data for the item
*/
protected function getAdditionalFeeData($fee, $patron = null)
{
$additionalData = [];
// The title is always displayed to the user in fines view if no record can
// be found for current fee. So always populate the title with content of
// about field.
if (isset($fee['about'])) {
$additionalData['title'] = $fee['about'];
}
// custom PAIA fields
// fee.about 0..1 string textual information about the fee
// fee.item 0..1 URI item that caused the fee
// fee.feeid 0..1 URI URI of the type of service that
// caused the fee
$additionalData['feeid'] = ($fee['feeid'] ?? null);
$additionalData['about'] = ($fee['about'] ?? null);
$additionalData['item'] = ($fee['item'] ?? null);
return $additionalData;
}
/**
* Get Patron Holds
*
* This is responsible for retrieving all holds by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return mixed Array of the patron's holds on success.
*/
public function getMyHolds($patron)
{
// filters for getMyHolds are by default configuration:
// status = 1 - reserved (the document is not accessible for the patron yet,
// but it will be)
// 4 - provided (the document is ready to be used by the patron)
$status = $this->config['Holds']['status'] ?? '1:4';
$filter = ['status' => explode(':', $status)];
// get items-docs for given filters
$items = $this->paiaGetItems($patron, $filter);
return $this->mapPaiaItems($items, 'myHoldsMapping');
}
/**
* Get Patron Profile
*
* This is responsible for retrieving the profile for a specific patron.
*
* @param array $patron The patron array
*
* @return array Array of the patron's profile data on success,
*/
public function getMyProfile($patron)
{
if (is_array($patron)) {
$type = isset($patron['type'])
? implode(
', ',
array_map(
[$this, 'getReadableGroupType'],
(array)$patron['type']
)
)
: null;
return [
'firstname' => $patron['firstname'],
'lastname' => $patron['lastname'],
'address1' => $patron['address'],
'address2' => null,
'city' => null,
'country' => null,
'zip' => null,
'phone' => null,
'mobile_phone' => null,
'group' => $type,
// PAIA specific custom values
'expires' => isset($patron['expires'])
? $this->convertDate($patron['expires']) : null,
'statuscode' => $patron['status'] ?? null,
'canWrite' => in_array(self::SCOPE_WRITE_ITEMS, $this->getScope()),
];
}
return [];
}
/**
* Get Readable Group Type
*
* Due to PAIA specifications type returns an URI. This method offers a
* possibility to translate the URI in a readable value by inheritance
* and implementing a personal proceeding.
*
* @param string $type URI of usertype
*
* @return string URI of usertype
*/
protected function getReadableGroupType($type)
{
return $type;
}
/**
* Get Patron Transactions
*
* This is responsible for retrieving all transactions (i.e. checked out items)
* by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return array Array of the patron's transactions on success,
*/
public function getMyTransactions($patron)
{
// filters for getMyTransactions are by default configuration:
// status = 3 - held (the document is on loan by the patron)
$status = $this->config['Transactions']['status'] ?? '3';
$filter = ['status' => explode(':', $status)];
// get items-docs for given filters
$items = $this->paiaGetItems($patron, $filter);
return $this->mapPaiaItems($items, 'myTransactionsMapping');
}
/**
* Get Patron StorageRetrievalRequests
*
* This is responsible for retrieving all storage retrieval requests
* by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return array Array of the patron's storage retrieval requests on success,
*/
public function getMyStorageRetrievalRequests($patron)
{
// filters for getMyStorageRetrievalRequests are by default configuration:
// status = 2 - ordered (the document is ordered by the patron)
$status = $this->config['StorageRetrievalRequests']['status'] ?? '2';
$filter = ['status' => explode(':', $status)];
// get items-docs for given filters
$items = $this->paiaGetItems($patron, $filter);
return $this->mapPaiaItems($items, 'myStorageRetrievalRequestsMapping');
}
/**
* This method queries the ILS for new items
*
* @param string $page page number of results to retrieve (counting starts @1)
* @param string $limit the size of each page of results to retrieve
* @param string $daysOld the maximum age of records to retrieve in days (max 30)
* @param string $fundID optional fund ID to use for limiting results
*
* @return array 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).
*/
public function getNewItems($page, $limit, $daysOld, $fundID)
{
return [];
}
/**
* Get Pick Up Locations
*
* This is responsible for gettting a list of valid library locations for
* holds / recall retrieval
*
* @param array $patron Patron information returned by the patronLogin
* method.
* @param array $holdDetails Optional array, only passed in when getting a list
* in the context of placing or editing a hold. When placing a hold, it contains
* most of the same values passed to placeHold, minus the patron data. When
* editing a hold it contains all the hold information returned by getMyHolds.
* May be used to limit the pickup options or may be ignored. The driver must
* not add new options to the return array based on this data or other areas of
* VuFind may behave incorrectly.
*
* @return array An array of associative arrays with locationID and
* locationDisplay keys
*/
public function getPickUpLocations($patron = null, $holdDetails = null)
{
// How to get valid PickupLocations for a PICA LBS?
return [];
}
/**
* This method returns a string to use as the input form value for renewing
* each hold item. (optional, but required if you implement the
* renewMyItems method) Not supported prior to VuFind 1.2
*
* @param array $checkOutDetails One of the individual item arrays returned by
* the getMyTransactions method
*
* @return string A string to use as the input form value for renewing
* each item; you can pass any data that is needed by your
* ILS to identify the transaction to renew – the output
* of this method will be used as part of the input to the
* renewMyItems method.
*/
public function getRenewDetails($checkOutDetails)
{
return $checkOutDetails['renew_details'];
}
/**
* Get the callnumber of this item
*
* @param array $doc Array of PAIA item.
*
* @return String
*/
protected function getCallNumber($doc)
{
return $doc['label'] ?? null;
}
/**
* Patron Login
*
* This is responsible for authenticating a patron against the catalog.
*
* @param string $username The patron's username
* @param string $password The patron's login password
*
* @return mixed Associative array of patron info on successful login,
* null on unsuccessful login.
*
* @throws ILSException
*/
public function patronLogin($username, $password)
{
if ($username == '' || $password == '') {
throw new ILSException('Invalid Login, Please try again.');
}
$session = $this->getSession();
// if we already have a session with access_token and patron id, try to get
// patron info with session data
if (isset($session->expires) && $session->expires > time()) {
return $this->enrichUserDetails(
$this->paiaGetUserDetails($session->patron),
$password
);
}
try {
if ($this->paiaLogin($username, $password)) {
return $this->enrichUserDetails(
$this->paiaGetUserDetails($session->patron),
$password
);
}
} catch (AuthException $e) {
// swallow auth exceptions and return null compliant to spec at:
// https://vufind.org/wiki/development:plugins:ils_drivers#patronlogin
return null;
}
}
/**
* Handle PAIA request errors and throw appropriate exception.
*
* @param array $array Array containing error messages
*
* @return void
*
* @throws AuthException
* @throws ILSException
*/
protected function paiaHandleErrors($array)
{
// TODO: also have exception contain content of 'error' as for at least
// error code 403 two differing errors are possible
// (cf. http://gbv.github.io/paia/paia.html#request-errors)
if (isset($array['error'])) {
switch ($array['error']) {
// cf. http://gbv.github.io/paia/paia.html#request-errors
// error code error_description
// access_denied 403 Wrong or missing credentials to get an
// access token
case 'access_denied':
throw new AuthException(
$array['error_description'] ?? $array['error'],
(int)($array['code'] ?? 0)
);
// invalid_grant 401 The access token was missing, invalid
// or expired
case 'invalid_grant':
// insufficient_scope 403 The access token was accepted but
// it lacks permission for the request
case 'insufficient_scope':
throw new ForbiddenException(
$array['error_description'] ?? $array['error'],
(int)($array['code'] ?? 0)
);
// not_found 404 Unknown request URL or unknown patron.
// Implementations SHOULD first check
// authentication and prefer error invalid_grant
// or access_denied to prevent leaking patron
// identifiers.
case 'not_found':
// not_implemented 501 Known but unsupported request URL (for
// instance a PAIA auth server server may
// not implement
// http://example.org/core/change)
case 'not_implemented':
// invalid_request 405 Unexpected HTTP verb
// invalid_request 400 Malformed request (for instance error
// parsing JSON, unsupported request content
// type, etc.)
// invalid_request 422 The request parameters could be parsed
// but they don’t match the request method
// (for instance missing fields, invalid
// values, etc.)
case 'invalid_request':
// internal_error 500 An unexpected error occurred. This
// error corresponds to a bug in the
// implementation of a PAIA auth/core server
case 'internal_error':
// service_unavailable 503 The request couldn’t be serviced
// because of a temporary failure
case 'service_unavailable':
// bad_gateway 502 The request couldn’t be serviced because
// of a backend failure (for instance the library
// system’s database)
case 'bad_gateway':
// gateway_timeout 504 The request couldn’t be serviced
// because of a backend failure
case 'gateway_timeout':
default:
throw new ILSException(
$array['error_description'] ?? $array['error'],
(int)($array['code'] ?? 0)
);
}
}
}
/**
* PAIA helper function to map session data to return value of patronLogin()
*
* @param array $details Patron details returned by patronLogin
* @param string $password Patron cataloge password
*
* @return mixed
*/
protected function enrichUserDetails($details, $password)
{
$session = $this->getSession();
$details['cat_username'] = $session->patron;
$details['cat_password'] = $password;
return $details;
}
/**
* Returns an array with PAIA confirmations based on the given holdDetails which
* will be used for a request.
* Currently two condition types are supported:
* - http://purl.org/ontology/paia#StorageCondition to select a document
* location -- mapped to pickUpLocation
* - http://purl.org/ontology/paia#FeeCondition to confirm or select a document
* service causing a fee -- not mapped yet
*
* @param array $holdDetails An array of item and patron data
*
* @return array
*/
protected function getConfirmations($holdDetails)
{
$confirmations = [];
if (isset($holdDetails['pickUpLocation'])) {
$confirmations['http://purl.org/ontology/paia#StorageCondition']
= [$holdDetails['pickUpLocation']];
}
return $confirmations;
}
/**
* Place Hold
*
* Attempts to place a hold or recall on a particular item and returns
* an array with result details
*
* Make a request on a specific record
*
* @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)
{
// check if user has appropriate scope (refer to scope declaration above for
// further details)
if (!$this->paiaCheckScope(self::SCOPE_WRITE_ITEMS)) {
throw new ForbiddenException(
'Exception::access_denied_write_items'
);
}
$item = $holdDetails['item_id'];
$patron = $holdDetails['patron'];
$doc = [];
$doc['item'] = stripslashes($item);
if ($confirm = $this->getConfirmations($holdDetails)) {
$doc["confirm"] = $confirm;
}
$post_data = [];
$post_data['doc'][] = $doc;
try {
$array_response = $this->paiaPostAsArray(
'core/' . $patron['cat_username'] . '/request',
$post_data
);
} catch (\Exception $e) {
$this->debug($e->getMessage());
return [
'success' => false,
'sysMessage' => $e->getMessage(),
];
}
$details = [];
if (isset($array_response['error'])) {
$details = [
'success' => false,
'sysMessage' => $array_response['error_description']
];
} else {
$elements = $array_response['doc'];
foreach ($elements as $element) {
if (isset($element['error'])) {
$details = [
'success' => false,
'sysMessage' => $element['error']
];
} else {
$details = [
'success' => true,
'sysMessage' => 'Successfully requested'
];
// if caching is enabled for DAIA remove the cached data for the
// current item otherwise the changed status will not be shown
// before the cache expires
if ($this->daiaCacheEnabled) {
$this->removeCachedData($holdDetails['doc_id']);
}
}
}
}
return $details;
}
/**
* Place a Storage Retrieval Request
*
* Attempts to place a request on a particular item and returns
* an array with result details.
*
* @param array $details 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 placeStorageRetrievalRequest($details)
{
// Making a storage retrieval request is the same in PAIA as placing a Hold
return $this->placeHold($details);
}
/**
* This method renews a list of items for a specific patron.
*
* @param array $details - An associative array with two keys:
* patron - array returned by patronLogin method
* details - array of values returned by the getRenewDetails method
* identifying which items to renew
*
* @return array - An associative array with two keys:
* blocks - An array of strings specifying why a user is blocked from
* renewing (false if no blocks)
* details - Not set when blocks exist; otherwise, an array of
* associative arrays (keyed by item ID) with each subarray
* containing these keys:
* success – Boolean true or false
* new_date – string – A new due date
* new_time – string – A new due time
* item_id – The item id of the renewed item
* sysMessage – A system supplied renewal message (optional)
*/
public function renewMyItems($details)
{
// check if user has appropriate scope (refer to scope declaration above for
// further details)
if (!$this->paiaCheckScope(self::SCOPE_WRITE_ITEMS)) {
throw new ForbiddenException(
'Exception::access_denied_write_items'
);
}
$it = $details['details'];
$items = [];
foreach ($it as $item) {
$items[] = ['item' => stripslashes($item)];
}
$patron = $details['patron'];
$post_data = ["doc" => $items];
try {
$array_response = $this->paiaPostAsArray(
'core/' . $patron['cat_username'] . '/renew',
$post_data
);
} catch (\Exception $e) {
$this->debug($e->getMessage());
return [
'success' => false,
'sysMessage' => $e->getMessage(),
];
}
$details = [];
if (isset($array_response['error'])) {
$details[] = [
'success' => false,
'sysMessage' => $array_response['error_description']
];
} else {
$elements = $array_response['doc'];
foreach ($elements as $element) {
// VuFind can only assign the response to an id - if none is given
// (which is possible) simply skip this response element
if (isset($element['item'])) {
if (isset($element['error'])) {
$details[$element['item']] = [
'success' => false,
'sysMessage' => $element['error']
];
} elseif ($element['status'] == '3') {
$details[$element['item']] = [
'success' => true,
'new_date' => isset($element['endtime'])
? $this->convertDatetime($element['endtime']) : '',
'item_id' => 0,
'sysMessage' => 'Successfully renewed'
];
} else {
$details[$element['item']] = [
'success' => false,
'item_id' => 0,
'new_date' => isset($element['endtime'])
? $this->convertDatetime($element['endtime']) : '',
'sysMessage' => 'Request rejected'
];
}
}
// DAIA cache cannot be cleared for particular item as PAIA only
// operates with specific item URIs and the DAIA cache is setup
// by doc URIs (containing items with URIs)
}
// If caching is enabled for PAIA clear the cache as at least for one
// item renew was successful and therefore the status changed. Otherwise
// the changed status will not be shown before the cache expires.
if ($this->paiaCacheEnabled) {
$this->removeCachedData($patron['cat_username']);
}
}
$returnArray = ['blocks' => false, 'details' => $details];
return $returnArray;
}
/*
* PAIA functions
*/
/**
* PAIA support method to return strings for PAIA service status values
*
* @param string $status PAIA service status
*
* @return string Describing PAIA service status
*/
protected function paiaStatusString($status)
{
return self::$statusStrings[$status] ?? '';
}
/**
* PAIA support method for PAIA core method 'items' returning only those
* documents containing the given service status.
*
* @param array $patron Array with patron information
* @param array $filter Array of properties identifying the wanted items
*
* @return array|mixed Array of documents containing the given filter properties
*/
protected function paiaGetItems($patron, $filter = [])
{
// check if user has appropriate scope (refer to scope declaration above for
// further details)
if (!$this->paiaCheckScope(self::SCOPE_READ_ITEMS)) {
throw new ForbiddenException('Exception::access_denied_read_items');
}
// check for existing data in cache
$itemsResponse = $this->paiaCacheEnabled
? $this->getCachedData($patron['cat_username']) : null;
if (!isset($itemsResponse) || $itemsResponse == null) {
$itemsResponse = $this->paiaGetAsArray(
'core/' . $patron['cat_username'] . '/items'
);
if ($this->paiaCacheEnabled) {
$this->putCachedData($patron['cat_username'], $itemsResponse);
}
}
if (isset($itemsResponse['doc'])) {
if (count($filter)) {
$filteredItems = [];
foreach ($itemsResponse['doc'] as $doc) {
$filterCounter = 0;
foreach ($filter as $filterKey => $filterValue) {
if (isset($doc[$filterKey])
&& in_array($doc[$filterKey], (array)$filterValue)
) {
$filterCounter++;
}
}
if ($filterCounter == count($filter)) {
$filteredItems[] = $doc;
}
}
return $filteredItems;
} else {
return $itemsResponse;
}
} else {
$this->debug(
"No documents found in PAIA response. Returning empty array."
);
}
return [];
}
/**
* PAIA support method to retrieve needed ItemId in case PAIA-response does not
* contain it
*
* @param string $id itemId
*
* @return string $id
*/
protected function getAlternativeItemId($id)
{
return $id;
}
/**
* PAIA support function to implement ILS specific parsing of user_details
*
* @param string $patron User id
* @param array $user_response Array with PAIA response data
*
* @return array
*/
protected function paiaParseUserDetails($patron, $user_response)
{
$username = trim($user_response['name']);
if (count(explode(',', $username)) == 2) {
$nameArr = explode(',', $username);
$firstname = $nameArr[1];
$lastname = $nameArr[0];
} else {
$nameArr = explode(' ', $username);
$firstname = $nameArr[0];
$lastname = '';
array_shift($nameArr);
foreach ($nameArr as $value) {
$lastname .= ' ' . $value;
}
$lastname = trim($lastname);
}
// TODO: implement parsing of user details according to types set
// (cf. https://github.com/gbv/paia/issues/29)
$user = [];
$user['id'] = $patron;
$user['firstname'] = $firstname;
$user['lastname'] = $lastname;
$user['email'] = ($user_response['email'] ?? '');
$user['major'] = null;
$user['college'] = null;
// add other information from PAIA - we don't want anything to get lost
// while parsing
foreach ($user_response as $key => $value) {
if (!isset($user[$key])) {
$user[$key] = $value;
}
}
return $user;
}
/**
* PAIA helper function to allow customization of mapping from PAIA response to
* VuFind ILS-method return values.
*
* @param array $items Array of PAIA items to be mapped
* @param string $mapping String identifying a custom mapping-method
*
* @return array
*/
protected function mapPaiaItems($items, $mapping)
{
if (is_callable([$this, $mapping])) {
return $this->$mapping($items);
}
$this->debug('Could not call method: ' . $mapping . '() .');
return [];
}
/**
* Map a PAIA document to an array for use in generating a VuFind request
* (holds, storage retrieval, etc).
*
* @param array $doc Array of PAIA document to be mapped.
*
* @return array
*/
protected function getBasicDetails($doc)
{
$result = [];
// item (0..1) URI of a particular copy
$result['item_id'] = ($doc['item'] ?? '');
$result['cancel_details']
= (isset($doc['cancancel']) && $doc['cancancel']
&& $this->paiaCheckScope(self::SCOPE_WRITE_ITEMS))
? $result['item_id'] : '';
// edition (0..1) URI of a the document (no particular copy)
// hook for retrieving alternative ItemId in case PAIA does not
// the needed id
$result['id'] = (isset($doc['edition'])
? $this->getAlternativeItemId($doc['edition']) : '');
$result['type'] = $this->paiaStatusString($doc['status']);
// storage (0..1) textual description of location of the document
$result['location'] = ($doc['storage'] ?? null);
// queue (0..1) number of waiting requests for the document or item
$result['position'] = ($doc['queue'] ?? null);
// only true if status == 4
$result['available'] = false;
// about (0..1) textual description of the document
$result['title'] = ($doc['about'] ?? null);
// PAIA custom field
// label (0..1) call number, shelf mark or similar item label
$result['callnumber'] = $this->getCallNumber($doc);
/*
* meaning of starttime and endtime depends on status:
*
* status | starttime
* | endtime
* -------+--------------------------------
* 0 | -
* | -
* 1 | when the document was reserved
* | when the reserved document is expected to be available
* 2 | when the document was ordered
* | when the ordered document is expected to be available
* 3 | when the document was lend
* | when the loan period ends or ended (due)
* 4 | when the document is provided
* | when the provision will expire
* 5 | when the request was rejected
* | -
*/
$result['create'] = (isset($doc['starttime'])
? $this->convertDatetime($doc['starttime']) : '');
// Optional VuFind fields
/*
$result['reqnum'] = null;
$result['volume'] = null;
$result['publication_year'] = null;
$result['isbn'] = null;
$result['issn'] = null;
$result['oclc'] = null;
$result['upc'] = null;
*/
return $result;
}
/**
* This PAIA helper function allows custom overrides for mapping of PAIA response
* to getMyHolds data structure.
*
* @param array $items Array of PAIA items to be mapped.
*
* @return array
*/
protected function myHoldsMapping($items)
{
$results = [];
foreach ($items as $doc) {
$result = $this->getBasicDetails($doc);
if ($doc['status'] == '4') {
$result['expire'] = (isset($doc['endtime'])
? $this->convertDatetime($doc['endtime']) : '');
} else {
$result['duedate'] = (isset($doc['endtime'])
? $this->convertDatetime($doc['endtime']) : '');
}
// status: provided (the document is ready to be used by the patron)
$result['available'] = $doc['status'] == 4 ? true : false;
$results[] = $result;
}
return $results;
}
/**
* This PAIA helper function allows custom overrides for mapping of PAIA response
* to getMyStorageRetrievalRequests data structure.
*
* @param array $items Array of PAIA items to be mapped.
*
* @return array
*/
protected function myStorageRetrievalRequestsMapping($items)
{
$results = [];
foreach ($items as $doc) {
$result = $this->getBasicDetails($doc);
$results[] = $result;
}
return $results;
}
/**
* This PAIA helper function allows custom overrides for mapping of PAIA response
* to getMyTransactions data structure.
*
* @param array $items Array of PAIA items to be mapped.
*
* @return array
*/
protected function myTransactionsMapping($items)
{
$results = [];
foreach ($items as $doc) {
$result = $this->getBasicDetails($doc);
// canrenew (0..1) whether a document can be renewed (bool)
$result['renewable'] = (isset($doc['canrenew'])
&& $this->paiaCheckScope(self::SCOPE_WRITE_ITEMS))
? $doc['canrenew'] : false;
$result['renew_details']
= (isset($doc['canrenew']) && $doc['canrenew']
&& $this->paiaCheckScope(self::SCOPE_WRITE_ITEMS))
? $result['item_id'] : '';
// queue (0..1) number of waiting requests for the document or item
$result['request'] = ($doc['queue'] ?? null);
// renewals (0..1) number of times the document has been renewed
$result['renew'] = ($doc['renewals'] ?? null);
// reminder (0..1) number of times the patron has been reminded
$result['reminder'] = (
$doc['reminder'] ?? null
);
// custom PAIA field
// starttime (0..1) date and time when the status began
$result['startTime'] = (isset($doc['starttime'])
? $this->convertDatetime($doc['starttime']) : '');
// endtime (0..1) date and time when the status will expire
$result['dueTime'] = (isset($doc['endtime'])
? $this->convertDatetime($doc['endtime']) : '');
// duedate (0..1) date when the current status will expire (deprecated)
$result['duedate'] = (isset($doc['duedate'])
? $this->convertDate($doc['duedate']) : '');
// cancancel (0..1) whether an ordered or provided document can be
// canceled
// error (0..1) error message, for instance if a request was rejected
$result['message'] = ($doc['error'] ?? '');
// storage (0..1) textual description of location of the document
$result['borrowingLocation'] = ($doc['storage'] ?? '');
// storageid (0..1) location URI
// Optional VuFind fields
/*
$result['barcode'] = null;
$result['dueStatus'] = null;
$result['renewLimit'] = "1";
$result['volume'] = null;
$result['publication_year'] = null;
$result['isbn'] = null;
$result['issn'] = null;
$result['oclc'] = null;
$result['upc'] = null;
$result['institution_name'] = null;
*/
$results[] = $result;
}
return $results;
}
/**
* Post something to a foreign host
*
* @param string $file POST target URL
* @param string $data_to_send POST data
* @param string $access_token PAIA access token for current session
*
* @return string POST response
* @throws ILSException
*/
protected function paiaPostRequest($file, $data_to_send, $access_token = null)
{
// json-encoding
$postData = json_encode($data_to_send);
$http_headers = [];
if (isset($access_token)) {
$http_headers['Authorization'] = 'Bearer ' . $access_token;
}
$result = $this->httpService->post(
$this->paiaURL . $file,
$postData,
'application/json; charset=UTF-8',
$this->paiaTimeout,
$http_headers
);
if (!$result->isSuccess()) {
// log error for debugging
$this->debug(
'HTTP status ' . $result->getStatusCode() .
' received'
);
}
// return any result as error-handling is done elsewhere
return $result->getBody();
}
/**
* GET data from foreign host
*
* @param string $file GET target URL
* @param string $access_token PAIA access token for current session
*
* @return bool|string
* @throws ILSException
*/
protected function paiaGetRequest($file, $access_token)
{
$http_headers = [
'Authorization' => 'Bearer ' . $access_token,
'Content-type' => 'application/json; charset=UTF-8',
];
$result = $this->httpService->get(
$this->paiaURL . $file,
[],
$this->paiaTimeout,
$http_headers
);
if (!$result->isSuccess()) {
// log error for debugging
$this->debug(
'HTTP status ' . $result->getStatusCode() .
' received'
);
}
// return any result as error-handling is done elsewhere
return $result->getBody();
}
/**
* Helper function for PAIA to uniformely parse JSON
*
* @param string $file JSON data
*
* @return mixed
* @throws \Exception
*/
protected function paiaParseJsonAsArray($file)
{
$responseArray = json_decode($file, true);
// if we have an error response handle it accordingly (any will throw an
// exception at the moment) and pass on the resulting exception
if (isset($responseArray['error'])) {
$this->paiaHandleErrors($responseArray);
}
return $responseArray;
}
/**
* Retrieve file at given URL and return it as json_decoded array
*
* @param string $file GET target URL
*
* @return array|mixed
* @throws ILSException
*/
protected function paiaGetAsArray($file)
{
$responseJson = $this->paiaGetRequest(
$file,
$this->getSession()->access_token
);
$responseArray = $this->paiaParseJsonAsArray($responseJson);
return $responseArray;
}
/**
* Post something at given URL and return it as json_decoded array
*
* @param string $file POST target URL
* @param array $data POST data
*
* @return array|mixed
* @throws ILSException
*/
protected function paiaPostAsArray($file, $data)
{
$responseJson = $this->paiaPostRequest(
$file,
$data,
$this->getSession()->access_token
);
$responseArray = $this->paiaParseJsonAsArray($responseJson);
return $responseArray;
}
/**
* PAIA authentication function
*
* @param string $username Username
* @param string $password Password
*
* @return mixed Associative array of patron info on successful login,
* null on unsuccessful login, PEAR_Error on error.
* @throws ILSException
*/
protected function paiaLogin($username, $password)
{
// perform full PAIA auth and get patron info
$post_data = [
"username" => $username,
"password" => $password,
"grant_type" => "password",
"scope" => self::SCOPE_READ_PATRON . " " .
self::SCOPE_READ_FEES . " " .
self::SCOPE_READ_ITEMS . " " .
self::SCOPE_WRITE_ITEMS . " " .
self::SCOPE_CHANGE_PASSWORD
];
$responseJson = $this->paiaPostRequest('auth/login', $post_data);
$responseArray = $this->paiaParseJsonAsArray($responseJson);
if (!isset($responseArray['access_token'])) {
throw new ILSException(
'Unknown error! Access denied.'
);
} elseif (!isset($responseArray['patron'])) {
throw new ILSException(
'Login credentials accepted, but got no patron ID?!?'
);
} else {
// at least access_token and patron got returned which is sufficient for
// us, now save all to session
$session = $this->getSession();
$session->patron
= $responseArray['patron'] ?? null;
$session->access_token
= $responseArray['access_token'] ?? null;
$session->scope
= isset($responseArray['scope'])
? explode(' ', $responseArray['scope']) : null;
$session->expires
= isset($responseArray['expires_in'])
? (time() + ($responseArray['expires_in'])) : null;
return true;
}
}
/**
* Support method for paiaLogin() -- load user details into session and return
* array of basic user data.
*
* @param array $patron patron ID
*
* @return array
* @throws ILSException
*/
protected function paiaGetUserDetails($patron)
{
// check if user has appropriate scope (refer to scope declaration above for
// further details)
if (!$this->paiaCheckScope(self::SCOPE_READ_PATRON)) {
throw new ForbiddenException(
'Exception::access_denied_read_patron'
);
}
$responseJson = $this->paiaGetRequest(
'core/' . $patron,
$this->getSession()->access_token
);
$responseArray = $this->paiaParseJsonAsArray($responseJson);
return $this->paiaParseUserDetails($patron, $responseArray);
}
/**
* Checks if the current scope is set for active session.
*
* @param string $scope The scope to test for with the current session scopes.
*
* @return boolean
*/
protected function paiaCheckScope($scope)
{
return (!empty($scope) && is_array($this->getScope()))
? in_array($scope, $this->getScope()) : false;
}
/**
* Check if storage retrieval request available
*
* This is responsible for determining if an item is requestable
*
* @param string $id The Bib ID
* @param array $data An Array of item data
* @param patron $patron An array of patron data
*
* @return bool True if request is valid, false if not
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function checkStorageRetrievalRequestIsValid($id, $data, $patron)
{
return $this->checkRequestIsValid($id, $data, $patron);
}
/**
* Check if hold or recall available
*
* This is responsible for determining if an item is requestable
*
* @param string $id The Bib ID
* @param array $data An Array of item data
* @param patron $patron An array of patron data
*
* @return bool True if request is valid, false if not
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function checkRequestIsValid($id, $data, $patron)
{
// TODO: make this more configurable
if (isset($patron['status']) && $patron['status'] == 0
&& isset($patron['expires']) && $patron['expires'] > date('Y-m-d')
&& in_array(self::SCOPE_WRITE_ITEMS, $this->getScope())
) {
return true;
}
return false;
}
/**
* PAIA support method for PAIA core method 'notifications'
*
* @param array $patron Array with patron information
*
* @return array|mixed Array of system notifications for the patron
* @throws \Exception
* @throws ILSException You are not entitled to read notifications
*/
protected function paiaGetSystemMessages($patron)
{
// check if user has appropriate scope
if (!$this->paiaCheckScope(self::SCOPE_READ_NOTIFICATIONS)) {
throw new ILSException('You are not entitled to read notifications.');
}
$cacheKey = null;
if ($this->paiaCacheEnabled) {
$cacheKey = $this->getCacheKey(
'notifications_' . $patron['cat_username']
);
$response = $this->getCachedData($cacheKey);
if (!empty($response)) {
return $response;
}
}
try {
$response = $this->paiaGetAsArray(
'core/' . $patron['cat_username'] . '/notifications'
);
} catch (\Exception $e) {
// all error handling is done in paiaHandleErrors
// so pass on the exception
throw $e;
}
$response = $this->enrichNotifications($response);
if ($this->paiaCacheEnabled) {
$this->putCachedData($cacheKey, $response);
}
return $response;
}
/**
* Enriches PAIA notifications response with additional mappings
*
* @param array $notifications list of PAIA notifications
*
* @return array list of enriched PAIA notifications
*/
protected function enrichNotifications(array $notifications)
{
// not yet implemented
return $notifications;
}
/**
* PAIA support method for PAIA core method DELETE 'notifications'
*
* @param array $patron Array with patron information
* @param string $messageId PAIA service specific ID
* of the notification to remove
* @param bool $keepCache if set to TRUE the notification cache will survive
* the remote operation, this is used by
* \VuFind\ILS\Driver\PAIA::paiaRemoveSystemMessages
* to avoid unnecessary cache operations
*
* @return array|mixed Array of system notifications for the patron
* @throws \Exception
* @throws ILSException You are not entitled to read notifications
*/
protected function paiaRemoveSystemMessage(
$patron,
$messageId,
$keepCache = false
) {
// check if user has appropriate scope
if (!$this->paiaCheckScope(self::SCOPE_DELETE_NOTIFICATIONS)) {
throw new ILSException('You are not entitled to delete notifications.');
}
try {
$response = $this->paiaDeleteRequest(
'core/'
. $patron['cat_username']
. '/notifications/'
. $this->getPaiaNotificationsId($messageId)
);
} catch (\Exception $e) {
// all error handling is done in paiaHandleErrors
// so pass on the exception
throw $e;
}
if (!$keepCache && $this->paiaCacheEnabled) {
$this->removeCachedData(
$this->getCacheKey('notifications_' . $patron['cat_username'])
);
}
return $response;
}
/**
* Removes multiple System Messages. Bulk deletion is not implemented in PAIA,
* so this method iterates over the set of IDs and removes them separately
*
* @param array $patron Array with patron information
* @param array $messageIds list of PAIA service specific IDs
* of the notifications to remove
*
* @return bool TRUE if all messages have been successfully removed,
* otherwise FALSE
* @throws ILSException
*/
protected function paiaRemoveSystemMessages($patron, array $messageIds)
{
foreach ($messageIds as $messageId) {
if (!$this->paiaRemoveSystemMessage($patron, $messageId, true)) {
return false;
}
}
if ($this->paiaCacheEnabled) {
$this->removeCachedData(
$this->getCacheKey('notifications_' . $patron['cat_username'])
);
}
return true;
}
/**
* Get notification identifier from message identifier
*
* @param string $messageId Message identifier
*
* @return string
*/
protected function getPaiaNotificationsId($messageId)
{
return $messageId;
}
/**
* DELETE data on foreign host
*
* @param string $file DELETE target URL
* @param string $access_token PAIA access token for current session
*
* @return bool|string
* @throws ILSException
*/
protected function paiaDeleteRequest($file, $access_token = null)
{
if (null === $access_token) {
$access_token = $this->getSession()->access_token;
}
$http_headers = [
'Authorization' => 'Bearer ' . $access_token,
'Content-type' => 'application/json; charset=UTF-8',
];
try {
$client = $this->httpService->createClient(
$this->paiaURL . $file,
\Laminas\Http\Request::METHOD_DELETE,
$this->paiaTimeout
);
$client->setHeaders($http_headers);
$result = $client->send();
} catch (\Exception $e) {
$this->throwAsIlsException($e);
}
if (!$result->isSuccess()) {
// log error for debugging
$this->debug(
'HTTP status ' . $result->getStatusCode() .
' received'
);
return false;
}
// return TRUE on success
return true;
}
}
| 1 | 32,537 | I think you could condense this code considerably by getting rid of the initialization and foreach loop and simply saying: `$firstname = trim(implode(' ', $nameArr));` What do you think? | vufind-org-vufind | php |
@@ -1,5 +1,4 @@
#!/usr/bin/env node
-'use strict'
const userAgent = process.env.npm_config_user_agent
if (!userAgent) { | 1 | #!/usr/bin/env node
'use strict'
const userAgent = process.env.npm_config_user_agent
if (!userAgent) {
// not much we can do
process.exit()
}
if (/^npm\/7/.test(userAgent)) {
console.error('Please use npm 6 to work in the Uppy monorepo.')
console.error('You can execute individual commands with npm 6 like below:')
console.error()
console.error(' $ npx npm@6 install')
console.error()
console.error('This way you can still use npm 7 in your other projects.')
process.exit(1)
}
| 1 | 13,826 | hmm, we actually should _add_ `'use strict'` everywhere | transloadit-uppy | js |
@@ -905,7 +905,7 @@ public class JdbcProjectImpl implements ProjectLoader {
propsName);
if (properties == null || properties.isEmpty()) {
- logger.warn("Project " + projectId + " version " + projectVer + " property " + propsName
+ logger.debug("Project " + projectId + " version " + projectVer + " property " + propsName
+ " is empty.");
return null;
} | 1 | /*
* Copyright 2017 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.project;
import static azkaban.project.JdbcProjectHandlerSet.IntHandler;
import static azkaban.project.JdbcProjectHandlerSet.ProjectFileChunkResultHandler;
import static azkaban.project.JdbcProjectHandlerSet.ProjectFlowsResultHandler;
import static azkaban.project.JdbcProjectHandlerSet.ProjectLogsResultHandler;
import static azkaban.project.JdbcProjectHandlerSet.ProjectPermissionsResultHandler;
import static azkaban.project.JdbcProjectHandlerSet.ProjectPropertiesResultsHandler;
import static azkaban.project.JdbcProjectHandlerSet.ProjectResultHandler;
import static azkaban.project.JdbcProjectHandlerSet.ProjectVersionResultHandler;
import azkaban.db.DatabaseOperator;
import azkaban.db.DatabaseTransOperator;
import azkaban.db.EncodingType;
import azkaban.db.SQLTransaction;
import azkaban.flow.Flow;
import azkaban.project.JdbcProjectHandlerSet.FlowFileResultHandler;
import azkaban.project.ProjectLogEvent.EventType;
import azkaban.user.Permission;
import azkaban.user.User;
import azkaban.utils.GZIPUtils;
import azkaban.utils.JSONUtils;
import azkaban.utils.Md5Hasher;
import azkaban.utils.Pair;
import azkaban.utils.Props;
import azkaban.utils.PropsUtils;
import azkaban.utils.Triple;
import com.google.common.io.Files;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
/**
* This class implements ProjectLoader using new azkaban-db code to allow DB failover. TODO
* kunkun-tang: This class is too long. In future, we should split {@link ProjectLoader} interface
* and have multiple short class implementations.
*/
@Singleton
public class JdbcProjectImpl implements ProjectLoader {
private static final Logger logger = Logger.getLogger(JdbcProjectImpl.class);
private static final int CHUCK_SIZE = 1024 * 1024 * 10;
// Flow yaml files are usually small, set size limitation to 10 MB should be sufficient for now.
private static final int MAX_FLOW_FILE_SIZE_IN_BYTES = 1024 * 1024 * 10;
private final DatabaseOperator dbOperator;
private final File tempDir;
private final EncodingType defaultEncodingType = EncodingType.GZIP;
@Inject
public JdbcProjectImpl(final Props props, final DatabaseOperator databaseOperator) {
this.dbOperator = databaseOperator;
this.tempDir = new File(props.getString("project.temp.dir", "temp"));
if (!this.tempDir.exists()) {
if (this.tempDir.mkdirs()) {
logger.info("project temporary folder is being constructed.");
} else {
logger.info("project temporary folder already existed.");
}
}
}
@Override
public List<Project> fetchAllActiveProjects() throws ProjectManagerException {
final ProjectResultHandler handler = new ProjectResultHandler();
List<Project> projects = null;
try {
projects = this.dbOperator.query(ProjectResultHandler.SELECT_ALL_ACTIVE_PROJECTS, handler);
projects.forEach(project -> {
for (final Triple<String, Boolean, Permission> perm : fetchPermissionsForProject(project)) {
setProjectPermission(project, perm);
}
});
} catch (final SQLException ex) {
logger.error(ProjectResultHandler.SELECT_PROJECT_BY_ID + " failed.", ex);
throw new ProjectManagerException("Error retrieving all projects", ex);
}
return projects;
}
private void setProjectPermission(final Project project,
final Triple<String, Boolean, Permission> perm) {
if (perm.getSecond()) {
project.setGroupPermission(perm.getFirst(), perm.getThird());
} else {
project.setUserPermission(perm.getFirst(), perm.getThird());
}
}
@Override
public Project fetchProjectById(final int id) throws ProjectManagerException {
Project project = null;
final ProjectResultHandler handler = new ProjectResultHandler();
try {
final List<Project> projects = this.dbOperator
.query(ProjectResultHandler.SELECT_PROJECT_BY_ID, handler, id);
if (projects.isEmpty()) {
throw new ProjectManagerException("No project with id " + id + " exists in db.");
}
project = projects.get(0);
// Fetch the user permissions
for (final Triple<String, Boolean, Permission> perm : fetchPermissionsForProject(project)) {
// TODO kunkun-tang: understand why we need to check permission not equal to 0 here.
if (perm.getThird().toFlags() != 0) {
setProjectPermission(project, perm);
}
}
} catch (final SQLException ex) {
logger.error(ProjectResultHandler.SELECT_PROJECT_BY_ID + " failed.", ex);
throw new ProjectManagerException("Query for existing project failed. Project " + id, ex);
}
return project;
}
@Override
public Project fetchProjectByName(final String name) throws ProjectManagerException {
Project project = null;
final ProjectResultHandler handler = new ProjectResultHandler();
// select active project from db first, if not exist, select inactive one.
// At most one active project with the same name exists in db.
try {
List<Project> projects = this.dbOperator
.query(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME, handler, name);
if (projects.isEmpty()) {
projects = this.dbOperator
.query(ProjectResultHandler.SELECT_PROJECT_BY_NAME, handler, name);
if (projects.isEmpty()) {
throw new ProjectManagerException("No project with name " + name + " exists in db.");
}
}
project = projects.get(0);
for (final Triple<String, Boolean, Permission> perm : fetchPermissionsForProject(project)) {
if (perm.getThird().toFlags() != 0) {
setProjectPermission(project, perm);
}
}
} catch (final SQLException ex) {
logger.error(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME + " failed.", ex);
throw new ProjectManagerException(
ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME + " failed.", ex);
}
return project;
}
private List<Triple<String, Boolean, Permission>> fetchPermissionsForProject(
final Project project)
throws ProjectManagerException {
final ProjectPermissionsResultHandler permHander = new ProjectPermissionsResultHandler();
List<Triple<String, Boolean, Permission>> permissions = null;
try {
permissions =
this.dbOperator
.query(ProjectPermissionsResultHandler.SELECT_PROJECT_PERMISSION, permHander,
project.getId());
} catch (final SQLException ex) {
logger.error(ProjectPermissionsResultHandler.SELECT_PROJECT_PERMISSION + " failed.", ex);
throw new ProjectManagerException(
"Query for permissions for " + project.getName() + " failed.", ex);
}
return permissions;
}
/**
* Creates a Project in the db.
*
* It will throw an exception if it finds an active project of the same name, or the SQL fails
*/
@Override
public synchronized Project createNewProject(final String name, final String description,
final User creator)
throws ProjectManagerException {
final ProjectResultHandler handler = new ProjectResultHandler();
// Check if the same project name exists.
try {
final List<Project> projects = this.dbOperator
.query(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME, handler, name);
if (!projects.isEmpty()) {
throw new ProjectManagerException(
"Active project with name " + name + " already exists in db.");
}
} catch (final SQLException ex) {
logger.error(ex);
throw new ProjectManagerException("Checking for existing project failed. " + name, ex);
}
final String INSERT_PROJECT =
"INSERT INTO projects ( name, active, modified_time, create_time, version, last_modified_by, description, enc_type, settings_blob) values (?,?,?,?,?,?,?,?,?)";
final SQLTransaction<Integer> insertProject = transOperator -> {
final long time = System.currentTimeMillis();
return transOperator
.update(INSERT_PROJECT, name, true, time, time, null, creator.getUserId(), description,
this.defaultEncodingType.getNumVal(), null);
};
// Insert project
try {
final int numRowsInserted = this.dbOperator.transaction(insertProject);
if (numRowsInserted == 0) {
throw new ProjectManagerException("No projects have been inserted.");
}
} catch (final SQLException ex) {
logger.error(INSERT_PROJECT + " failed.", ex);
throw new ProjectManagerException("Insert project" + name + " for existing project failed. ",
ex);
}
return fetchProjectByName(name);
}
@Override
public void uploadProjectFile(final int projectId, final int version, final File localFile,
final String uploader)
throws ProjectManagerException {
final long startMs = System.currentTimeMillis();
logger.info(String
.format("Uploading Project ID: %d file: %s [%d bytes]", projectId, localFile.getName(),
localFile.length()));
/*
* The below transaction uses one connection to do all operations. Ideally, we should commit
* after the transaction completes. However, uploadFile needs to commit every time when we
* upload any single chunk.
*
* Todo kunkun-tang: fix the transaction issue.
*/
final SQLTransaction<Integer> uploadProjectFileTransaction = transOperator -> {
/* Step 1: Update DB with new project info */
addProjectToProjectVersions(transOperator, projectId, version, localFile, uploader,
computeHash(localFile), null);
transOperator.getConnection().commit();
/* Step 2: Upload File in chunks to DB */
final int chunks = uploadFileInChunks(transOperator, projectId, version, localFile);
/* Step 3: Update number of chunks in DB */
updateChunksInProjectVersions(transOperator, projectId, version, chunks);
return 1;
};
try {
this.dbOperator.transaction(uploadProjectFileTransaction);
} catch (final SQLException e) {
logger.error("upload project files failed.", e);
throw new ProjectManagerException("upload project files failed.", e);
}
final long duration = (System.currentTimeMillis() - startMs) / 1000;
logger.info(String.format("Uploaded Project ID: %d file: %s [%d bytes] in %d sec", projectId,
localFile.getName(),
localFile.length(), duration));
}
private byte[] computeHash(final File localFile) {
logger.info("Creating message digest for upload " + localFile.getName());
final byte[] md5;
try {
md5 = Md5Hasher.md5Hash(localFile);
} catch (final IOException e) {
throw new ProjectManagerException("Error getting md5 hash.", e);
}
logger.info("Md5 hash created");
return md5;
}
@Override
public void addProjectVersion(
final int projectId,
final int version,
final File localFile,
final String uploader,
final byte[] md5,
final String resourceId) throws ProjectManagerException {
// when one transaction completes, it automatically commits.
final SQLTransaction<Integer> transaction = transOperator -> {
addProjectToProjectVersions(transOperator, projectId, version, localFile, uploader, md5,
resourceId);
return 1;
};
try {
this.dbOperator.transaction(transaction);
} catch (final SQLException e) {
logger.error("addProjectVersion failed.", e);
throw new ProjectManagerException("addProjectVersion failed.", e);
}
}
/**
* Insert a new version record to TABLE project_versions before uploading files.
*
* The reason for this operation: When error chunking happens in remote mysql server, incomplete
* file data remains in DB, and an SQL exception is thrown. If we don't have this operation before
* uploading file, the SQL exception prevents AZ from creating the new version record in Table
* project_versions. However, the Table project_files still reserve the incomplete files, which
* causes troubles when uploading a new file: Since the version in TABLE project_versions is still
* old, mysql will stop inserting new files to db.
*
* Why this operation is safe: When AZ uploads a new zip file, it always fetches the latest
* version proj_v from TABLE project_version, proj_v+1 will be used as the new version for the
* uploading files.
*
* Assume error chunking happens on day 1. proj_v is created for this bad file (old file version +
* 1). When we upload a new project zip in day2, new file in day 2 will use the new version
* (proj_v + 1). When file uploading completes, AZ will clean all old chunks in DB afterward.
*/
private void addProjectToProjectVersions(
final DatabaseTransOperator transOperator,
final int projectId,
final int version,
final File localFile,
final String uploader,
final byte[] md5,
final String resourceId) throws ProjectManagerException {
final long updateTime = System.currentTimeMillis();
final String INSERT_PROJECT_VERSION = "INSERT INTO project_versions "
+ "(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id) values "
+ "(?,?,?,?,?,?,?,?,?)";
try {
/*
* As we don't know the num_chunks before uploading the file, we initialize it to 0,
* and will update it after uploading completes.
*/
transOperator.update(INSERT_PROJECT_VERSION, projectId, version, updateTime, uploader,
Files.getFileExtension(localFile.getName()), localFile.getName(), md5, 0, resourceId);
} catch (final SQLException e) {
final String msg = String
.format("Error initializing project id: %d version: %d ", projectId, version);
logger.error(msg, e);
throw new ProjectManagerException(msg, e);
}
}
private int uploadFileInChunks(final DatabaseTransOperator transOperator, final int projectId,
final int version, final File localFile)
throws ProjectManagerException {
// Really... I doubt we'll get a > 2gig file. So int casting it is!
final byte[] buffer = new byte[CHUCK_SIZE];
final String INSERT_PROJECT_FILES =
"INSERT INTO project_files (project_id, version, chunk, size, file) values (?,?,?,?,?)";
BufferedInputStream bufferedStream = null;
int chunk = 0;
try {
bufferedStream = new BufferedInputStream(new FileInputStream(localFile));
int size = bufferedStream.read(buffer);
while (size >= 0) {
logger.info("Read bytes for " + localFile.getName() + " size:" + size);
byte[] buf = buffer;
if (size < buffer.length) {
buf = Arrays.copyOfRange(buffer, 0, size);
}
try {
logger.info("Running update for " + localFile.getName() + " chunk " + chunk);
transOperator.update(INSERT_PROJECT_FILES, projectId, version, chunk, size, buf);
/*
* We enforce az committing to db when uploading every single chunk,
* in order to reduce the transaction duration and conserve sql server resources.
*
* If the files to be uploaded is very large and we don't commit every single chunk,
* the remote mysql server will run into memory troubles.
*/
transOperator.getConnection().commit();
logger.info("Finished update for " + localFile.getName() + " chunk " + chunk);
} catch (final SQLException e) {
throw new ProjectManagerException("Error Chunking during uploading files to db...");
}
++chunk;
size = bufferedStream.read(buffer);
}
} catch (final IOException e) {
throw new ProjectManagerException(
String.format(
"Error chunking file. projectId: %d, version: %d, file:%s[%d bytes], chunk: %d",
projectId,
version, localFile.getName(), localFile.length(), chunk));
} finally {
IOUtils.closeQuietly(bufferedStream);
}
return chunk;
}
/**
* we update num_chunks's actual number to db here.
*/
private void updateChunksInProjectVersions(final DatabaseTransOperator transOperator,
final int projectId, final int version, final int chunk)
throws ProjectManagerException {
final String UPDATE_PROJECT_NUM_CHUNKS =
"UPDATE project_versions SET num_chunks=? WHERE project_id=? AND version=?";
try {
transOperator.update(UPDATE_PROJECT_NUM_CHUNKS, chunk, projectId, version);
transOperator.getConnection().commit();
} catch (final SQLException e) {
logger.error("Error updating project " + projectId + " : chunk_num " + chunk, e);
throw new ProjectManagerException(
"Error updating project " + projectId + " : chunk_num " + chunk, e);
}
}
@Override
public ProjectFileHandler fetchProjectMetaData(final int projectId, final int version) {
final ProjectVersionResultHandler pfHandler = new ProjectVersionResultHandler();
try {
final List<ProjectFileHandler> projectFiles =
this.dbOperator
.query(ProjectVersionResultHandler.SELECT_PROJECT_VERSION, pfHandler, projectId,
version);
if (projectFiles == null || projectFiles.isEmpty()) {
return null;
}
return projectFiles.get(0);
} catch (final SQLException ex) {
logger.error("Query for uploaded file for project id " + projectId + " failed.", ex);
throw new ProjectManagerException(
"Query for uploaded file for project id " + projectId + " failed.", ex);
}
}
@Override
public ProjectFileHandler getUploadedFile(final int projectId, final int version)
throws ProjectManagerException {
final ProjectFileHandler projHandler = fetchProjectMetaData(projectId, version);
if (projHandler == null) {
return null;
}
final int numChunks = projHandler.getNumChunks();
BufferedOutputStream bStream = null;
File file;
try {
try {
file = File
.createTempFile(projHandler.getFileName(), String.valueOf(version), this.tempDir);
bStream = new BufferedOutputStream(new FileOutputStream(file));
} catch (final IOException e) {
throw new ProjectManagerException("Error creating temp file for stream.");
}
final int collect = 5;
int fromChunk = 0;
int toChunk = collect;
do {
final ProjectFileChunkResultHandler chunkHandler = new ProjectFileChunkResultHandler();
List<byte[]> data = null;
try {
data = this.dbOperator
.query(ProjectFileChunkResultHandler.SELECT_PROJECT_CHUNKS_FILE, chunkHandler,
projectId,
version, fromChunk, toChunk);
} catch (final SQLException e) {
logger.error(e);
throw new ProjectManagerException("Query for uploaded file for " + projectId + " failed.",
e);
}
try {
for (final byte[] d : data) {
bStream.write(d);
}
} catch (final IOException e) {
throw new ProjectManagerException("Error writing file", e);
}
// Add all the bytes to the stream.
fromChunk += collect;
toChunk += collect;
} while (fromChunk <= numChunks);
} finally {
IOUtils.closeQuietly(bStream);
}
// Check md5.
byte[] md5 = null;
try {
md5 = Md5Hasher.md5Hash(file);
} catch (final IOException e) {
throw new ProjectManagerException("Error getting md5 hash.", e);
}
if (Arrays.equals(projHandler.getMd5Hash(), md5)) {
logger.info("Md5 Hash is valid");
} else {
throw new ProjectManagerException("Md5 Hash failed on retrieval of file");
}
projHandler.setLocalFile(file);
return projHandler;
}
@Override
public void changeProjectVersion(final Project project, final int version, final String user)
throws ProjectManagerException {
final long timestamp = System.currentTimeMillis();
try {
final String UPDATE_PROJECT_VERSION =
"UPDATE projects SET version=?,modified_time=?,last_modified_by=? WHERE id=?";
this.dbOperator.update(UPDATE_PROJECT_VERSION, version, timestamp, user, project.getId());
project.setVersion(version);
project.setLastModifiedTimestamp(timestamp);
project.setLastModifiedUser(user);
} catch (final SQLException e) {
logger.error("Error updating switching project version " + project.getName(), e);
throw new ProjectManagerException(
"Error updating switching project version " + project.getName(), e);
}
}
@Override
public void updatePermission(final Project project, final String name, final Permission perm,
final boolean isGroup)
throws ProjectManagerException {
final long updateTime = System.currentTimeMillis();
try {
if (this.dbOperator.getDataSource().allowsOnDuplicateKey()) {
final String INSERT_PROJECT_PERMISSION =
"INSERT INTO project_permissions (project_id, modified_time, name, permissions, isGroup) values (?,?,?,?,?)"
+ "ON DUPLICATE KEY UPDATE modified_time = VALUES(modified_time), permissions = VALUES(permissions)";
this.dbOperator
.update(INSERT_PROJECT_PERMISSION, project.getId(), updateTime, name, perm.toFlags(),
isGroup);
} else {
final String MERGE_PROJECT_PERMISSION =
"MERGE INTO project_permissions (project_id, modified_time, name, permissions, isGroup) KEY (project_id, name) values (?,?,?,?,?)";
this.dbOperator
.update(MERGE_PROJECT_PERMISSION, project.getId(), updateTime, name, perm.toFlags(),
isGroup);
}
} catch (final SQLException ex) {
logger.error("Error updating project permission", ex);
throw new ProjectManagerException(
"Error updating project " + project.getName() + " permissions for " + name, ex);
}
if (isGroup) {
project.setGroupPermission(name, perm);
} else {
project.setUserPermission(name, perm);
}
}
@Override
public void updateProjectSettings(final Project project) throws ProjectManagerException {
updateProjectSettings(project, this.defaultEncodingType);
}
private byte[] convertJsonToBytes(final EncodingType type, final String json) throws IOException {
byte[] data = json.getBytes("UTF-8");
if (type == EncodingType.GZIP) {
data = GZIPUtils.gzipBytes(data);
}
return data;
}
private void updateProjectSettings(final Project project, final EncodingType encType)
throws ProjectManagerException {
final String UPDATE_PROJECT_SETTINGS = "UPDATE projects SET enc_type=?, settings_blob=? WHERE id=?";
final String json = JSONUtils.toJSON(project.toObject());
byte[] data = null;
try {
data = convertJsonToBytes(encType, json);
logger.debug("NumChars: " + json.length() + " Gzip:" + data.length);
} catch (final IOException e) {
throw new ProjectManagerException("Failed to encode. ", e);
}
try {
this.dbOperator.update(UPDATE_PROJECT_SETTINGS, encType.getNumVal(), data, project.getId());
} catch (final SQLException e) {
logger.error("update Project Settings failed.", e);
throw new ProjectManagerException(
"Error updating project " + project.getName() + " version " + project.getVersion(), e);
}
}
@Override
public void removePermission(final Project project, final String name, final boolean isGroup)
throws ProjectManagerException {
final String DELETE_PROJECT_PERMISSION =
"DELETE FROM project_permissions WHERE project_id=? AND name=? AND isGroup=?";
try {
this.dbOperator.update(DELETE_PROJECT_PERMISSION, project.getId(), name, isGroup);
} catch (final SQLException e) {
logger.error("remove Permission failed.", e);
throw new ProjectManagerException(
"Error deleting project " + project.getName() + " permissions for " + name, e);
}
if (isGroup) {
project.removeGroupPermission(name);
} else {
project.removeUserPermission(name);
}
}
@Override
public List<Triple<String, Boolean, Permission>> getProjectPermissions(final Project project)
throws ProjectManagerException {
return fetchPermissionsForProject(project);
}
/**
* Todo kunkun-tang: the below implementation doesn't remove a project, but inactivate a project.
* We should rewrite the code to follow the literal meanings.
*/
@Override
public void removeProject(final Project project, final String user)
throws ProjectManagerException {
final long updateTime = System.currentTimeMillis();
final String UPDATE_INACTIVE_PROJECT =
"UPDATE projects SET active=false,modified_time=?,last_modified_by=? WHERE id=?";
try {
this.dbOperator.update(UPDATE_INACTIVE_PROJECT, updateTime, user, project.getId());
} catch (final SQLException e) {
logger.error("error remove project " + project.getName(), e);
throw new ProjectManagerException("Error remove project " + project.getName(), e);
}
}
@Override
public boolean postEvent(final Project project, final EventType type, final String user,
final String message) {
final String INSERT_PROJECT_EVENTS =
"INSERT INTO project_events (project_id, event_type, event_time, username, message) values (?,?,?,?,?)";
final long updateTime = System.currentTimeMillis();
try {
this.dbOperator
.update(INSERT_PROJECT_EVENTS, project.getId(), type.getNumVal(), updateTime, user,
message);
} catch (final SQLException e) {
logger.error("post event failed,", e);
return false;
}
return true;
}
@Override
public List<ProjectLogEvent> getProjectEvents(final Project project, final int num,
final int skip) throws ProjectManagerException {
final ProjectLogsResultHandler logHandler = new ProjectLogsResultHandler();
List<ProjectLogEvent> events = null;
try {
events = this.dbOperator
.query(ProjectLogsResultHandler.SELECT_PROJECT_EVENTS_ORDER, logHandler, project.getId(),
num,
skip);
} catch (final SQLException e) {
logger.error("Error getProjectEvents, project " + project.getName(), e);
throw new ProjectManagerException("Error getProjectEvents, project " + project.getName(), e);
}
return events;
}
@Override
public void updateDescription(final Project project, final String description, final String user)
throws ProjectManagerException {
final String UPDATE_PROJECT_DESCRIPTION =
"UPDATE projects SET description=?,modified_time=?,last_modified_by=? WHERE id=?";
final long updateTime = System.currentTimeMillis();
try {
this.dbOperator
.update(UPDATE_PROJECT_DESCRIPTION, description, updateTime, user, project.getId());
project.setDescription(description);
project.setLastModifiedTimestamp(updateTime);
project.setLastModifiedUser(user);
} catch (final SQLException e) {
logger.error(e);
throw new ProjectManagerException("Error update Description, project " + project.getName(),
e);
}
}
@Override
public int getLatestProjectVersion(final Project project) throws ProjectManagerException {
final IntHandler handler = new IntHandler();
try {
return this.dbOperator.query(IntHandler.SELECT_LATEST_VERSION, handler, project.getId());
} catch (final SQLException e) {
logger.error(e);
throw new ProjectManagerException(
"Error marking project " + project.getName() + " as inactive", e);
}
}
@Override
public void uploadFlows(final Project project, final int version, final Collection<Flow> flows)
throws ProjectManagerException {
// We do one at a time instead of batch... because well, the batch could be
// large.
logger.info("Uploading flows");
try {
for (final Flow flow : flows) {
uploadFlow(project, version, flow, this.defaultEncodingType);
}
} catch (final IOException e) {
throw new ProjectManagerException("Flow Upload failed.", e);
}
}
@Override
public void uploadFlow(final Project project, final int version, final Flow flow)
throws ProjectManagerException {
logger.info("Uploading flow " + flow.getId());
try {
uploadFlow(project, version, flow, this.defaultEncodingType);
} catch (final IOException e) {
throw new ProjectManagerException("Flow Upload failed.", e);
}
}
@Override
public void updateFlow(final Project project, final int version, final Flow flow)
throws ProjectManagerException {
logger.info("Uploading flow " + flow.getId());
try {
final String json = JSONUtils.toJSON(flow.toObject());
final byte[] data = convertJsonToBytes(this.defaultEncodingType, json);
logger.info("Flow upload " + flow.getId() + " is byte size " + data.length);
final String UPDATE_FLOW =
"UPDATE project_flows SET encoding_type=?,json=? WHERE project_id=? AND version=? AND flow_id=?";
try {
this.dbOperator
.update(UPDATE_FLOW, this.defaultEncodingType.getNumVal(), data, project.getId(),
version, flow.getId());
} catch (final SQLException e) {
logger.error("Error inserting flow", e);
throw new ProjectManagerException("Error inserting flow " + flow.getId(), e);
}
} catch (final IOException e) {
throw new ProjectManagerException("Flow Upload failed.", e);
}
}
private void uploadFlow(final Project project, final int version, final Flow flow,
final EncodingType encType)
throws ProjectManagerException, IOException {
final String json = JSONUtils.toJSON(flow.toObject());
final byte[] data = convertJsonToBytes(encType, json);
logger.info("Flow upload " + flow.getId() + " is byte size " + data.length);
final String INSERT_FLOW =
"INSERT INTO project_flows (project_id, version, flow_id, modified_time, encoding_type, json) values (?,?,?,?,?,?)";
try {
this.dbOperator
.update(INSERT_FLOW, project.getId(), version, flow.getId(), System.currentTimeMillis(),
encType.getNumVal(), data);
} catch (final SQLException e) {
logger.error("Error inserting flow", e);
throw new ProjectManagerException("Error inserting flow " + flow.getId(), e);
}
}
@Override
public Flow fetchFlow(final Project project, final String flowId) throws ProjectManagerException {
throw new UnsupportedOperationException("this method has not been instantiated.");
}
@Override
public List<Flow> fetchAllProjectFlows(final Project project) throws ProjectManagerException {
final ProjectFlowsResultHandler handler = new ProjectFlowsResultHandler();
List<Flow> flows = null;
try {
flows = this.dbOperator
.query(ProjectFlowsResultHandler.SELECT_ALL_PROJECT_FLOWS, handler, project.getId(),
project.getVersion());
} catch (final SQLException e) {
throw new ProjectManagerException(
"Error fetching flows from project " + project.getName() + " version " + project
.getVersion(), e);
}
return flows;
}
@Override
public void uploadProjectProperties(final Project project, final List<Props> properties)
throws ProjectManagerException {
for (final Props props : properties) {
try {
uploadProjectProperty(project, props.getSource(), props);
} catch (final IOException e) {
throw new ProjectManagerException("Error uploading project property file", e);
}
}
}
@Override
public void uploadProjectProperty(final Project project, final Props props)
throws ProjectManagerException {
try {
uploadProjectProperty(project, props.getSource(), props);
} catch (final IOException e) {
throw new ProjectManagerException("Error uploading project property file", e);
}
}
@Override
public void updateProjectProperty(final Project project, final Props props)
throws ProjectManagerException {
try {
updateProjectProperty(project, props.getSource(), props);
} catch (final IOException e) {
throw new ProjectManagerException("Error uploading project property file", e);
}
}
private void updateProjectProperty(final Project project, final String name, final Props props)
throws ProjectManagerException, IOException {
final String UPDATE_PROPERTIES =
"UPDATE project_properties SET property=? WHERE project_id=? AND version=? AND name=?";
final byte[] propsData = getBytes(props);
try {
this.dbOperator
.update(UPDATE_PROPERTIES, propsData, project.getId(), project.getVersion(), name);
} catch (final SQLException e) {
throw new ProjectManagerException(
"Error updating property " + project.getName() + " version " + project.getVersion(), e);
}
}
private void uploadProjectProperty(final Project project, final String name, final Props props)
throws ProjectManagerException, IOException {
final String INSERT_PROPERTIES =
"INSERT INTO project_properties (project_id, version, name, modified_time, encoding_type, property) values (?,?,?,?,?,?)";
final byte[] propsData = getBytes(props);
try {
this.dbOperator.update(INSERT_PROPERTIES, project.getId(), project.getVersion(), name,
System.currentTimeMillis(),
this.defaultEncodingType.getNumVal(), propsData);
} catch (final SQLException e) {
throw new ProjectManagerException(
"Error uploading project properties " + name + " into " + project.getName() + " version "
+ project.getVersion(), e);
}
}
private byte[] getBytes(final Props props) throws IOException {
final String propertyJSON = PropsUtils.toJSONString(props, true);
byte[] data = propertyJSON.getBytes("UTF-8");
if (this.defaultEncodingType == EncodingType.GZIP) {
data = GZIPUtils.gzipBytes(data);
}
return data;
}
@Override
public Props fetchProjectProperty(final int projectId, final int projectVer,
final String propsName) throws ProjectManagerException {
final ProjectPropertiesResultsHandler handler = new ProjectPropertiesResultsHandler();
try {
final List<Pair<String, Props>> properties =
this.dbOperator
.query(ProjectPropertiesResultsHandler.SELECT_PROJECT_PROPERTY, handler, projectId,
projectVer,
propsName);
if (properties == null || properties.isEmpty()) {
logger.warn("Project " + projectId + " version " + projectVer + " property " + propsName
+ " is empty.");
return null;
}
return properties.get(0).getSecond();
} catch (final SQLException e) {
logger.error("Error fetching property " + propsName + " Project " + projectId + " version "
+ projectVer, e);
throw new ProjectManagerException("Error fetching property " + propsName, e);
}
}
@Override
public Props fetchProjectProperty(final Project project, final String propsName)
throws ProjectManagerException {
return fetchProjectProperty(project.getId(), project.getVersion(), propsName);
}
@Override
public Map<String, Props> fetchProjectProperties(final int projectId, final int version)
throws ProjectManagerException {
try {
final List<Pair<String, Props>> properties = this.dbOperator
.query(ProjectPropertiesResultsHandler.SELECT_PROJECT_PROPERTIES,
new ProjectPropertiesResultsHandler(), projectId, version);
if (properties == null || properties.isEmpty()) {
return null;
}
final HashMap<String, Props> props = new HashMap<>();
for (final Pair<String, Props> pair : properties) {
props.put(pair.getFirst(), pair.getSecond());
}
return props;
} catch (final SQLException e) {
logger.error("Error fetching properties, project id" + projectId + " version " + version, e);
throw new ProjectManagerException("Error fetching properties", e);
}
}
@Override
public void cleanOlderProjectVersion(final int projectId, final int version)
throws ProjectManagerException {
final String DELETE_FLOW = "DELETE FROM project_flows WHERE project_id=? AND version<?";
final String DELETE_PROPERTIES = "DELETE FROM project_properties WHERE project_id=? AND version<?";
final String DELETE_PROJECT_FILES = "DELETE FROM project_files WHERE project_id=? AND version<?";
final String UPDATE_PROJECT_VERSIONS = "UPDATE project_versions SET num_chunks=0 WHERE project_id=? AND version<?";
// Todo jamiesjc: delete flow files
final SQLTransaction<Integer> cleanOlderProjectTransaction = transOperator -> {
transOperator.update(DELETE_FLOW, projectId, version);
transOperator.update(DELETE_PROPERTIES, projectId, version);
transOperator.update(DELETE_PROJECT_FILES, projectId, version);
return transOperator.update(UPDATE_PROJECT_VERSIONS, projectId, version);
};
try {
final int res = this.dbOperator.transaction(cleanOlderProjectTransaction);
if (res == 0) {
logger.info("clean older project given project id " + projectId + " doesn't take effect.");
}
} catch (final SQLException e) {
logger.error("clean older project transaction failed", e);
throw new ProjectManagerException("clean older project transaction failed", e);
}
}
@Override
public void uploadFlowFile(final int projectId, final int projectVersion, final File flowFile,
final int flowVersion) throws ProjectManagerException {
logger.info(String
.format(
"Uploading flow file %s, version %d for project %d, version %d, file length is [%d bytes]",
flowFile.getName(), flowVersion, projectId, projectVersion, flowFile.length()));
if (flowFile.length() > MAX_FLOW_FILE_SIZE_IN_BYTES) {
throw new ProjectManagerException("Flow file length exceeds 10 MB limit.");
}
final byte[] buffer = new byte[MAX_FLOW_FILE_SIZE_IN_BYTES];
final String INSERT_FLOW_FILES =
"INSERT INTO project_flow_files (project_id, project_version, flow_name, flow_version, "
+ "modified_time, "
+ "flow_file) values (?,?,?,?,?,?)";
try (final FileInputStream input = new FileInputStream(flowFile);
final BufferedInputStream bufferedStream = new BufferedInputStream(input)) {
final int size = bufferedStream.read(buffer);
logger.info("Read bytes for " + flowFile.getName() + ", size:" + size);
final byte[] buf = Arrays.copyOfRange(buffer, 0, size);
try {
this.dbOperator
.update(INSERT_FLOW_FILES, projectId, projectVersion, flowFile.getName(), flowVersion,
System.currentTimeMillis(), buf);
} catch (final SQLException e) {
throw new ProjectManagerException(
"Error uploading flow file " + flowFile.getName() + ", version " + flowVersion + ".",
e);
}
} catch (final IOException e) {
throw new ProjectManagerException(
String.format(
"Error reading flow file %s, version: %d, length: [%d bytes].",
flowFile.getName(), flowVersion, flowFile.length()));
}
}
@Override
public File getUploadedFlowFile(final int projectId, final int projectVersion,
final String flowFileName, final int flowVersion, final File tempDir)
throws ProjectManagerException, IOException {
final FlowFileResultHandler handler = new FlowFileResultHandler();
final List<byte[]> data;
// Created separate temp directory for each flow file to avoid overwriting the same file by
// multiple threads concurrently. Flow file name will be interpret as the flow name when
// parsing the yaml flow file, so it has to be specific.
final File file = new File(tempDir, flowFileName);
try (final FileOutputStream output = new FileOutputStream(file);
final BufferedOutputStream bufferedStream = new BufferedOutputStream(output)) {
try {
data = this.dbOperator
.query(FlowFileResultHandler.SELECT_FLOW_FILE, handler,
projectId, projectVersion, flowFileName, flowVersion);
} catch (final SQLException e) {
throw new ProjectManagerException(
"Failed to query uploaded flow file for project " + projectId + " version "
+ projectVersion + ", flow file " + flowFileName + " version " + flowVersion, e);
}
if (data == null || data.isEmpty()) {
throw new ProjectManagerException(
"No flow file could be found in DB table for project " + projectId + " version " +
projectVersion + ", flow file " + flowFileName + " version " + flowVersion);
}
bufferedStream.write(data.get(0));
} catch (final IOException e) {
throw new ProjectManagerException(
"Error writing to output stream for project " + projectId + " version " + projectVersion
+ ", flow file " + flowFileName + " version " + flowVersion, e);
}
return file;
}
@Override
public int getLatestFlowVersion(final int projectId, final int projectVersion,
final String flowName) throws ProjectManagerException {
final IntHandler handler = new IntHandler();
try {
return this.dbOperator.query(IntHandler.SELECT_LATEST_FLOW_VERSION, handler, projectId,
projectVersion, flowName);
} catch (final SQLException e) {
logger.error(e);
throw new ProjectManagerException(
"Error selecting latest flow version from project " + projectId + ", version " +
projectVersion + ", flow " + flowName + ".", e);
}
}
@Override
public boolean isFlowFileUploaded(final int projectId, final int projectVersion)
throws ProjectManagerException {
final FlowFileResultHandler handler = new FlowFileResultHandler();
final List<byte[]> data;
try {
data = this.dbOperator
.query(FlowFileResultHandler.SELECT_ALL_FLOW_FILES, handler,
projectId, projectVersion);
} catch (final SQLException e) {
logger.error(e);
throw new ProjectManagerException("Failed to query uploaded flow files ", e);
}
return !data.isEmpty();
}
}
| 1 | 17,053 | it's not just fetching override properties here, right? | azkaban-azkaban | java |
@@ -200,6 +200,7 @@ func (acsSession *session) Start() error {
if shouldReconnectWithoutBackoff(acsError) {
// If ACS closed the connection, there's no need to backoff,
// reconnect immediately
+ seelog.Info("ACS Websocket connection closed for a valid reason")
acsSession.backoff.Reset()
sendEmptyMessageOnChannel(connectToACS)
} else { | 1 | // Copyright 2014-2017 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 handler deals with appropriately reacting to all ACS messages as well
// as maintaining the connection to ACS.
package handler
import (
"io"
"net/url"
"strconv"
"strings"
"time"
"golang.org/x/net/context"
acsclient "github.com/aws/amazon-ecs-agent/agent/acs/client"
"github.com/aws/amazon-ecs-agent/agent/acs/model/ecsacs"
"github.com/aws/amazon-ecs-agent/agent/acs/update_handler"
"github.com/aws/amazon-ecs-agent/agent/api"
"github.com/aws/amazon-ecs-agent/agent/config"
rolecredentials "github.com/aws/amazon-ecs-agent/agent/credentials"
"github.com/aws/amazon-ecs-agent/agent/engine"
"github.com/aws/amazon-ecs-agent/agent/eventhandler"
"github.com/aws/amazon-ecs-agent/agent/eventstream"
"github.com/aws/amazon-ecs-agent/agent/statemanager"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/aws/amazon-ecs-agent/agent/utils/ttime"
"github.com/aws/amazon-ecs-agent/agent/version"
"github.com/aws/amazon-ecs-agent/agent/wsclient"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/cihub/seelog"
)
const (
// heartbeatTimeout is the maximum time to wait between heartbeats
// without disconnecting
heartbeatTimeout = 1 * time.Minute
heartbeatJitter = 1 * time.Minute
inactiveInstanceReconnectDelay = 1 * time.Hour
connectionBackoffMin = 250 * time.Millisecond
connectionBackoffMax = 2 * time.Minute
connectionBackoffJitter = 0.2
connectionBackoffMultiplier = 1.5
// payloadMessageBufferSize is the maximum number of payload messages
// to queue up without having handled previous ones.
payloadMessageBufferSize = 10
// sendCredentialsURLParameterName is the name of the URL parameter
// in the ACS URL that is used to indicate if ACS should send
// credentials for all tasks on establishing the connection
sendCredentialsURLParameterName = "sendCredentials"
inactiveInstanceExceptionPrefix = "InactiveInstanceException:"
)
// Session defines an interface for handler's long-lived connection with ACS.
type Session interface {
Start() error
}
// session encapsulates all arguments needed by the handler to connect to ACS
// and to handle messages recieved by ACS. The Session.Start() method can be used
// to start processing messages from ACS.
type session struct {
containerInstanceARN string
credentialsProvider *credentials.Credentials
agentConfig *config.Config
deregisterInstanceEventStream *eventstream.EventStream
taskEngine engine.TaskEngine
ecsClient api.ECSClient
stateManager statemanager.StateManager
credentialsManager rolecredentials.Manager
taskHandler *eventhandler.TaskHandler
ctx context.Context
cancel context.CancelFunc
backoff utils.Backoff
resources sessionResources
_heartbeatTimeout time.Duration
_heartbeatJitter time.Duration
_inactiveInstanceReconnectDelay time.Duration
}
// sessionResources defines the resource creator interface for starting
// a session with ACS. This interface is intended to define methods
// that create resources used to establish the connection to ACS
// It is confined to just the createACSClient() method for now. It can be
// extended to include the acsWsURL() and newDisconnectionTimer() methods
// when needed
// The goal is to make it easier to test and inject dependencies
type sessionResources interface {
// createACSClient creates a new websocket client
createACSClient(url string, cfg *config.Config) wsclient.ClientServer
sessionState
}
// acsSessionResources implements resource creator and session state interfaces
// to create resources needed to connect to ACS and to record session state
// for the same
type acsSessionResources struct {
credentialsProvider *credentials.Credentials
// sendCredentials is used to set the 'sendCredentials' URL parameter
// used to connect to ACS
// It is set to 'true' for the very first successful connection on
// agent start. It is set to false for all successive connections
sendCredentials bool
}
// sessionState defines state recorder interface for the
// session established with ACS. It can be used to record and
// retrieve data shared across multiple connections to ACS
type sessionState interface {
// connectedToACS callback indicates that the client has
// connected to ACS
connectedToACS()
// getSendCredentialsURLParameter retrieves the value for
// the 'sendCredentials' URL parameter
getSendCredentialsURLParameter() string
}
// NewSession creates a new Session object
func NewSession(ctx context.Context,
config *config.Config,
deregisterInstanceEventStream *eventstream.EventStream,
containerInstanceArn string,
credentialsProvider *credentials.Credentials,
ecsClient api.ECSClient,
stateManager statemanager.StateManager,
taskEngine engine.TaskEngine,
credentialsManager rolecredentials.Manager,
taskHandler *eventhandler.TaskHandler) Session {
resources := newSessionResources(credentialsProvider)
backoff := utils.NewSimpleBackoff(connectionBackoffMin, connectionBackoffMax,
connectionBackoffJitter, connectionBackoffMultiplier)
derivedContext, cancel := context.WithCancel(ctx)
return &session{
agentConfig: config,
deregisterInstanceEventStream: deregisterInstanceEventStream,
containerInstanceARN: containerInstanceArn,
credentialsProvider: credentialsProvider,
ecsClient: ecsClient,
stateManager: stateManager,
taskEngine: taskEngine,
credentialsManager: credentialsManager,
taskHandler: taskHandler,
ctx: derivedContext,
cancel: cancel,
backoff: backoff,
resources: resources,
_heartbeatTimeout: heartbeatTimeout,
_heartbeatJitter: heartbeatJitter,
_inactiveInstanceReconnectDelay: inactiveInstanceReconnectDelay,
}
}
// Start starts the session. It'll forever keep trying to connect to ACS unless
// the context is cancelled.
//
// If the context is cancelled, Start() would return with the error code returned
// by the context.
// If the instance is deregistered, Start() would emit an event to the
// deregister-instance event stream and sets the connection backoff time to 1 hour.
func (acsSession *session) Start() error {
// connectToACS channel is used to inidcate the intent to connect to ACS
// It's processed by the select loop to connect to ACS
connectToACS := make(chan struct{})
// This is required to trigger the first connection to ACS. Subsequent
// connections are triggered by the handleACSError() method
go func() {
connectToACS <- struct{}{}
}()
for {
select {
case <-connectToACS:
seelog.Debugf("Received connect to ACS message")
// Start a session with ACS
acsError := acsSession.startSessionOnce()
// Session with ACS was stopped with some error, start processing the error
isInactiveInstance := isInactiveInstanceError(acsError)
if isInactiveInstance {
// If the instance was deregistered, send an event to the event stream
// for the same
seelog.Debug("Container instance is deregistered, notifying listeners")
err := acsSession.deregisterInstanceEventStream.WriteToEventStream(struct{}{})
if err != nil {
seelog.Debugf("Failed to write to deregister container instance event stream, err: %v", err)
}
}
if shouldReconnectWithoutBackoff(acsError) {
// If ACS closed the connection, there's no need to backoff,
// reconnect immediately
acsSession.backoff.Reset()
sendEmptyMessageOnChannel(connectToACS)
} else {
// Disconnected unexpectedly from ACS, compute backoff duration to
// reconnect
reconnectDelay := acsSession.computeReconnectDelay(isInactiveInstance)
seelog.Debugf("Reconnecting to ACS in: %v", reconnectDelay)
waitComplete := acsSession.waitForDuration(reconnectDelay)
if waitComplete {
// If the context was not cancelled and we've waited for the
// wait duration without any errors, send the message to the channel
// to reconnect to ACS
sendEmptyMessageOnChannel(connectToACS)
} else {
// Wait was interrupted. We expect the session to close as canelling
// the session context is the only way to end up here. Print a message
// to indicate the same
seelog.Info("Interrupted waiting for reconnect delay to elapse; Expect session to close")
}
}
case <-acsSession.ctx.Done():
seelog.Debugf("context done")
return acsSession.ctx.Err()
}
}
}
// startSessionOnce creates a session with ACS and handles requests using the passed
// in arguments
func (acsSession *session) startSessionOnce() error {
acsEndpoint, err := acsSession.ecsClient.DiscoverPollEndpoint(acsSession.containerInstanceARN)
if err != nil {
seelog.Errorf("Unable to discover poll endpoint, err: %v", err)
return err
}
url := acsWsURL(acsEndpoint, acsSession.agentConfig.Cluster, acsSession.containerInstanceARN, acsSession.taskEngine, acsSession.resources)
client := acsSession.resources.createACSClient(url, acsSession.agentConfig)
defer client.Close()
// Start inactivity timer for closing the connection
timer := newDisconnectionTimer(client, acsSession.heartbeatTimeout(), acsSession.heartbeatJitter())
defer timer.Stop()
return acsSession.startACSSession(client, timer)
}
// startACSSession starts a session with ACS. It adds request handlers for various
// kinds of messages expected from ACS. It returns on server disconnection or when
// the context is cancelled
func (acsSession *session) startACSSession(client wsclient.ClientServer, timer ttime.Timer) error {
// Any message from the server resets the disconnect timeout
client.SetAnyRequestHandler(anyMessageHandler(timer))
cfg := acsSession.agentConfig
refreshCredsHandler := newRefreshCredentialsHandler(acsSession.ctx, cfg.Cluster, acsSession.containerInstanceARN,
client, acsSession.credentialsManager, acsSession.taskEngine)
defer refreshCredsHandler.clearAcks()
refreshCredsHandler.start()
defer refreshCredsHandler.stop()
client.AddRequestHandler(refreshCredsHandler.handlerFunc())
// Add request handler for handling payload messages from ACS
payloadHandler := newPayloadRequestHandler(
acsSession.ctx,
acsSession.taskEngine,
acsSession.ecsClient,
cfg.Cluster,
acsSession.containerInstanceARN,
client,
acsSession.stateManager,
refreshCredsHandler,
acsSession.credentialsManager,
acsSession.taskHandler)
// Clear the acks channel on return because acks of messageids don't have any value across sessions
defer payloadHandler.clearAcks()
payloadHandler.start()
defer payloadHandler.stop()
client.AddRequestHandler(payloadHandler.handlerFunc())
// Ignore heartbeat messages; anyMessageHandler gets 'em
client.AddRequestHandler(func(*ecsacs.HeartbeatMessage) {})
updater.AddAgentUpdateHandlers(client, cfg, acsSession.stateManager, acsSession.taskEngine)
err := client.Connect()
if err != nil {
seelog.Errorf("Error connecting to ACS: %v", err)
return err
}
acsSession.resources.connectedToACS()
backoffResetTimer := time.AfterFunc(
utils.AddJitter(acsSession.heartbeatTimeout(), acsSession.heartbeatJitter()), func() {
// If we do not have an error connecting and remain connected for at
// least 1 or so minutes, reset the backoff. This prevents disconnect
// errors that only happen infrequently from damaging the
// reconnectability as significantly.
acsSession.backoff.Reset()
})
defer backoffResetTimer.Stop()
serveErr := make(chan error, 1)
go func() {
serveErr <- client.Serve()
}()
for {
select {
case <-acsSession.ctx.Done():
// Stop receiving and sending messages from and to ACS when
// the context received from the main function is canceled
return acsSession.ctx.Err()
case err := <-serveErr:
// Stop receiving and sending messages from and to ACS when
// client.Serve returns an error. This can happen when the
// the connection is closed by ACS or the agent
return err
}
}
}
func (acsSession *session) computeReconnectDelay(isInactiveInstance bool) time.Duration {
if isInactiveInstance {
return acsSession._inactiveInstanceReconnectDelay
}
return acsSession.backoff.Duration()
}
// waitForDuration waits for the specified duration of time. If the wait is interrupted,
// it returns a false value. Else, it returns true, indicating completion of wait time.
func (acsSession *session) waitForDuration(delay time.Duration) bool {
reconnectTimer := time.NewTimer(delay)
select {
case <-reconnectTimer.C:
return true
case <-acsSession.ctx.Done():
reconnectTimer.Stop()
return false
}
}
func (acsSession *session) heartbeatTimeout() time.Duration {
return acsSession._heartbeatTimeout
}
func (acsSession *session) heartbeatJitter() time.Duration {
return acsSession._heartbeatJitter
}
// createACSClient creates the ACS Client using the specified URL
func (acsResources *acsSessionResources) createACSClient(url string, cfg *config.Config) wsclient.ClientServer {
return acsclient.New(url, cfg, acsResources.credentialsProvider)
}
// connectedToACS records a successful connection to ACS
// It sets sendCredentials to false on such an event
func (acsResources *acsSessionResources) connectedToACS() {
acsResources.sendCredentials = false
}
// getSendCredentialsURLParameter gets the value to be set for the
// 'sendCredentials' URL parameter
func (acsResources *acsSessionResources) getSendCredentialsURLParameter() string {
return strconv.FormatBool(acsResources.sendCredentials)
}
func newSessionResources(credentialsProvider *credentials.Credentials) sessionResources {
return &acsSessionResources{
credentialsProvider: credentialsProvider,
sendCredentials: true,
}
}
// acsWsURL returns the websocket url for ACS given the endpoint
func acsWsURL(endpoint, cluster, containerInstanceArn string, taskEngine engine.TaskEngine, acsSessionState sessionState) string {
acsUrl := endpoint
if endpoint[len(endpoint)-1] != '/' {
acsUrl += "/"
}
acsUrl += "ws"
query := url.Values{}
query.Set("clusterArn", cluster)
query.Set("containerInstanceArn", containerInstanceArn)
query.Set("agentHash", version.GitHashString())
query.Set("agentVersion", version.Version)
query.Set("seqNum", "1")
if dockerVersion, err := taskEngine.Version(); err == nil {
query.Set("dockerVersion", "DockerVersion: "+dockerVersion)
}
query.Set(sendCredentialsURLParameterName, acsSessionState.getSendCredentialsURLParameter())
return acsUrl + "?" + query.Encode()
}
// newDisconnectionTimer creates a new time object, with a callback to
// disconnect from ACS on inactivity
func newDisconnectionTimer(client wsclient.ClientServer, timeout time.Duration, jitter time.Duration) ttime.Timer {
timer := time.AfterFunc(utils.AddJitter(timeout, jitter), func() {
seelog.Warn("ACS Connection hasn't had any activity for too long; closing connection")
closeErr := client.Close()
if closeErr != nil {
seelog.Warnf("Error disconnecting: %v", closeErr)
}
})
return timer
}
// anyMessageHandler handles any server message. Any server message means the
// connection is active and thus the heartbeat disconnect should not occur
func anyMessageHandler(timer ttime.Timer) func(interface{}) {
return func(interface{}) {
seelog.Debug("ACS activity occured")
timer.Reset(utils.AddJitter(heartbeatTimeout, heartbeatJitter))
}
}
func shouldReconnectWithoutBackoff(acsError error) bool {
return acsError == nil || acsError == io.EOF
}
func isInactiveInstanceError(acsError error) bool {
return acsError != nil && strings.HasPrefix(acsError.Error(), inactiveInstanceExceptionPrefix)
}
// sendEmptyMessageOnChannel sends an empty message using a go-routine on the
// sepcified channel
func sendEmptyMessageOnChannel(channel chan<- struct{}) {
go func() {
channel <- struct{}{}
}()
}
| 1 | 17,034 | Is it worth logging the error? | aws-amazon-ecs-agent | go |
@@ -16,6 +16,19 @@ import watchdog.events
from watchdog.observers import polling
+class NS:
+ def __init__(self, ns):
+ self.__dict__["ns"] = ns
+
+ def __getattr__(self, key):
+ if key not in self.ns:
+ raise AttributeError("No such element: %s", key)
+ return self.ns[key]
+
+ def __setattr__(self, key, value):
+ self.__dict__["ns"][key] = value
+
+
def parse_command(command):
"""
Returns a (path, args) tuple. | 1 | from __future__ import absolute_import, print_function, division
import contextlib
import os
import shlex
import sys
import threading
import traceback
from mitmproxy import exceptions
from mitmproxy import controller
from mitmproxy import ctx
import watchdog.events
from watchdog.observers import polling
def parse_command(command):
"""
Returns a (path, args) tuple.
"""
if not command or not command.strip():
raise exceptions.AddonError("Empty script command.")
# Windows: escape all backslashes in the path.
if os.name == "nt": # pragma: no cover
backslashes = shlex.split(command, posix=False)[0].count("\\")
command = command.replace("\\", "\\\\", backslashes)
args = shlex.split(command) # pragma: no cover
args[0] = os.path.expanduser(args[0])
if not os.path.exists(args[0]):
raise exceptions.AddonError(
("Script file not found: %s.\r\n"
"If your script path contains spaces, "
"make sure to wrap it in additional quotes, e.g. -s \"'./foo bar/baz.py' --args\".") %
args[0])
elif os.path.isdir(args[0]):
raise exceptions.AddonError("Not a file: %s" % args[0])
return args[0], args[1:]
@contextlib.contextmanager
def scriptenv(path, args):
oldargs = sys.argv
sys.argv = [path] + args
script_dir = os.path.dirname(os.path.abspath(path))
sys.path.append(script_dir)
try:
yield
except Exception:
_, _, tb = sys.exc_info()
scriptdir = os.path.dirname(os.path.abspath(path))
for i, s in enumerate(reversed(traceback.extract_tb(tb))):
tb = tb.tb_next
if not os.path.abspath(s[0]).startswith(scriptdir):
break
ctx.log.error("Script error: %s" % "".join(traceback.format_tb(tb)))
finally:
sys.argv = oldargs
sys.path.pop()
def load_script(path, args):
with open(path, "rb") as f:
try:
code = compile(f.read(), path, 'exec')
except SyntaxError as e:
ctx.log.error(
"Script error: %s line %s: %s" % (
e.filename, e.lineno, e.msg
)
)
return
ns = {'__file__': os.path.abspath(path)}
with scriptenv(path, args):
exec(code, ns, ns)
return ns
class ReloadHandler(watchdog.events.FileSystemEventHandler):
def __init__(self, callback):
self.callback = callback
def on_modified(self, event):
self.callback()
def on_created(self, event):
self.callback()
class Script:
"""
An addon that manages a single script.
"""
def __init__(self, command):
self.name = command
self.command = command
self.path, self.args = parse_command(command)
self.ns = None
self.observer = None
self.dead = False
self.last_options = None
self.should_reload = threading.Event()
for i in controller.Events:
if not hasattr(self, i):
def mkprox():
evt = i
def prox(*args, **kwargs):
self.run(evt, *args, **kwargs)
return prox
setattr(self, i, mkprox())
def run(self, name, *args, **kwargs):
# It's possible for ns to be un-initialised if we failed during
# configure
if self.ns is not None and not self.dead:
func = self.ns.get(name)
if func:
with scriptenv(self.path, self.args):
func(*args, **kwargs)
def reload(self):
self.should_reload.set()
def tick(self):
if self.should_reload.is_set():
self.should_reload.clear()
ctx.log.info("Reloading script: %s" % self.name)
self.ns = load_script(self.path, self.args)
self.start()
self.configure(self.last_options)
else:
self.run("tick")
def start(self):
self.ns = load_script(self.path, self.args)
self.run("start")
def configure(self, options):
self.last_options = options
if not self.observer:
self.observer = polling.PollingObserver()
# Bind the handler to the real underlying master object
self.observer.schedule(
ReloadHandler(self.reload),
os.path.dirname(self.path) or "."
)
self.observer.start()
self.run("configure", options)
def done(self):
self.run("done")
self.dead = True
class ScriptLoader():
"""
An addon that manages loading scripts from options.
"""
def configure(self, options):
for s in options.scripts:
if options.scripts.count(s) > 1:
raise exceptions.OptionsError("Duplicate script: %s" % s)
for a in ctx.master.addons.chain[:]:
if isinstance(a, Script) and a.name not in options.scripts:
ctx.log.info("Un-loading script: %s" % a.name)
ctx.master.addons.remove(a)
current = {}
for a in ctx.master.addons.chain[:]:
if isinstance(a, Script):
current[a.name] = a
ctx.master.addons.chain.remove(a)
for s in options.scripts:
if s in current:
ctx.master.addons.chain.append(current[s])
else:
ctx.log.info("Loading script: %s" % s)
sc = Script(s)
ctx.master.addons.add(sc)
| 1 | 11,997 | What's the point of this class? | mitmproxy-mitmproxy | py |
@@ -411,7 +411,7 @@ import template from './libraryoptionseditor.template.html';
parent.querySelector('.chkEnableEmbeddedEpisodeInfosContainer').classList.add('hide');
}
- parent.querySelector('.chkAutomaticallyAddToCollectionContainer').classList.toggle('hide', contentType !== 'movies');
+ parent.querySelector('.chkAutomaticallyAddToCollectionContainer').classList.toggle('hide', contentType !== 'movies' && contentType !== 'mixed');
return populateMetadataSettings(parent, contentType);
} | 1 | /* eslint-disable indent */
/**
* Module for library options editor.
* @module components/libraryoptionseditor/libraryoptionseditor
*/
import globalize from '../../scripts/globalize';
import dom from '../../scripts/dom';
import '../../elements/emby-checkbox/emby-checkbox';
import '../../elements/emby-select/emby-select';
import '../../elements/emby-input/emby-input';
import template from './libraryoptionseditor.template.html';
function populateLanguages(parent) {
return ApiClient.getCultures().then(languages => {
populateLanguagesIntoSelect(parent.querySelector('#selectLanguage'), languages);
populateLanguagesIntoList(parent.querySelector('.subtitleDownloadLanguages'), languages);
});
}
function populateLanguagesIntoSelect(select, languages) {
let html = '';
html += "<option value=''></option>";
for (let i = 0; i < languages.length; i++) {
const culture = languages[i];
html += `<option value='${culture.TwoLetterISOLanguageName}'>${culture.DisplayName}</option>`;
}
select.innerHTML = html;
}
function populateLanguagesIntoList(element, languages) {
let html = '';
for (let i = 0; i < languages.length; i++) {
const culture = languages[i];
html += `<label><input type="checkbox" is="emby-checkbox" class="chkSubtitleLanguage" data-lang="${culture.ThreeLetterISOLanguageName.toLowerCase()}" /><span>${culture.DisplayName}</span></label>`;
}
element.innerHTML = html;
}
function populateCountries(select) {
return ApiClient.getCountries().then(allCountries => {
let html = '';
html += "<option value=''></option>";
for (let i = 0; i < allCountries.length; i++) {
const culture = allCountries[i];
html += `<option value='${culture.TwoLetterISORegionName}'>${culture.DisplayName}</option>`;
}
select.innerHTML = html;
});
}
function populateRefreshInterval(select) {
let html = '';
html += `<option value='0'>${globalize.translate('Never')}</option>`;
html += [30, 60, 90].map(val => {
return `<option value='${val}'>${globalize.translate('EveryNDays', val)}</option>`;
}).join('');
select.innerHTML = html;
}
function renderMetadataReaders(page, plugins) {
let html = '';
const elem = page.querySelector('.metadataReaders');
if (plugins.length < 1) return elem.innerHTML = '', elem.classList.add('hide'), !1;
html += `<h3 class="checkboxListLabel">${globalize.translate('LabelMetadataReaders')}</h3>`;
html += '<div class="checkboxList paperList checkboxList-paperList">';
for (let i = 0; i < plugins.length; i++) {
const plugin = plugins[i];
html += `<div class="listItem localReaderOption sortableOption" data-pluginname="${plugin.Name}">`;
html += '<span class="listItemIcon material-icons live_tv"></span>';
html += '<div class="listItemBody">';
html += '<h3 class="listItemBodyText">';
html += plugin.Name;
html += '</h3>';
html += '</div>';
if (i > 0) {
html += `<button type="button" is="paper-icon-button-light" title="${globalize.translate('Up')}" class="btnSortableMoveUp btnSortable" data-pluginindex="${i}"><span class="material-icons keyboard_arrow_up"></span></button>`;
} else if (plugins.length > 1) {
html += `<button type="button" is="paper-icon-button-light" title="${globalize.translate('Down')}" class="btnSortableMoveDown btnSortable" data-pluginindex="${i}"><span class="material-icons keyboard_arrow_down"></span></button>`;
}
html += '</div>';
}
html += '</div>';
html += `<div class="fieldDescription">${globalize.translate('LabelMetadataReadersHelp')}</div>`;
if (plugins.length < 2) {
elem.classList.add('hide');
} else {
elem.classList.remove('hide');
}
elem.innerHTML = html;
return true;
}
function renderMetadataSavers(page, metadataSavers) {
let html = '';
const elem = page.querySelector('.metadataSavers');
if (!metadataSavers.length) return elem.innerHTML = '', elem.classList.add('hide'), false;
html += `<h3 class="checkboxListLabel">${globalize.translate('LabelMetadataSavers')}</h3>`;
html += '<div class="checkboxList paperList checkboxList-paperList">';
for (let i = 0; i < metadataSavers.length; i++) {
const plugin = metadataSavers[i];
html += `<label><input type="checkbox" data-defaultenabled="${plugin.DefaultEnabled}" is="emby-checkbox" class="chkMetadataSaver" data-pluginname="${plugin.Name}" ${false}><span>${plugin.Name}</span></label>`;
}
html += '</div>';
html += `<div class="fieldDescription" style="margin-top:.25em;">${globalize.translate('LabelMetadataSaversHelp')}</div>`;
elem.innerHTML = html;
elem.classList.remove('hide');
return true;
}
function getMetadataFetchersForTypeHtml(availableTypeOptions, libraryOptionsForType) {
let html = '';
let plugins = availableTypeOptions.MetadataFetchers;
plugins = getOrderedPlugins(plugins, libraryOptionsForType.MetadataFetcherOrder || []);
if (!plugins.length) return html;
html += '<div class="metadataFetcher" data-type="' + availableTypeOptions.Type + '">';
html += '<h3 class="checkboxListLabel">' + globalize.translate('LabelTypeMetadataDownloaders', globalize.translate('TypeOptionPlural' + availableTypeOptions.Type)) + '</h3>';
html += '<div class="checkboxList paperList checkboxList-paperList">';
plugins.forEach((plugin, index) => {
html += '<div class="listItem metadataFetcherItem sortableOption" data-pluginname="' + plugin.Name + '">';
const isChecked = libraryOptionsForType.MetadataFetchers ? libraryOptionsForType.MetadataFetchers.includes(plugin.Name) : plugin.DefaultEnabled;
const checkedHtml = isChecked ? ' checked="checked"' : '';
html += '<label class="listItemCheckboxContainer"><input type="checkbox" is="emby-checkbox" class="chkMetadataFetcher" data-pluginname="' + plugin.Name + '" ' + checkedHtml + '><span></span></label>';
html += '<div class="listItemBody">';
html += '<h3 class="listItemBodyText">';
html += plugin.Name;
html += '</h3>';
html += '</div>';
if (index > 0) {
html += '<button type="button" is="paper-icon-button-light" title="' + globalize.translate('Up') + '" class="btnSortableMoveUp btnSortable" data-pluginindex="' + index + '"><span class="material-icons keyboard_arrow_up"></span></button>';
} else if (plugins.length > 1) {
html += '<button type="button" is="paper-icon-button-light" title="' + globalize.translate('Down') + '" class="btnSortableMoveDown btnSortable" data-pluginindex="' + index + '"><span class="material-icons keyboard_arrow_down"></span></button>';
}
html += '</div>';
});
html += '</div>';
html += '<div class="fieldDescription">' + globalize.translate('LabelMetadataDownloadersHelp') + '</div>';
html += '</div>';
return html;
}
function getTypeOptions(allOptions, type) {
const allTypeOptions = allOptions.TypeOptions || [];
for (let i = 0; i < allTypeOptions.length; i++) {
const typeOptions = allTypeOptions[i];
if (typeOptions.Type === type) return typeOptions;
}
return null;
}
function renderMetadataFetchers(page, availableOptions, libraryOptions) {
let html = '';
const elem = page.querySelector('.metadataFetchers');
for (let i = 0; i < availableOptions.TypeOptions.length; i++) {
const availableTypeOptions = availableOptions.TypeOptions[i];
html += getMetadataFetchersForTypeHtml(availableTypeOptions, getTypeOptions(libraryOptions, availableTypeOptions.Type) || {});
}
elem.innerHTML = html;
if (html) {
elem.classList.remove('hide');
page.querySelector('.fldAutoRefreshInterval').classList.remove('hide');
page.querySelector('.fldMetadataLanguage').classList.remove('hide');
page.querySelector('.fldMetadataCountry').classList.remove('hide');
} else {
elem.classList.add('hide');
page.querySelector('.fldAutoRefreshInterval').classList.add('hide');
page.querySelector('.fldMetadataLanguage').classList.add('hide');
page.querySelector('.fldMetadataCountry').classList.add('hide');
}
return true;
}
function renderSubtitleFetchers(page, availableOptions, libraryOptions) {
let html = '';
const elem = page.querySelector('.subtitleFetchers');
let plugins = availableOptions.SubtitleFetchers;
plugins = getOrderedPlugins(plugins, libraryOptions.SubtitleFetcherOrder || []);
if (!plugins.length) return html;
html += `<h3 class="checkboxListLabel">${globalize.translate('LabelSubtitleDownloaders')}</h3>`;
html += '<div class="checkboxList paperList checkboxList-paperList">';
for (let i = 0; i < plugins.length; i++) {
const plugin = plugins[i];
html += `<div class="listItem subtitleFetcherItem sortableOption" data-pluginname="${plugin.Name}">`;
const isChecked = libraryOptions.DisabledSubtitleFetchers ? !libraryOptions.DisabledSubtitleFetchers.includes(plugin.Name) : plugin.DefaultEnabled;
const checkedHtml = isChecked ? ' checked="checked"' : '';
html += `<label class="listItemCheckboxContainer"><input type="checkbox" is="emby-checkbox" class="chkSubtitleFetcher" data-pluginname="${plugin.Name}" ${checkedHtml}><span></span></label>`;
html += '<div class="listItemBody">';
html += '<h3 class="listItemBodyText">';
html += plugin.Name;
html += '</h3>';
html += '</div>';
if (i > 0) {
html += `<button type="button" is="paper-icon-button-light" title="${globalize.translate('Up')}" class="btnSortableMoveUp btnSortable" data-pluginindex="${i}"><span class="material-icons keyboard_arrow_up"></span></button>`;
} else if (plugins.length > 1) {
html += `<button type="button" is="paper-icon-button-light" title="${globalize.translate('Down')}" class="btnSortableMoveDown btnSortable" data-pluginindex="${i}"><span class="material-icons keyboard_arrow_down"></span></button>`;
}
html += '</div>';
}
html += '</div>';
html += `<div class="fieldDescription">${globalize.translate('SubtitleDownloadersHelp')}</div>`;
elem.innerHTML = html;
}
function getImageFetchersForTypeHtml(availableTypeOptions, libraryOptionsForType) {
let html = '';
let plugins = availableTypeOptions.ImageFetchers;
plugins = getOrderedPlugins(plugins, libraryOptionsForType.ImageFetcherOrder || []);
if (!plugins.length) return html;
html += '<div class="imageFetcher" data-type="' + availableTypeOptions.Type + '">';
html += '<div class="flex align-items-center" style="margin:1.5em 0 .5em;">';
html += '<h3 class="checkboxListLabel" style="margin:0;">' + globalize.translate('HeaderTypeImageFetchers', globalize.translate('TypeOptionPlural' + availableTypeOptions.Type)) + '</h3>';
const supportedImageTypes = availableTypeOptions.SupportedImageTypes || [];
if (supportedImageTypes.length > 1 || supportedImageTypes.length === 1 && supportedImageTypes[0] !== 'Primary') {
html += '<button is="emby-button" class="raised btnImageOptionsForType" type="button" style="margin-left:1.5em;font-size:90%;"><span>' + globalize.translate('HeaderFetcherSettings') + '</span></button>';
}
html += '</div>';
html += '<div class="checkboxList paperList checkboxList-paperList">';
for (let i = 0; i < plugins.length; i++) {
const plugin = plugins[i];
html += '<div class="listItem imageFetcherItem sortableOption" data-pluginname="' + plugin.Name + '">';
const isChecked = libraryOptionsForType.ImageFetchers ? libraryOptionsForType.ImageFetchers.includes(plugin.Name) : plugin.DefaultEnabled;
const checkedHtml = isChecked ? ' checked="checked"' : '';
html += '<label class="listItemCheckboxContainer"><input type="checkbox" is="emby-checkbox" class="chkImageFetcher" data-pluginname="' + plugin.Name + '" ' + checkedHtml + '><span></span></label>';
html += '<div class="listItemBody">';
html += '<h3 class="listItemBodyText">';
html += plugin.Name;
html += '</h3>';
html += '</div>';
if (i > 0) {
html += '<button type="button" is="paper-icon-button-light" title="' + globalize.translate('Up') + '" class="btnSortableMoveUp btnSortable" data-pluginindex="' + i + '"><span class="material-icons keyboard_arrow_up"></span></button>';
} else if (plugins.length > 1) {
html += '<button type="button" is="paper-icon-button-light" title="' + globalize.translate('Down') + '" class="btnSortableMoveDown btnSortable" data-pluginindex="' + i + '"><span class="material-icons keyboard_arrow_down"></span></button>';
}
html += '</div>';
}
html += '</div>';
html += '<div class="fieldDescription">' + globalize.translate('LabelImageFetchersHelp') + '</div>';
html += '</div>';
return html;
}
function renderImageFetchers(page, availableOptions, libraryOptions) {
let html = '';
const elem = page.querySelector('.imageFetchers');
for (let i = 0; i < availableOptions.TypeOptions.length; i++) {
const availableTypeOptions = availableOptions.TypeOptions[i];
html += getImageFetchersForTypeHtml(availableTypeOptions, getTypeOptions(libraryOptions, availableTypeOptions.Type) || {});
}
elem.innerHTML = html;
if (html) {
elem.classList.remove('hide');
page.querySelector('.chkSaveLocalContainer').classList.remove('hide');
} else {
elem.classList.add('hide');
page.querySelector('.chkSaveLocalContainer').classList.add('hide');
}
return true;
}
function populateMetadataSettings(parent, contentType) {
const isNewLibrary = parent.classList.contains('newlibrary');
return ApiClient.getJSON(ApiClient.getUrl('Libraries/AvailableOptions', {
LibraryContentType: contentType,
IsNewLibrary: isNewLibrary
})).then(availableOptions => {
currentAvailableOptions = availableOptions;
parent.availableOptions = availableOptions;
renderMetadataSavers(parent, availableOptions.MetadataSavers);
renderMetadataReaders(parent, availableOptions.MetadataReaders);
renderMetadataFetchers(parent, availableOptions, {});
renderSubtitleFetchers(parent, availableOptions, {});
renderImageFetchers(parent, availableOptions, {});
availableOptions.SubtitleFetchers.length ? parent.querySelector('.subtitleDownloadSettings').classList.remove('hide') : parent.querySelector('.subtitleDownloadSettings').classList.add('hide');
}).catch(() => {
return Promise.resolve();
});
}
function adjustSortableListElement(elem) {
const btnSortable = elem.querySelector('.btnSortable');
const inner = btnSortable.querySelector('.material-icons');
if (elem.previousSibling) {
btnSortable.title = globalize.translate('Up');
btnSortable.classList.add('btnSortableMoveUp');
btnSortable.classList.remove('btnSortableMoveDown');
inner.classList.remove('keyboard_arrow_down');
inner.classList.add('keyboard_arrow_up');
} else {
btnSortable.title = globalize.translate('Down');
btnSortable.classList.remove('btnSortableMoveUp');
btnSortable.classList.add('btnSortableMoveDown');
inner.classList.remove('keyboard_arrow_up');
inner.classList.add('keyboard_arrow_down');
}
}
function showImageOptionsForType(type) {
import('../imageOptionsEditor/imageOptionsEditor').then(({default: ImageOptionsEditor}) => {
let typeOptions = getTypeOptions(currentLibraryOptions, type);
if (!typeOptions) {
typeOptions = {
Type: type
};
currentLibraryOptions.TypeOptions.push(typeOptions);
}
const availableOptions = getTypeOptions(currentAvailableOptions || {}, type);
const imageOptionsEditor = new ImageOptionsEditor();
imageOptionsEditor.show(type, typeOptions, availableOptions);
});
}
function onImageFetchersContainerClick(e) {
const btnImageOptionsForType = dom.parentWithClass(e.target, 'btnImageOptionsForType');
if (btnImageOptionsForType) {
return void showImageOptionsForType(dom.parentWithClass(btnImageOptionsForType, 'imageFetcher').getAttribute('data-type'));
}
onSortableContainerClick.call(this, e);
}
function onSortableContainerClick(e) {
const btnSortable = dom.parentWithClass(e.target, 'btnSortable');
if (btnSortable) {
const li = dom.parentWithClass(btnSortable, 'sortableOption');
const list = dom.parentWithClass(li, 'paperList');
if (btnSortable.classList.contains('btnSortableMoveDown')) {
const next = li.nextSibling;
if (next) {
li.parentNode.removeChild(li);
next.parentNode.insertBefore(li, next.nextSibling);
}
} else {
const prev = li.previousSibling;
if (prev) {
li.parentNode.removeChild(li);
prev.parentNode.insertBefore(li, prev);
}
}
Array.prototype.forEach.call(list.querySelectorAll('.sortableOption'), adjustSortableListElement);
}
}
function bindEvents(parent) {
parent.querySelector('.metadataReaders').addEventListener('click', onSortableContainerClick);
parent.querySelector('.subtitleFetchers').addEventListener('click', onSortableContainerClick);
parent.querySelector('.metadataFetchers').addEventListener('click', onSortableContainerClick);
parent.querySelector('.imageFetchers').addEventListener('click', onImageFetchersContainerClick);
}
export async function embed(parent, contentType, libraryOptions) {
currentLibraryOptions = {
TypeOptions: []
};
currentAvailableOptions = null;
const isNewLibrary = libraryOptions === null;
isNewLibrary && parent.classList.add('newlibrary');
parent.innerHTML = globalize.translateHtml(template);
populateRefreshInterval(parent.querySelector('#selectAutoRefreshInterval'));
const promises = [populateLanguages(parent), populateCountries(parent.querySelector('#selectCountry'))];
Promise.all(promises).then(function() {
return setContentType(parent, contentType).then(function() {
libraryOptions && setLibraryOptions(parent, libraryOptions);
bindEvents(parent);
return;
});
});
}
export function setContentType(parent, contentType) {
if (contentType === 'homevideos' || contentType === 'photos') {
parent.querySelector('.chkEnablePhotosContainer').classList.remove('hide');
} else {
parent.querySelector('.chkEnablePhotosContainer').classList.add('hide');
}
if (contentType !== 'tvshows' && contentType !== 'movies' && contentType !== 'homevideos' && contentType !== 'musicvideos' && contentType !== 'mixed') {
parent.querySelector('.chapterSettingsSection').classList.add('hide');
} else {
parent.querySelector('.chapterSettingsSection').classList.remove('hide');
}
if (contentType === 'tvshows') {
parent.querySelector('.chkAutomaticallyGroupSeriesContainer').classList.remove('hide');
parent.querySelector('.fldSeasonZeroDisplayName').classList.remove('hide');
parent.querySelector('#txtSeasonZeroName').setAttribute('required', 'required');
} else {
parent.querySelector('.chkAutomaticallyGroupSeriesContainer').classList.add('hide');
parent.querySelector('.fldSeasonZeroDisplayName').classList.add('hide');
parent.querySelector('#txtSeasonZeroName').removeAttribute('required');
}
if (contentType === 'books' || contentType === 'boxsets' || contentType === 'playlists' || contentType === 'music') {
parent.querySelector('.chkEnableEmbeddedTitlesContainer').classList.add('hide');
} else {
parent.querySelector('.chkEnableEmbeddedTitlesContainer').classList.remove('hide');
}
if (contentType === 'tvshows') {
parent.querySelector('.chkEnableEmbeddedEpisodeInfosContainer').classList.remove('hide');
} else {
parent.querySelector('.chkEnableEmbeddedEpisodeInfosContainer').classList.add('hide');
}
parent.querySelector('.chkAutomaticallyAddToCollectionContainer').classList.toggle('hide', contentType !== 'movies');
return populateMetadataSettings(parent, contentType);
}
function setSubtitleFetchersIntoOptions(parent, options) {
options.DisabledSubtitleFetchers = Array.prototype.map.call(Array.prototype.filter.call(parent.querySelectorAll('.chkSubtitleFetcher'), elem => {
return !elem.checked;
}), elem => {
return elem.getAttribute('data-pluginname');
});
options.SubtitleFetcherOrder = Array.prototype.map.call(parent.querySelectorAll('.subtitleFetcherItem'), elem => {
return elem.getAttribute('data-pluginname');
});
}
function setMetadataFetchersIntoOptions(parent, options) {
const sections = parent.querySelectorAll('.metadataFetcher');
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const type = section.getAttribute('data-type');
let typeOptions = getTypeOptions(options, type);
if (!typeOptions) {
typeOptions = {
Type: type
};
options.TypeOptions.push(typeOptions);
}
typeOptions.MetadataFetchers = Array.prototype.map.call(Array.prototype.filter.call(section.querySelectorAll('.chkMetadataFetcher'), elem => {
return elem.checked;
}), elem => {
return elem.getAttribute('data-pluginname');
});
typeOptions.MetadataFetcherOrder = Array.prototype.map.call(section.querySelectorAll('.metadataFetcherItem'), elem => {
return elem.getAttribute('data-pluginname');
});
}
}
function setImageFetchersIntoOptions(parent, options) {
const sections = parent.querySelectorAll('.imageFetcher');
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const type = section.getAttribute('data-type');
let typeOptions = getTypeOptions(options, type);
if (!typeOptions) {
typeOptions = {
Type: type
};
options.TypeOptions.push(typeOptions);
}
typeOptions.ImageFetchers = Array.prototype.map.call(Array.prototype.filter.call(section.querySelectorAll('.chkImageFetcher'), elem => {
return elem.checked;
}), elem => {
return elem.getAttribute('data-pluginname');
});
typeOptions.ImageFetcherOrder = Array.prototype.map.call(section.querySelectorAll('.imageFetcherItem'), elem => {
return elem.getAttribute('data-pluginname');
});
}
}
function setImageOptionsIntoOptions(options) {
const originalTypeOptions = (currentLibraryOptions || {}).TypeOptions || [];
for (let i = 0; i < originalTypeOptions.length; i++) {
const originalTypeOption = originalTypeOptions[i];
let typeOptions = getTypeOptions(options, originalTypeOption.Type);
if (!typeOptions) {
typeOptions = {
Type: originalTypeOption.Type
};
options.TypeOptions.push(typeOptions);
}
originalTypeOption.ImageOptions && (typeOptions.ImageOptions = originalTypeOption.ImageOptions);
}
}
export function getLibraryOptions(parent) {
const options = {
EnableArchiveMediaFiles: false,
EnablePhotos: parent.querySelector('.chkEnablePhotos').checked,
EnableRealtimeMonitor: parent.querySelector('.chkEnableRealtimeMonitor').checked,
ExtractChapterImagesDuringLibraryScan: parent.querySelector('.chkExtractChaptersDuringLibraryScan').checked,
EnableChapterImageExtraction: parent.querySelector('.chkExtractChapterImages').checked,
EnableInternetProviders: true,
SaveLocalMetadata: parent.querySelector('#chkSaveLocal').checked,
EnableAutomaticSeriesGrouping: parent.querySelector('.chkAutomaticallyGroupSeries').checked,
PreferredMetadataLanguage: parent.querySelector('#selectLanguage').value,
MetadataCountryCode: parent.querySelector('#selectCountry').value,
SeasonZeroDisplayName: parent.querySelector('#txtSeasonZeroName').value,
AutomaticRefreshIntervalDays: parseInt(parent.querySelector('#selectAutoRefreshInterval').value),
EnableEmbeddedTitles: parent.querySelector('#chkEnableEmbeddedTitles').checked,
EnableEmbeddedEpisodeInfos: parent.querySelector('#chkEnableEmbeddedEpisodeInfos').checked,
SkipSubtitlesIfEmbeddedSubtitlesPresent: parent.querySelector('#chkSkipIfGraphicalSubsPresent').checked,
SkipSubtitlesIfAudioTrackMatches: parent.querySelector('#chkSkipIfAudioTrackPresent').checked,
SaveSubtitlesWithMedia: parent.querySelector('#chkSaveSubtitlesLocally').checked,
RequirePerfectSubtitleMatch: parent.querySelector('#chkRequirePerfectMatch').checked,
AutomaticallyAddToCollection: parent.querySelector('#chkAutomaticallyAddToCollection').checked,
MetadataSavers: Array.prototype.map.call(Array.prototype.filter.call(parent.querySelectorAll('.chkMetadataSaver'), elem => {
return elem.checked;
}), elem => {
return elem.getAttribute('data-pluginname');
}),
TypeOptions: []
};
options.LocalMetadataReaderOrder = Array.prototype.map.call(parent.querySelectorAll('.localReaderOption'), elem => {
return elem.getAttribute('data-pluginname');
});
options.SubtitleDownloadLanguages = Array.prototype.map.call(Array.prototype.filter.call(parent.querySelectorAll('.chkSubtitleLanguage'), elem => {
return elem.checked;
}), elem => {
return elem.getAttribute('data-lang');
});
setSubtitleFetchersIntoOptions(parent, options);
setMetadataFetchersIntoOptions(parent, options);
setImageFetchersIntoOptions(parent, options);
setImageOptionsIntoOptions(options);
return options;
}
function getOrderedPlugins(plugins, configuredOrder) {
plugins = plugins.slice(0);
plugins.sort((a, b) => {
return a = configuredOrder.indexOf(a.Name), b = configuredOrder.indexOf(b.Name), a < b ? -1 : a > b ? 1 : 0;
});
return plugins;
}
export function setLibraryOptions(parent, options) {
currentLibraryOptions = options;
currentAvailableOptions = parent.availableOptions;
parent.querySelector('#selectLanguage').value = options.PreferredMetadataLanguage || '';
parent.querySelector('#selectCountry').value = options.MetadataCountryCode || '';
parent.querySelector('#selectAutoRefreshInterval').value = options.AutomaticRefreshIntervalDays || '0';
parent.querySelector('#txtSeasonZeroName').value = options.SeasonZeroDisplayName || 'Specials';
parent.querySelector('.chkEnablePhotos').checked = options.EnablePhotos;
parent.querySelector('.chkEnableRealtimeMonitor').checked = options.EnableRealtimeMonitor;
parent.querySelector('.chkExtractChaptersDuringLibraryScan').checked = options.ExtractChapterImagesDuringLibraryScan;
parent.querySelector('.chkExtractChapterImages').checked = options.EnableChapterImageExtraction;
parent.querySelector('#chkSaveLocal').checked = options.SaveLocalMetadata;
parent.querySelector('.chkAutomaticallyGroupSeries').checked = options.EnableAutomaticSeriesGrouping;
parent.querySelector('#chkEnableEmbeddedTitles').checked = options.EnableEmbeddedTitles;
parent.querySelector('#chkEnableEmbeddedEpisodeInfos').checked = options.EnableEmbeddedEpisodeInfos;
parent.querySelector('#chkSkipIfGraphicalSubsPresent').checked = options.SkipSubtitlesIfEmbeddedSubtitlesPresent;
parent.querySelector('#chkSaveSubtitlesLocally').checked = options.SaveSubtitlesWithMedia;
parent.querySelector('#chkSkipIfAudioTrackPresent').checked = options.SkipSubtitlesIfAudioTrackMatches;
parent.querySelector('#chkRequirePerfectMatch').checked = options.RequirePerfectSubtitleMatch;
parent.querySelector('#chkAutomaticallyAddToCollection').checked = options.AutomaticallyAddToCollection;
Array.prototype.forEach.call(parent.querySelectorAll('.chkMetadataSaver'), elem => {
elem.checked = options.MetadataSavers ? options.MetadataSavers.includes(elem.getAttribute('data-pluginname')) : elem.getAttribute('data-defaultenabled') === 'true';
});
Array.prototype.forEach.call(parent.querySelectorAll('.chkSubtitleLanguage'), elem => {
elem.checked = !!options.SubtitleDownloadLanguages && options.SubtitleDownloadLanguages.includes(elem.getAttribute('data-lang'));
});
renderMetadataReaders(parent, getOrderedPlugins(parent.availableOptions.MetadataReaders, options.LocalMetadataReaderOrder || []));
renderMetadataFetchers(parent, parent.availableOptions, options);
renderImageFetchers(parent, parent.availableOptions, options);
renderSubtitleFetchers(parent, parent.availableOptions, options);
}
let currentLibraryOptions;
let currentAvailableOptions;
/* eslint-enable indent */
export default {
embed: embed,
setContentType: setContentType,
getLibraryOptions: getLibraryOptions,
setLibraryOptions: setLibraryOptions
};
| 1 | 20,188 | I'm being picky here, but I think I would prefer `toggle` to be kept here and just change the condition to `contentType !== 'movies' && contentType !== 'mixed'` or `!['movies', 'mixed'].includes(contentType)`. | jellyfin-jellyfin-web | js |
@@ -7,6 +7,9 @@ package libkbfs
import (
"encoding/json"
"fmt"
+ "github.com/syndtr/goleveldb/leveldb"
+ "os"
+ sysPath "path"
"sort"
"strings"
"sync" | 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 (
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfsblock"
"github.com/keybase/kbfs/kbfscrypto"
"github.com/keybase/kbfs/kbfsmd"
"github.com/keybase/kbfs/kbfssync"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// CtxCRTagKey is the type used for unique context tags related to
// conflict resolution
type CtxCRTagKey int
const (
// CtxCRIDKey is the type of the tag for unique operation IDs
// related to conflict resolution
CtxCRIDKey CtxCRTagKey = iota
// If the number of outstanding unmerged revisions that need to be
// resolved together is greater than this number, then block
// unmerged writes to make sure we don't get *too* unmerged.
// TODO: throttle unmerged writes before resorting to complete
// blockage.
crMaxRevsThresholdDefault = 500
// How long we're allowed to block writes for if we exceed the max
// revisions threshold.
crMaxWriteLockTime = 10 * time.Second
)
// CtxCROpID is the display name for the unique operation
// conflict resolution ID tag.
const CtxCROpID = "CRID"
type conflictInput struct {
unmerged kbfsmd.Revision
merged kbfsmd.Revision
}
// ConflictResolver is responsible for resolving conflicts in the
// background.
type ConflictResolver struct {
config Config
fbo *folderBranchOps
prepper folderUpdatePrepper
log traceLogger
deferLog traceLogger
maxRevsThreshold int
inputChanLock sync.RWMutex
inputChan chan conflictInput
// resolveGroup tracks the outstanding resolves.
resolveGroup kbfssync.RepeatedWaitGroup
inputLock sync.Mutex
currInput conflictInput
currCancel context.CancelFunc
lockNextTime bool
canceledCount int
}
// NewConflictResolver constructs a new ConflictResolver (and launches
// any necessary background goroutines).
func NewConflictResolver(
config Config, fbo *folderBranchOps) *ConflictResolver {
// make a logger with an appropriate module name
branchSuffix := ""
if fbo.branch() != MasterBranch {
branchSuffix = " " + string(fbo.branch())
}
tlfStringFull := fbo.id().String()
log := config.MakeLogger(fmt.Sprintf("CR %s%s", tlfStringFull[:8],
branchSuffix))
cr := &ConflictResolver{
config: config,
fbo: fbo,
prepper: folderUpdatePrepper{
config: config,
folderBranch: fbo.folderBranch,
blocks: &fbo.blocks,
log: log,
},
log: traceLogger{log},
deferLog: traceLogger{log.CloneWithAddedDepth(1)},
maxRevsThreshold: crMaxRevsThresholdDefault,
currInput: conflictInput{
unmerged: kbfsmd.RevisionUninitialized,
merged: kbfsmd.RevisionUninitialized,
},
}
if fbo.bType == standard && config.Mode().ConflictResolutionEnabled() {
cr.startProcessing(BackgroundContextWithCancellationDelayer())
}
return cr
}
func (cr *ConflictResolver) startProcessing(baseCtx context.Context) {
cr.inputChanLock.Lock()
defer cr.inputChanLock.Unlock()
if cr.inputChan != nil {
return
}
cr.inputChan = make(chan conflictInput)
go cr.processInput(baseCtx, cr.inputChan)
}
func (cr *ConflictResolver) stopProcessing() {
cr.inputChanLock.Lock()
defer cr.inputChanLock.Unlock()
if cr.inputChan == nil {
return
}
close(cr.inputChan)
cr.inputChan = nil
}
// cancelExistingLocked must be called while holding cr.inputLock.
func (cr *ConflictResolver) cancelExistingLocked(ci conflictInput) bool {
// The input is only interesting if one of the revisions is
// greater than what we've looked at to date.
if ci.unmerged <= cr.currInput.unmerged &&
ci.merged <= cr.currInput.merged {
return false
}
if cr.currCancel != nil {
cr.currCancel()
}
return true
}
// ForceCancel cancels any currently-running CR, regardless of what
// its inputs were.
func (cr *ConflictResolver) ForceCancel() {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
if cr.currCancel != nil {
cr.currCancel()
}
}
// processInput processes conflict resolution jobs from the given
// channel until it is closed. This function uses a parameter for the
// channel instead of accessing cr.inputChan directly so that it
// doesn't have to hold inputChanLock.
func (cr *ConflictResolver) processInput(baseCtx context.Context,
inputChan <-chan conflictInput) {
// Start off with a closed prevCRDone, so that the first CR call
// doesn't have to wait.
prevCRDone := make(chan struct{})
close(prevCRDone)
defer func() {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
if cr.currCancel != nil {
cr.currCancel()
}
CleanupCancellationDelayer(baseCtx)
}()
for ci := range inputChan {
ctx := CtxWithRandomIDReplayable(baseCtx, CtxCRIDKey, CtxCROpID, cr.log)
valid := func() bool {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
valid := cr.cancelExistingLocked(ci)
if !valid {
return false
}
cr.log.CDebugf(ctx, "New conflict input %v following old "+
"input %v", ci, cr.currInput)
cr.currInput = ci
ctx, cr.currCancel = context.WithCancel(ctx)
return true
}()
if !valid {
cr.log.CDebugf(ctx, "Ignoring uninteresting input: %v", ci)
cr.resolveGroup.Done()
continue
}
waitChan := prevCRDone
prevCRDone = make(chan struct{}) // closed when doResolve finishes
go func(ci conflictInput, done chan<- struct{}) {
defer cr.resolveGroup.Done()
defer close(done)
// Wait for the previous CR without blocking any
// Resolve callers, as that could result in deadlock
// (KBFS-1001).
select {
case <-waitChan:
case <-ctx.Done():
cr.log.CDebugf(ctx, "Resolution canceled before starting")
return
}
cr.doResolve(ctx, ci)
}(ci, prevCRDone)
}
}
// Resolve takes the latest known unmerged and merged revision
// numbers, and kicks off the resolution process.
func (cr *ConflictResolver) Resolve(ctx context.Context,
unmerged kbfsmd.Revision, merged kbfsmd.Revision) {
cr.inputChanLock.RLock()
defer cr.inputChanLock.RUnlock()
// CR can end up trying to cancel itself via the SyncAll call, so
// prevent that from happening.
if crOpID := ctx.Value(CtxCRIDKey); crOpID != nil {
cr.log.CDebugf(ctx, "Ignoring self-resolve during CR")
return
}
if cr.inputChan == nil {
return
}
ci := conflictInput{unmerged, merged}
func() {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
// Cancel any running CR before we return, so the caller can be
// confident any ongoing CR superseded by this new input will be
// canceled before it releases any locks it holds.
//
// TODO: return early if this returns false, and log something
// using a newly-pass-in context.
_ = cr.cancelExistingLocked(ci)
}()
cr.resolveGroup.Add(1)
cr.inputChan <- ci
}
// Wait blocks until the current set of submitted resolutions are
// complete (though not necessarily successful), or until the given
// context is canceled.
func (cr *ConflictResolver) Wait(ctx context.Context) error {
return cr.resolveGroup.Wait(ctx)
}
// Shutdown cancels any ongoing resolutions and stops any background
// goroutines.
func (cr *ConflictResolver) Shutdown() {
cr.stopProcessing()
}
// Pause cancels any ongoing resolutions and prevents any new ones from
// starting.
func (cr *ConflictResolver) Pause() {
cr.stopProcessing()
}
// Restart re-enables conflict resolution, with a base context for CR
// operations. baseCtx must have a cancellation delayer.
func (cr *ConflictResolver) Restart(baseCtx context.Context) {
cr.startProcessing(baseCtx)
}
// BeginNewBranch resets any internal state to be ready to accept
// resolutions from a new branch.
func (cr *ConflictResolver) BeginNewBranch() {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
// Reset the curr input so we don't ignore a future CR
// request that uses the same revision number (i.e.,
// because the previous CR failed to flush due to a
// conflict).
cr.currInput = conflictInput{}
}
func (cr *ConflictResolver) checkDone(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return nil
}
}
func (cr *ConflictResolver) getMDs(ctx context.Context, lState *lockState,
writerLocked bool) (unmerged []ImmutableRootMetadata,
merged []ImmutableRootMetadata, err error) {
// First get all outstanding unmerged MDs for this device.
var branchPoint kbfsmd.Revision
if writerLocked {
branchPoint, unmerged, err =
cr.fbo.getUnmergedMDUpdatesLocked(ctx, lState)
} else {
branchPoint, unmerged, err =
cr.fbo.getUnmergedMDUpdates(ctx, lState)
}
if err != nil {
return nil, nil, err
}
if len(unmerged) > 0 && unmerged[0].BID() == kbfsmd.PendingLocalSquashBranchID {
cr.log.CDebugf(ctx, "Squashing local branch")
return unmerged, nil, nil
}
// Now get all the merged MDs, starting from after the branch
// point. We fetch the branch point (if possible) to make sure
// it's the right predecessor of the unmerged branch. TODO: stop
// fetching the branch point and remove the successor check below
// once we fix KBFS-1664.
fetchFrom := branchPoint + 1
if branchPoint >= kbfsmd.RevisionInitial {
fetchFrom = branchPoint
}
merged, err = getMergedMDUpdates(
ctx, cr.fbo.config, cr.fbo.id(), fetchFrom, nil)
if err != nil {
return nil, nil, err
}
if len(unmerged) > 0 {
err := merged[0].CheckValidSuccessor(
merged[0].mdID, unmerged[0].ReadOnly())
if err != nil {
cr.log.CDebugf(ctx, "Branch point (rev=%d, mdID=%s) is not a "+
"valid successor for unmerged rev %d (mdID=%s, bid=%s)",
merged[0].Revision(), merged[0].mdID, unmerged[0].Revision(),
unmerged[0].mdID, unmerged[0].BID())
return nil, nil, err
}
}
// Remove branch point.
if len(merged) > 0 && fetchFrom == branchPoint {
merged = merged[1:]
}
return unmerged, merged, nil
}
// updateCurrInput assumes that both unmerged and merged are
// non-empty.
func (cr *ConflictResolver) updateCurrInput(ctx context.Context,
unmerged, merged []ImmutableRootMetadata) (err error) {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
// check done while holding the lock, so we know for sure if
// we've already been canceled and replaced by a new input.
err = cr.checkDone(ctx)
if err != nil {
return err
}
prevInput := cr.currInput
defer func() {
// reset the currInput if we get an error below
if err != nil {
cr.currInput = prevInput
}
}()
rev := unmerged[len(unmerged)-1].bareMd.RevisionNumber()
if rev < cr.currInput.unmerged {
return fmt.Errorf("Unmerged revision %d is lower than the "+
"expected unmerged revision %d", rev, cr.currInput.unmerged)
}
cr.currInput.unmerged = rev
if len(merged) > 0 {
rev = merged[len(merged)-1].bareMd.RevisionNumber()
if rev < cr.currInput.merged {
return fmt.Errorf("Merged revision %d is lower than the "+
"expected merged revision %d", rev, cr.currInput.merged)
}
} else {
rev = kbfsmd.RevisionUninitialized
}
cr.currInput.merged = rev
// Take the lock right away next time if either there are lots of
// unmerged revisions, or this is a local squash and we won't
// block for very long.
//
// TODO: if there are a lot of merged revisions, and they keep
// coming, we might consider doing a "partial" resolution, writing
// the result back to the unmerged branch (basically "rebasing"
// it). See KBFS-1896.
if (len(unmerged) > cr.maxRevsThreshold) ||
(len(unmerged) > 0 && unmerged[0].BID() == kbfsmd.PendingLocalSquashBranchID) {
cr.lockNextTime = true
}
return nil
}
func (cr *ConflictResolver) makeChains(ctx context.Context,
unmerged, merged []ImmutableRootMetadata) (
unmergedChains, mergedChains *crChains, err error) {
unmergedChains, err = newCRChainsForIRMDs(
ctx, cr.config.Codec(), unmerged, &cr.fbo.blocks, true)
if err != nil {
return nil, nil, err
}
// Make sure we don't try to unref any blocks that have already
// been GC'd in the merged branch.
for _, md := range merged {
for _, op := range md.data.Changes.Ops {
_, isGCOp := op.(*GCOp)
if !isGCOp {
continue
}
for _, ptr := range op.Unrefs() {
unmergedChains.doNotUnrefPointers[ptr] = true
}
}
}
// If there are no new merged changes, don't make any merged
// chains.
if len(merged) == 0 {
return unmergedChains, newCRChainsEmpty(), nil
}
mergedChains, err = newCRChainsForIRMDs(
ctx, cr.config.Codec(), merged, &cr.fbo.blocks, true)
if err != nil {
return nil, nil, err
}
// Make the chain summaries. Identify using the unmerged chains,
// since those are most likely to be able to identify a node in
// the cache.
unmergedSummary := unmergedChains.summary(unmergedChains, cr.fbo.nodeCache)
mergedSummary := mergedChains.summary(unmergedChains, cr.fbo.nodeCache)
// Ignore CR summaries for pending local squashes.
if len(unmerged) == 0 || unmerged[0].BID() != kbfsmd.PendingLocalSquashBranchID {
cr.fbo.status.setCRSummary(unmergedSummary, mergedSummary)
}
return unmergedChains, mergedChains, nil
}
// A helper class that implements sort.Interface to sort paths by
// descending path length.
type crSortedPaths []path
// Len implements sort.Interface for crSortedPaths
func (sp crSortedPaths) Len() int {
return len(sp)
}
// Less implements sort.Interface for crSortedPaths
func (sp crSortedPaths) Less(i, j int) bool {
return len(sp[i].path) > len(sp[j].path)
}
// Swap implements sort.Interface for crSortedPaths
func (sp crSortedPaths) Swap(i, j int) {
sp[j], sp[i] = sp[i], sp[j]
}
func createdFileWithConflictingWrite(unmergedChains, mergedChains *crChains,
unmergedOriginal, mergedOriginal BlockPointer) bool {
mergedChain := mergedChains.byOriginal[mergedOriginal]
unmergedChain := unmergedChains.byOriginal[unmergedOriginal]
if mergedChain == nil || unmergedChain == nil {
return false
}
unmergedWriteRange := unmergedChain.getCollapsedWriteRange()
mergedWriteRange := mergedChain.getCollapsedWriteRange()
// Are they exactly equivalent?
if writeRangesEquivalent(unmergedWriteRange, mergedWriteRange) {
unmergedChain.removeSyncOps()
return false
}
// If the unmerged one is just a truncate, we can safely ignore
// the unmerged chain.
if len(unmergedWriteRange) == 1 && unmergedWriteRange[0].isTruncate() &&
unmergedWriteRange[0].Off == 0 {
unmergedChain.removeSyncOps()
return false
}
// If the merged one is just a truncate, we can safely ignore
// the merged chain.
if len(mergedWriteRange) == 1 && mergedWriteRange[0].isTruncate() &&
mergedWriteRange[0].Off == 0 {
mergedChain.removeSyncOps()
return false
}
return true
}
// createdFileWithNonzeroSizes checks two possibly-conflicting
// createOps and returns true if the corresponding file has non-zero
// directory entry sizes in both the unmerged and merged branch. We
// need to check this sometimes, because a call to
// `createdFileWithConflictingWrite` might not have access to syncOps
// that have been resolved away in a previous iteration. See
// KBFS-2825 for details.
func (cr *ConflictResolver) createdFileWithNonzeroSizes(
ctx context.Context, unmergedChains, mergedChains *crChains,
unmergedChain *crChain, mergedChain *crChain,
unmergedCop, mergedCop *createOp) (bool, error) {
lState := makeFBOLockState()
// The pointers on the ops' final paths aren't necessarily filled
// in, so construct our own partial paths using the chain
// pointers, which are enough to satisfy `GetEntry`.
mergedPath := path{
FolderBranch: mergedCop.getFinalPath().FolderBranch,
path: []pathNode{
{mergedChain.mostRecent, ""},
{zeroPtr, mergedCop.NewName},
},
}
kmd := mergedChains.mostRecentChainMDInfo
mergedEntry, err := cr.fbo.blocks.GetEntry(ctx, lState, kmd, mergedPath)
if _, noExists := errors.Cause(err).(NoSuchNameError); noExists {
return false, nil
} else if err != nil {
return false, err
}
kmd = unmergedChains.mostRecentChainMDInfo
unmergedPath := path{
FolderBranch: mergedCop.getFinalPath().FolderBranch,
path: []pathNode{
{unmergedChain.mostRecent, ""},
{zeroPtr, mergedCop.NewName},
},
}
unmergedEntry, err := cr.fbo.blocks.GetEntry(ctx, lState, kmd, unmergedPath)
if _, noExists := errors.Cause(err).(NoSuchNameError); noExists {
return false, nil
} else if err != nil {
return false, err
}
if mergedEntry.Size > 0 && unmergedEntry.Size > 0 {
cr.log.CDebugf(ctx,
"Not merging files named %s with non-zero sizes "+
"(merged=%d unmerged=%d)",
unmergedCop.NewName, mergedEntry.Size, unmergedEntry.Size)
return true, nil
}
return false, nil
}
// checkPathForMerge checks whether the given unmerged chain and path
// contains any newly-created subdirectories that were created
// simultaneously in the merged branch as well. If so, it recursively
// checks that directory as well. It returns a slice of any new
// unmerged paths that need to be checked for conflicts later in
// conflict resolution, for all subdirectories of the given path.
func (cr *ConflictResolver) checkPathForMerge(ctx context.Context,
unmergedChain *crChain, unmergedPath path,
unmergedChains, mergedChains *crChains) ([]path, error) {
mergedChain, ok := mergedChains.byOriginal[unmergedChain.original]
if !ok {
// No corresponding merged chain means we don't have to merge
// any directories.
return nil, nil
}
// Find instances of the same directory being created in both
// branches. Only merge completely new directories -- anything
// involving a rename will result in a conflict for now.
//
// TODO: have a better merge strategy for renamed directories!
mergedCreates := make(map[string]*createOp)
for _, op := range mergedChain.ops {
cop, ok := op.(*createOp)
if !ok || len(cop.Refs()) == 0 || cop.renamed {
continue
}
mergedCreates[cop.NewName] = cop
}
if len(mergedCreates) == 0 {
return nil, nil
}
var newUnmergedPaths []path
toDrop := make(map[int]bool)
for i, op := range unmergedChain.ops {
cop, ok := op.(*createOp)
if !ok || len(cop.Refs()) == 0 || cop.renamed {
continue
}
// Is there a corresponding merged create with the same type?
mergedCop, ok := mergedCreates[cop.NewName]
if !ok || mergedCop.Type != cop.Type {
continue
}
unmergedOriginal := cop.Refs()[0]
mergedOriginal := mergedCop.Refs()[0]
if cop.Type != Dir {
// Only merge files if they don't both have writes.
// Double-check the directory blocks to see if the files
// have non-zero sizes, because an earlier resolution
// might have collapsed all the sync ops away.
if createdFileWithConflictingWrite(unmergedChains, mergedChains,
unmergedOriginal, mergedOriginal) {
continue
}
conflicts, err := cr.createdFileWithNonzeroSizes(
ctx, unmergedChains, mergedChains, unmergedChain, mergedChain,
cop, mergedCop)
if err != nil {
return nil, err
}
if conflicts {
continue
}
}
toDrop[i] = true
cr.log.CDebugf(ctx, "Merging name %s (%s) in %v (unmerged original %v "+
"changed to %v)", cop.NewName, cop.Type, unmergedChain.mostRecent,
unmergedOriginal, mergedOriginal)
// Change the original to match the merged original, so we can
// check for conflicts later. Note that the most recent will
// stay the same, so we can still match the unmerged path
// correctly.
err := unmergedChains.changeOriginal(unmergedOriginal, mergedOriginal)
if _, notFound := errors.Cause(err).(NoChainFoundError); notFound {
unmergedChains.toUnrefPointers[unmergedOriginal] = true
continue
} else if err != nil {
return nil, err
} else if unmergedOriginal == mergedOriginal {
cr.log.CDebugf(ctx,
"Treating self-conflicting directory like a normal conflict")
}
unmergedChain, ok := unmergedChains.byOriginal[mergedOriginal]
if !ok {
return nil, fmt.Errorf("Change original (%v -> %v) didn't work",
unmergedOriginal, mergedOriginal)
}
newPath := unmergedPath.ChildPath(cop.NewName, unmergedChain.mostRecent)
if cop.Type == Dir {
// recurse for this chain
newPaths, err := cr.checkPathForMerge(ctx, unmergedChain, newPath,
unmergedChains, mergedChains)
if err != nil {
return nil, err
}
// Add any further subdirectories that need merging under this
// subdirectory.
newUnmergedPaths = append(newUnmergedPaths, newPaths...)
} else {
// Set the path for all child ops
unrefedOrig := false
for _, op := range unmergedChain.ops {
op.setFinalPath(newPath)
_, isSyncOp := op.(*syncOp)
// If a later write overwrites the original, take it
// out of the unmerged created list so it can be
// properly unreferenced.
if !unrefedOrig && isSyncOp {
unrefedOrig = true
delete(unmergedChains.createdOriginals, mergedOriginal)
}
}
}
// Then add this create's path.
newUnmergedPaths = append(newUnmergedPaths, newPath)
}
// Remove the unneeded create ops
if len(toDrop) > 0 {
newOps := make([]op, 0, len(unmergedChain.ops)-len(toDrop))
for i, op := range unmergedChain.ops {
if toDrop[i] {
cr.log.CDebugf(ctx,
"Dropping double create unmerged operation: %s", op)
} else {
newOps = append(newOps, op)
}
}
unmergedChain.ops = newOps
}
return newUnmergedPaths, nil
}
// findCreatedDirsToMerge finds directories that were created in both
// the unmerged and merged branches, and resets the original unmerged
// pointer to match the original merged pointer. It returns a slice of
// new unmerged paths that need to be combined with the unmergedPaths
// slice.
func (cr *ConflictResolver) findCreatedDirsToMerge(ctx context.Context,
unmergedPaths []path, unmergedChains, mergedChains *crChains) (
[]path, error) {
var newUnmergedPaths []path
for _, unmergedPath := range unmergedPaths {
unmergedChain, ok :=
unmergedChains.byMostRecent[unmergedPath.tailPointer()]
if !ok {
return nil, fmt.Errorf("findCreatedDirsToMerge: No unmerged chain "+
"for most recent %v", unmergedPath.tailPointer())
}
newPaths, err := cr.checkPathForMerge(ctx, unmergedChain, unmergedPath,
unmergedChains, mergedChains)
if err != nil {
return nil, err
}
newUnmergedPaths = append(newUnmergedPaths, newPaths...)
}
return newUnmergedPaths, nil
}
type createMapKey struct {
ptr BlockPointer
name string
}
// addChildBlocksIfIndirectFile adds refblocks for all child blocks of
// the given file. It will return an error if called with a pointer
// that doesn't represent a file.
func (cr *ConflictResolver) addChildBlocksIfIndirectFile(ctx context.Context,
lState *lockState, unmergedChains *crChains, currPath path, op op) error {
// For files with indirect pointers, add all child blocks
// as refblocks for the re-created file.
infos, err := cr.fbo.blocks.GetIndirectFileBlockInfos(
ctx, lState, unmergedChains.mostRecentChainMDInfo, currPath)
if err != nil {
return err
}
if len(infos) > 0 {
cr.log.CDebugf(ctx, "Adding child pointers for recreated "+
"file %s", currPath)
for _, info := range infos {
op.AddRefBlock(info.BlockPointer)
}
}
return nil
}
// resolvedMergedPathTail takes an unmerged path, and returns as much
// of the tail-end of the corresponding merged path that it can, using
// only information within the chains. It may not be able to return a
// complete chain if, for example, a directory was changed in the
// unmerged branch but not in the merged branch, and so the merged
// chain would not have enough information to construct the merged
// branch completely. This function returns the partial path, as well
// as the most recent pointer to the first changed node in the merged
// chains (which can be subsequently used to find the beginning of the
// merged path).
//
// The given unmerged path should be for a node that wasn't created
// during the unmerged branch.
//
// It is also possible for directories used in the unmerged path to
// have been completely removed from the merged path. In this case,
// they need to be recreated. So this function also returns a slice
// of create ops that will need to be replayed in the merged branch
// for the conflicts to be resolved; all of these ops have their
// writer info set to the given one.
func (cr *ConflictResolver) resolveMergedPathTail(ctx context.Context,
lState *lockState, unmergedPath path,
unmergedChains, mergedChains *crChains,
currUnmergedWriterInfo writerInfo) (
path, BlockPointer, []*createOp, error) {
unmergedOriginal, err :=
unmergedChains.originalFromMostRecent(unmergedPath.tailPointer())
if err != nil {
cr.log.CDebugf(ctx, "Couldn't find original pointer for %v",
unmergedPath.tailPointer())
return path{}, BlockPointer{}, nil, err
}
var recreateOps []*createOp // fill in backwards, and reverse at the end
currOriginal := unmergedOriginal
currPath := unmergedPath
mergedPath := path{
FolderBranch: unmergedPath.FolderBranch,
path: nil, // fill in backwards, and reverse at the end
}
// First find the earliest merged parent.
for mergedChains.isDeleted(currOriginal) {
cr.log.CDebugf(ctx, "%v was deleted in the merged branch (%s)",
currOriginal, currPath)
if !currPath.hasValidParent() {
return path{}, BlockPointer{}, nil,
fmt.Errorf("Couldn't find valid merged parent path for %v",
unmergedOriginal)
}
// If this node has been deleted, we need to search
// backwards in the path to find the latest node that
// hasn't been deleted and re-recreate nodes upward from
// there.
name := currPath.tailName()
mergedPath.path = append(mergedPath.path, pathNode{
BlockPointer: currOriginal,
Name: name,
})
parentPath := *currPath.parentPath()
parentOriginal, err :=
unmergedChains.originalFromMostRecent(parentPath.tailPointer())
if err != nil {
cr.log.CDebugf(ctx, "Couldn't find original pointer for %v",
parentPath.tailPointer())
return path{}, BlockPointer{}, nil, err
}
// Drop the merged rmOp since we're recreating it, and we
// don't want to replay that notification locally.
if mergedChain, ok := mergedChains.byOriginal[parentOriginal]; ok {
mergedMostRecent, err :=
mergedChains.mostRecentFromOriginalOrSame(currOriginal)
if err != nil {
return path{}, BlockPointer{}, nil, err
}
outer:
for i, op := range mergedChain.ops {
ro, ok := op.(*rmOp)
if !ok {
continue
}
// Use the unref'd pointer, and not the name, to identify
// the operation, since renames might have happened on the
// merged branch.
for _, unref := range ro.Unrefs() {
if unref != mergedMostRecent {
continue
}
mergedChain.ops =
append(mergedChain.ops[:i], mergedChain.ops[i+1:]...)
break outer
}
}
} else {
// If there's no chain, then likely a previous resolution
// removed an entire directory tree, and so the individual
// rm operations aren't listed. In that case, there's no
// rm op to remove.
cr.log.CDebugf(ctx, "No corresponding merged chain for parent "+
"%v; skipping rm removal", parentOriginal)
}
de, err := cr.fbo.blocks.GetEntry(
ctx, lState, unmergedChains.mostRecentChainMDInfo, currPath)
if err != nil {
return path{}, BlockPointer{}, nil, err
}
co, err := newCreateOp(name, parentOriginal, de.Type)
if err != nil {
return path{}, BlockPointer{}, nil, err
}
co.AddSelfUpdate(parentOriginal)
co.setFinalPath(parentPath)
co.AddRefBlock(currOriginal)
co.setWriterInfo(currUnmergedWriterInfo)
if co.Type != Dir {
err = cr.addChildBlocksIfIndirectFile(ctx, lState,
unmergedChains, currPath, co)
if err != nil {
return path{}, BlockPointer{}, nil, err
}
// Delete any sync/setattr ops on the removed, merged file.
if mergedChain, ok := mergedChains.byOriginal[currOriginal]; ok {
mergedChains.removeChain(mergedChain.mostRecent)
}
}
// If this happens to have been renamed on the unmerged
// branch, drop the rm half of the rename operation; just
// leave it as a create.
if ri, ok := unmergedChains.renamedOriginals[currOriginal]; ok {
oldParent, ok := unmergedChains.byOriginal[ri.originalOldParent]
if !ok {
cr.log.CDebugf(ctx, "Couldn't find chain for original "+
"old parent: %v", ri.originalOldParent)
return path{}, BlockPointer{}, nil,
errors.WithStack(NoChainFoundError{ri.originalOldParent})
}
for _, op := range oldParent.ops {
ro, ok := op.(*rmOp)
if !ok {
continue
}
if ro.OldName == ri.oldName {
ro.dropThis = true
break
}
}
// Replace the create op with the new recreate op,
// which contains the proper refblock.
newParent, ok := unmergedChains.byOriginal[ri.originalNewParent]
if !ok {
cr.log.CDebugf(ctx, "Couldn't find chain for original new "+
"parent: %v", ri.originalNewParent)
return path{}, BlockPointer{}, nil,
errors.WithStack(NoChainFoundError{ri.originalNewParent})
}
for i, op := range newParent.ops {
oldCo, ok := op.(*createOp)
if !ok {
continue
}
if oldCo.NewName == ri.newName {
newParent.ops[i] = co
break
}
}
} else {
recreateOps = append(recreateOps, co)
}
currOriginal = parentOriginal
currPath = parentPath
}
// Now we have the latest pointer along the path that is
// shared between the branches. Our next step is to find the
// current merged path to the most recent version of that
// original. We can do that as follows:
// * If the pointer has been changed in the merged branch, we
// can search for it later using fbo.blocks.SearchForNodes
// * If it hasn't been changed, check if it has been renamed to
// somewhere else. If so, use fbo.blocks.SearchForNodes on
// that parent later.
// * Otherwise, iterate up the path towards the root.
var mostRecent BlockPointer
for i := len(currPath.path) - 1; i >= 0; i-- {
currOriginal, err := unmergedChains.originalFromMostRecent(
currPath.path[i].BlockPointer)
if err != nil {
cr.log.CDebugf(ctx, "Couldn't find original pointer for %v",
currPath.path[i])
return path{}, BlockPointer{}, nil, err
}
// Has it changed in the merged branch?
mostRecent, err = mergedChains.mostRecentFromOriginal(currOriginal)
if err == nil {
break
}
mergedPath.path = append(mergedPath.path, pathNode{
BlockPointer: currOriginal,
Name: currPath.path[i].Name,
})
// Has it been renamed?
if originalParent, newName, ok :=
mergedChains.renamedParentAndName(currOriginal); ok {
cr.log.CDebugf(ctx, "%v has been renamed in the merged branch",
currOriginal)
mostRecentParent, err :=
mergedChains.mostRecentFromOriginal(originalParent)
if err != nil {
cr.log.CDebugf(ctx, "Couldn't find original pointer for %v",
originalParent)
return path{}, BlockPointer{}, nil, err
}
mostRecent = mostRecentParent
// update the name for this renamed node
mergedPath.path[len(mergedPath.path)-1].Name = newName
break
}
}
// reverse the merged path
for i, j := 0, len(mergedPath.path)-1; i < j; i, j = i+1, j-1 {
mergedPath.path[i], mergedPath.path[j] =
mergedPath.path[j], mergedPath.path[i]
}
// reverse recreateOps
for i, j := 0, len(recreateOps)-1; i < j; i, j = i+1, j-1 {
recreateOps[i], recreateOps[j] = recreateOps[j], recreateOps[i]
}
return mergedPath, mostRecent, recreateOps, nil
}
// resolveMergedPaths maps each tail most recent pointer for all the
// given unmerged paths to a corresponding path in the merged branch.
// The merged branch may be missing some nodes that have been deleted;
// in that case, the merged path will contain placeholder path nodes
// using the original pointers for those directories.
//
// This function also returns a set of createOps that can be used to
// recreate the missing directories in the merged branch. If the
// parent directory needing the create has been deleted, then the
// unref ptr in the createOp contains the original pointer for the
// directory rather than the most recent merged pointer.
//
// It also potentially returns a new slice of unmerged paths that the
// caller should combine with the existing slice, corresponding to
// deleted unmerged chains that still have relevant operations to
// resolve.
func (cr *ConflictResolver) resolveMergedPaths(ctx context.Context,
lState *lockState, unmergedPaths []path,
unmergedChains, mergedChains *crChains,
currUnmergedWriterInfo writerInfo) (
map[BlockPointer]path, []*createOp, []path, error) {
// maps each most recent unmerged pointer to the corresponding
// most recent merged path.
mergedPaths := make(map[BlockPointer]path)
chainsToSearchFor := make(map[BlockPointer][]BlockPointer)
var ptrs []BlockPointer
// While we're at it, find any deleted unmerged directory chains
// containing operations, where the corresponding merged chain has
// changed. The unmerged rm ops will need to be re-applied in
// that case.
var newUnmergedPaths []path
for original, unmergedChain := range unmergedChains.byOriginal {
if !unmergedChains.isDeleted(original) || len(unmergedChain.ops) == 0 ||
unmergedChain.isFile() {
continue
}
mergedChain, ok := mergedChains.byOriginal[original]
if !ok || len(mergedChain.ops) == 0 ||
mergedChains.isDeleted(original) {
continue
}
cr.log.CDebugf(ctx, "A modified unmerged path %v was deleted but "+
"also modified in the merged branch %v",
unmergedChain.mostRecent, mergedChain.mostRecent)
// We know that everything in the directory has been removed,
// so only rm ops matter.
var newOps []op
for _, op := range unmergedChain.ops {
if rop, ok := op.(*rmOp); ok {
newOps = append(newOps, rop)
}
}
unmergedChain.ops = newOps
// Fake the unmerged path, it doesn't matter
unmergedPath := path{
FolderBranch: cr.fbo.folderBranch,
path: []pathNode{{BlockPointer: unmergedChain.mostRecent}},
}
chainsToSearchFor[mergedChain.mostRecent] =
append(chainsToSearchFor[mergedChain.mostRecent],
unmergedChain.mostRecent)
ptrs = append(ptrs, mergedChain.mostRecent)
newUnmergedPaths = append(newUnmergedPaths, unmergedPath)
}
// Skip out early if there's nothing to do.
if len(unmergedPaths) == 0 && len(ptrs) == 0 {
return mergedPaths, nil, nil, nil
}
// For each unmerged path, find the corresponding most recent
// pointer in the merged path. Track which entries need to be
// re-created.
var recreateOps []*createOp
createsSeen := make(map[createMapKey]bool)
// maps a merged most recent pointer to the set of unmerged most
// recent pointers that need some of their path filled in.
for _, p := range unmergedPaths {
mergedPath, mostRecent, ops, err := cr.resolveMergedPathTail(
ctx, lState, p, unmergedChains, mergedChains,
currUnmergedWriterInfo)
if err != nil {
return nil, nil, nil, err
}
// Save any recreateOps we've haven't seen yet.
for _, op := range ops {
key := createMapKey{op.Dir.Unref, op.NewName}
if _, ok := createsSeen[key]; ok {
continue
}
createsSeen[key] = true
recreateOps = append(recreateOps, op)
}
// At the end of this process, we are left with a merged path
// that begins just after mostRecent. We will fill this in
// later with the searchFromNodes result.
mergedPaths[p.tailPointer()] = mergedPath
if !mergedPath.isValid() {
// Temporary debugging for KBFS-2507.
cr.log.CDebugf(ctx, "Adding invalid merged path for %v "+
"(may be temporary)", p.tailPointer())
}
if mostRecent.IsInitialized() {
// Remember to fill in the corresponding mergedPath once we
// get mostRecent's full path.
chainsToSearchFor[mostRecent] =
append(chainsToSearchFor[mostRecent], p.tailPointer())
}
}
// Now we can search for all the merged paths that need to be
// updated due to unmerged operations. Start with a clean node
// cache for the merged branch.
newPtrs := make(map[BlockPointer]bool)
for ptr := range mergedChains.byMostRecent {
newPtrs[ptr] = true
}
for ptr := range chainsToSearchFor {
ptrs = append(ptrs, ptr)
}
if len(ptrs) == 0 {
// Nothing to search for
return mergedPaths, recreateOps, newUnmergedPaths, nil
}
mergedNodeCache := newNodeCacheStandard(cr.fbo.folderBranch)
nodeMap, _, err := cr.fbo.blocks.SearchForNodes(
ctx, mergedNodeCache, ptrs, newPtrs,
mergedChains.mostRecentChainMDInfo,
mergedChains.mostRecentChainMDInfo.GetRootDirEntry().BlockPointer)
if err != nil {
return nil, nil, nil, err
}
for ptr, n := range nodeMap {
if n == nil {
// All the pointers we're looking for should definitely be
// findable in the merged branch somewhere.
return nil, nil, nil, NodeNotFoundError{ptr}
}
p := mergedNodeCache.PathFromNode(n)
for _, unmergedMostRecent := range chainsToSearchFor[ptr] {
// Prepend the found path to the existing path
mergedPath := mergedPaths[unmergedMostRecent]
if !mergedPath.isValid() {
// Temporary debugging for KBFS-2507.
cr.log.CDebugf(ctx, "Populating merged path for %v with %v",
unmergedMostRecent, p.path)
}
newPath := make([]pathNode, len(p.path)+len(mergedPath.path))
copy(newPath[:len(p.path)], p.path)
copy(newPath[len(p.path):], mergedPath.path)
mergedPath.path = newPath
mergedPaths[unmergedMostRecent] = mergedPath
// update the final paths for those corresponding merged
// chains
mergedMostRecent := mergedPath.tailPointer()
chain, ok := mergedChains.byMostRecent[mergedMostRecent]
if !ok {
// it's ok for the merged path not to exist because we
// might still need to create it.
continue
}
for _, op := range chain.ops {
op.setFinalPath(mergedPath)
}
}
}
return mergedPaths, recreateOps, newUnmergedPaths, nil
}
// buildChainsAndPaths make crChains for both the unmerged and merged
// branches since the branch point, the corresponding full paths for
// those changes, any new recreate ops, and returns the MDs used to
// compute all this. Note that even if err is nil, the merged MD list
// might be non-nil to allow for better error handling.
//
// This always returns the merged MDs, even in an error case, to allow
// the caller's error-handling code to unstage if necessary.
func (cr *ConflictResolver) buildChainsAndPaths(
ctx context.Context, lState *lockState, writerLocked bool) (
unmergedChains, mergedChains *crChains, unmergedPaths []path,
mergedPaths map[BlockPointer]path, recreateOps []*createOp,
unmerged, merged []ImmutableRootMetadata, err error) {
// Fetch the merged and unmerged MDs
unmerged, merged, err = cr.getMDs(ctx, lState, writerLocked)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, err
}
if len(unmerged) == 0 {
cr.log.CDebugf(ctx, "Skipping merge process due to empty MD list")
return nil, nil, nil, nil, nil, nil, merged, nil
}
// Update the current input to reflect the MDs we'll actually be
// working with.
err = cr.updateCurrInput(ctx, unmerged, merged)
if err != nil {
return nil, nil, nil, nil, nil, nil, merged, err
}
// Canceled before we start the heavy lifting?
err = cr.checkDone(ctx)
if err != nil {
return nil, nil, nil, nil, nil, nil, merged, err
}
// Make the chains
unmergedChains, mergedChains, err = cr.makeChains(ctx, unmerged, merged)
if err != nil {
return nil, nil, nil, nil, nil, nil, merged, err
}
// TODO: if the root node didn't change in either chain, we can
// short circuit the rest of the process with a really easy
// merge...
// Get the full path for every most recent unmerged pointer with a
// chain of unmerged operations, and which was not created or
// deleted within in the unmerged branch.
unmergedPaths, err = unmergedChains.getPaths(ctx, &cr.fbo.blocks,
cr.log, cr.fbo.nodeCache, false, cr.config.Mode().IsTestMode())
if err != nil {
return nil, nil, nil, nil, nil, nil, merged, err
}
// Add in any directory paths that were created in both branches.
newUnmergedPaths, err := cr.findCreatedDirsToMerge(ctx, unmergedPaths,
unmergedChains, mergedChains)
if err != nil {
return nil, nil, nil, nil, nil, nil, merged, err
}
unmergedPaths = append(unmergedPaths, newUnmergedPaths...)
if len(newUnmergedPaths) > 0 {
sort.Sort(crSortedPaths(unmergedPaths))
}
// Mark the recreate ops as being authored by the current user.
kbpki := cr.config.KBPKI()
session, err := kbpki.GetCurrentSession(ctx)
if err != nil {
return nil, nil, nil, nil, nil, nil, merged, err
}
currUnmergedWriterInfo := newWriterInfo(session.UID,
session.VerifyingKey, unmerged[len(unmerged)-1].Revision())
// Find the corresponding path in the merged branch for each of
// these unmerged paths, and the set of any createOps needed to
// apply these unmerged operations in the merged branch.
mergedPaths, recreateOps, newUnmergedPaths, err = cr.resolveMergedPaths(
ctx, lState, unmergedPaths, unmergedChains, mergedChains,
currUnmergedWriterInfo)
if err != nil {
return nil, nil, nil, nil, nil, nil, merged, err
}
unmergedPaths = append(unmergedPaths, newUnmergedPaths...)
if len(newUnmergedPaths) > 0 {
sort.Sort(crSortedPaths(unmergedPaths))
}
return unmergedChains, mergedChains, unmergedPaths, mergedPaths,
recreateOps, unmerged, merged, nil
}
// addRecreateOpsToUnmergedChains inserts each recreateOp, into its
// appropriate unmerged chain, creating one if it doesn't exist yet.
// It also adds entries as necessary to mergedPaths, and returns a
// slice of new unmergedPaths to be added.
func (cr *ConflictResolver) addRecreateOpsToUnmergedChains(ctx context.Context,
recreateOps []*createOp, unmergedChains, mergedChains *crChains,
mergedPaths map[BlockPointer]path) ([]path, error) {
if len(recreateOps) == 0 {
return nil, nil
}
// First create a lookup table that maps every block pointer in
// every merged path to a corresponding key in the mergedPaths map.
keys := make(map[BlockPointer]BlockPointer)
for ptr, p := range mergedPaths {
for _, node := range p.path {
keys[node.BlockPointer] = ptr
}
}
var newUnmergedPaths []path
for _, rop := range recreateOps {
// If rop.Dir.Unref is a merged most recent pointer, look up the
// original. Otherwise rop.Dir.Unref is the original. Use the
// original to look up the appropriate unmerged chain and stick
// this op at the front.
origTargetPtr, err :=
mergedChains.originalFromMostRecentOrSame(rop.Dir.Unref)
if err != nil {
return nil, err
}
chain, ok := unmergedChains.byOriginal[origTargetPtr]
if !ok {
return nil, fmt.Errorf("recreateOp for %v has no chain",
origTargetPtr)
}
if len(chain.ops) == 0 {
newUnmergedPaths = append(newUnmergedPaths, rop.getFinalPath())
}
chain.ops = append([]op{rop}, chain.ops...)
// Look up the corresponding unmerged most recent pointer, and
// check whether there's a merged path for it yet. If not,
// create one by looking it up in the lookup table (created
// above) and taking the appropriate subpath.
_, ok = mergedPaths[chain.mostRecent]
if !ok {
mergedMostRecent := chain.original
if !mergedChains.isDeleted(chain.original) {
if mChain, ok := mergedChains.byOriginal[chain.original]; ok {
mergedMostRecent = mChain.mostRecent
}
}
key, ok := keys[mergedMostRecent]
if !ok {
return nil, fmt.Errorf("Couldn't find a merged path "+
"containing the target of a recreate op: %v",
mergedMostRecent)
}
currPath := mergedPaths[key]
for currPath.tailPointer() != mergedMostRecent &&
currPath.hasValidParent() {
currPath = *currPath.parentPath()
}
mergedPaths[chain.mostRecent] = currPath
}
}
return newUnmergedPaths, nil
}
// convertCreateIntoSymlink finds the create operation for the given
// node in the chain, and makes it into one that creates a new symlink
// (for directories) or a file copy. It also removes the
// corresponding remove operation from the old parent chain.
func (cr *ConflictResolver) convertCreateIntoSymlinkOrCopy(ctx context.Context,
ptr BlockPointer, info renameInfo, chain *crChain,
unmergedChains, mergedChains *crChains, symPath string) error {
found := false
outer:
for _, op := range chain.ops {
switch cop := op.(type) {
case *createOp:
if !cop.renamed || cop.NewName != info.newName {
continue
}
oldType := cop.Type
if cop.Type == Dir {
cop.Type = Sym
cop.crSymPath = symPath
cop.RefBlocks = nil
} else {
cop.forceCopy = true
}
cop.renamed = false
newInfo := renameInfo{
originalOldParent: info.originalNewParent,
oldName: info.newName,
originalNewParent: info.originalOldParent,
newName: info.oldName,
}
if newInfo2, ok := mergedChains.renamedOriginals[ptr]; ok {
// If this node was already moved in the merged
// branch, we need to tweak the merged branch's rename
// info so that it looks like it's being renamed from
// the new unmerged location.
newInfo = newInfo2
newInfo.originalOldParent = info.originalNewParent
newInfo.oldName = info.newName
} else {
// invert the op in the merged chains
invertCreate, err := newRmOp(info.newName,
info.originalNewParent, oldType)
if err != nil {
return err
}
err = invertCreate.Dir.setRef(info.originalNewParent)
if err != nil {
return err
}
invertRm, err := newCreateOp(info.oldName,
info.originalOldParent, cop.Type)
if err != nil {
return err
}
err = invertRm.Dir.setRef(info.originalOldParent)
if err != nil {
return err
}
invertRm.renamed = true
invertRm.AddRefBlock(ptr)
mergedNewMostRecent, err := mergedChains.
mostRecentFromOriginalOrSame(info.originalNewParent)
if err != nil {
return err
}
mergedOldMostRecent, err := mergedChains.
mostRecentFromOriginalOrSame(info.originalOldParent)
if err != nil {
return err
}
prependOpsToChain(mergedOldMostRecent, mergedChains,
invertRm)
prependOpsToChain(mergedNewMostRecent, mergedChains,
invertCreate)
}
cr.log.CDebugf(ctx, "Putting new merged rename info "+
"%v -> %v (symPath: %v)", ptr, newInfo, symPath)
mergedChains.renamedOriginals[ptr] = newInfo
// Fix up the corresponding rmOp to make sure
// that it gets dropped
oldParentChain :=
unmergedChains.byOriginal[info.originalOldParent]
for _, oldOp := range oldParentChain.ops {
ro, ok := oldOp.(*rmOp)
if !ok {
continue
}
if ro.OldName == info.oldName {
// No need to copy since this createOp
// must have been created as part of
// conflict resolution.
ro.dropThis = true
break
}
}
found = true
break outer
}
}
if !found {
return fmt.Errorf("fixRenameConflicts: couldn't find "+
"rename op corresponding to %v,%s", ptr, info.newName)
}
return nil
}
// crConflictCheckQuick checks whether the two given chains have any
// direct conflicts. TODO: currently this is a little pessimistic
// because it assumes any set attrs are in conflict, when in reality
// they can be for different attributes, or the same attribute with
// the same value.
func crConflictCheckQuick(unmergedChain, mergedChain *crChain) bool {
return unmergedChain != nil && mergedChain != nil &&
((unmergedChain.hasSyncOp() && mergedChain.hasSyncOp()) ||
(unmergedChain.hasSetAttrOp() && mergedChain.hasSetAttrOp()))
}
func (cr *ConflictResolver) getSingleUnmergedPath(
ctx context.Context, unmergedChains *crChains, chain *crChain) (
path, error) {
// Reuse some code by creating a new chains object
// consisting of only this node.
newChains := newCRChainsEmpty()
newChains.byOriginal[chain.original] = chain
newChains.byMostRecent[chain.mostRecent] = chain
// Fake out the rest of the chains to populate newPtrs.
for _, c := range unmergedChains.byOriginal {
if c.original == chain.original {
continue
}
newChain := &crChain{
original: c.original,
mostRecent: c.mostRecent,
}
newChains.byOriginal[c.original] = newChain
newChains.byMostRecent[c.mostRecent] = newChain
}
newChains.mostRecentChainMDInfo = unmergedChains.mostRecentChainMDInfo
unmergedPaths, err := newChains.getPaths(ctx, &cr.fbo.blocks,
cr.log, cr.fbo.nodeCache, false, cr.config.Mode().IsTestMode())
if err != nil {
return path{}, err
}
if len(unmergedPaths) != 1 {
return path{}, fmt.Errorf("Couldn't find the unmerged path for %v",
chain.original)
}
return unmergedPaths[0], nil
}
// fixRenameConflicts checks every unmerged createOp associated with a
// rename to see if it will cause a cycle. If so, it makes it a
// symlink create operation instead. It also checks whether a
// particular node had been renamed in both branches; if so, it will
// copy files, and use symlinks for directories.
func (cr *ConflictResolver) fixRenameConflicts(ctx context.Context,
unmergedChains, mergedChains *crChains,
mergedPaths map[BlockPointer]path) ([]path, error) {
// For every renamed block pointer in the unmerged chains:
// * Check if any BlockPointer in its merged path contains a relative of
// itself
// * If so, replace the corresponding unmerged create operation with a
// symlink creation to the new merged path instead.
// So, if in the merged branch someone did `mv b/ a/` and in the unmerged
// branch someone did `mv a/ b/`, the conflict resolution would end up with
// `a/b/a` where the second a is a symlink to "../".
//
// To calculate what the symlink should be, consider the following:
// * The unmerged path for the new parent of ptr P is u_1/u_2/.../u_n
// * u_i is the largest i <= n such that the corresponding block
// can be mapped to a node in merged branch (pointer m_j).
// * The full path to m_j in the merged branch is m_1/m_2/m_3/.../m_j
// * For a rename cycle to occur, some m_x where x <= j must be a
// descendant of P's original pointer.
// * The full merged path to the parent of the second copy of P will
// then be: m_1/m_2/.../m_x/.../m_j/u_i+1/.../u_n.
// * Then, the symlink to put under P's name in u_n is "../"*((n-i)+(j-x))
// In the case that u_n is a directory that was newly-created in the
// unmerged branch, we also need to construct a complete corresponding
// merged path, for use in later stages (like executing actions). This
// merged path is just m_1/.../m_j/u_i+1/.../u_n, using the most recent
// unmerged pointers.
var newUnmergedPaths []path
var removeRenames []BlockPointer
var doubleRenames []BlockPointer // merged most recent ptrs
for ptr, info := range unmergedChains.renamedOriginals {
if unmergedChains.isDeleted(ptr) {
continue
}
// Also, we need to get the merged paths for anything that was
// renamed in both branches, if they are different.
if mergedInfo, ok := mergedChains.renamedOriginals[ptr]; ok &&
(info.originalNewParent != mergedInfo.originalNewParent ||
info.newName != mergedInfo.newName) {
mergedMostRecent, err :=
mergedChains.mostRecentFromOriginalOrSame(ptr)
if err != nil {
return nil, err
}
doubleRenames = append(doubleRenames, mergedMostRecent)
continue
}
// If this node was modified in both branches, we need to fork
// the node, so we can get rid of the unmerged remove op and
// force a copy on the create op.
unmergedChain := unmergedChains.byOriginal[ptr]
mergedChain := mergedChains.byOriginal[ptr]
if crConflictCheckQuick(unmergedChain, mergedChain) {
cr.log.CDebugf(ctx, "File that was renamed on the unmerged "+
"branch from %s -> %s has conflicting edits, forking "+
"(original ptr %v)", info.oldName, info.newName, ptr)
oldParent := unmergedChains.byOriginal[info.originalOldParent]
for _, op := range oldParent.ops {
ro, ok := op.(*rmOp)
if !ok {
continue
}
if ro.OldName == info.oldName {
ro.dropThis = true
break
}
}
newParent := unmergedChains.byOriginal[info.originalNewParent]
for _, npOp := range newParent.ops {
co, ok := npOp.(*createOp)
if !ok {
continue
}
if co.NewName == info.newName && co.renamed {
co.forceCopy = true
co.renamed = false
co.AddRefBlock(unmergedChain.mostRecent)
co.DelRefBlock(ptr)
// Clear out the ops on the file itself, as we
// will be doing a fresh create instead.
unmergedChain.ops = nil
break
}
}
// Reset the chain of the forked file to the most recent
// pointer, since we want to avoid any local notifications
// linking the old version of the file to the new one.
if ptr != unmergedChain.mostRecent {
err := unmergedChains.changeOriginal(
ptr, unmergedChain.mostRecent)
if err != nil {
return nil, err
}
unmergedChains.createdOriginals[unmergedChain.mostRecent] = true
}
continue
}
// The merged path is keyed by the most recent unmerged tail
// pointer.
parent, err :=
unmergedChains.mostRecentFromOriginal(info.originalNewParent)
if err != nil {
return nil, err
}
mergedPath, ok := mergedPaths[parent]
unmergedWalkBack := 0 // (n-i) in the equation above
var unmergedPath path
if !ok {
// If this parent was newly created in the unmerged
// branch, we need to look up its earliest parent that
// existed in both branches.
if !unmergedChains.isCreated(info.originalNewParent) {
// There should definitely be a merged path for this
// parent, since it doesn't have a create operation.
return nil, fmt.Errorf("fixRenameConflicts: couldn't find "+
"merged path for %v", parent)
}
chain := unmergedChains.byOriginal[info.originalNewParent]
unmergedPath, err = cr.getSingleUnmergedPath(
ctx, unmergedChains, chain)
if err != nil {
return nil, err
}
// Look backwards to find the first parent with a merged path.
n := len(unmergedPath.path) - 1
for i := n; i >= 0; i-- {
mergedPath, ok = mergedPaths[unmergedPath.path[i].BlockPointer]
if ok {
unmergedWalkBack = n - i
break
}
}
if !ok {
return nil, fmt.Errorf("fixRenameConflicts: couldn't find any "+
"merged path for any parents of %v", parent)
}
}
for x, pn := range mergedPath.path {
original, err :=
mergedChains.originalFromMostRecent(pn.BlockPointer)
if err != nil {
// This node wasn't changed in the merged branch
original = pn.BlockPointer
}
if original != ptr {
continue
}
// If any node on this path matches the renamed pointer,
// we have a cycle.
chain, ok := unmergedChains.byMostRecent[parent]
if !ok {
return nil, fmt.Errorf("fixRenameConflicts: no chain for "+
"parent %v", parent)
}
j := len(mergedPath.path) - 1
// (j-x) in the above equation
mergedWalkBack := j - x
walkBack := unmergedWalkBack + mergedWalkBack
// Mark this as a symlink, and the resolver
// will take care of making it a symlink in
// the merged branch later. No need to copy
// since this createOp must have been created
// as part of conflict resolution.
symPath := "./" + strings.Repeat("../", walkBack)
cr.log.CDebugf(ctx, "Creating symlink %s at "+
"merged path %s", symPath, mergedPath)
err = cr.convertCreateIntoSymlinkOrCopy(ctx, ptr, info, chain,
unmergedChains, mergedChains, symPath)
if err != nil {
return nil, err
}
if unmergedWalkBack > 0 {
cr.log.CDebugf(ctx, "Adding new unmerged path %s",
unmergedPath)
newUnmergedPaths = append(newUnmergedPaths,
unmergedPath)
// Fake a merged path to make sure these
// actions will be taken.
mergedLen := len(mergedPath.path)
pLen := mergedLen + unmergedWalkBack
p := path{
FolderBranch: mergedPath.FolderBranch,
path: make([]pathNode, pLen),
}
unmergedStart := len(unmergedPath.path) -
unmergedWalkBack
copy(p.path[:mergedLen], mergedPath.path)
copy(p.path[mergedLen:],
unmergedPath.path[unmergedStart:])
mergedPaths[unmergedPath.tailPointer()] = p
if !p.isValid() {
// Temporary debugging for KBFS-2507.
cr.log.CDebugf(ctx, "Added invalid unmerged path for %v",
unmergedPath.tailPointer())
}
}
removeRenames = append(removeRenames, ptr)
}
}
// A map from merged most recent pointers of the parent
// directories of files that have been forked, to a list of child
// pointers within those directories that need their merged paths
// fixed up.
forkedFromMergedRenames := make(map[BlockPointer][]pathNode)
// Check the merged renames to see if any of them affect a
// modified file that the unmerged branch did not rename. If we
// find one, fork the file and leave the unmerged version under
// its unmerged name.
for ptr, info := range mergedChains.renamedOriginals {
if mergedChains.isDeleted(ptr) {
continue
}
// Skip double renames, already dealt with them above.
if unmergedInfo, ok := unmergedChains.renamedOriginals[ptr]; ok &&
(info.originalNewParent != unmergedInfo.originalNewParent ||
info.newName != unmergedInfo.newName) {
continue
}
// If this is a file that was modified in both branches, we
// need to fork the file and tell the unmerged copy to keep
// its current name.
unmergedChain := unmergedChains.byOriginal[ptr]
mergedChain := mergedChains.byOriginal[ptr]
if crConflictCheckQuick(unmergedChain, mergedChain) {
cr.log.CDebugf(ctx, "File that was renamed on the merged "+
"branch from %s -> %s has conflicting edits, forking "+
"(original ptr %v)", info.oldName, info.newName, ptr)
var unmergedParentPath path
for _, op := range unmergedChain.ops {
switch realOp := op.(type) {
case *syncOp:
realOp.keepUnmergedTailName = true
unmergedParentPath = *op.getFinalPath().parentPath()
case *setAttrOp:
realOp.keepUnmergedTailName = true
unmergedParentPath = *op.getFinalPath().parentPath()
}
}
if unmergedParentPath.isValid() {
// Reset the merged path for this file back to the
// merged path corresponding to the unmerged parent.
// Put the merged parent path on the list of paths to
// search for.
unmergedParent := unmergedParentPath.tailPointer()
if _, ok := mergedPaths[unmergedParent]; !ok {
upOriginal := unmergedChains.originals[unmergedParent]
mergedParent, err :=
mergedChains.mostRecentFromOriginalOrSame(upOriginal)
if err != nil {
return nil, err
}
forkedFromMergedRenames[mergedParent] =
append(forkedFromMergedRenames[mergedParent],
pathNode{unmergedChain.mostRecent, info.oldName})
newUnmergedPaths =
append(newUnmergedPaths, unmergedParentPath)
}
}
}
}
for _, ptr := range removeRenames {
delete(unmergedChains.renamedOriginals, ptr)
}
numRenamesToCheck := len(doubleRenames) + len(forkedFromMergedRenames)
if numRenamesToCheck == 0 {
return newUnmergedPaths, nil
}
// Make chains for the new merged parents of all the double renames.
newPtrs := make(map[BlockPointer]bool)
ptrs := make([]BlockPointer, len(doubleRenames), numRenamesToCheck)
copy(ptrs, doubleRenames)
for ptr := range forkedFromMergedRenames {
ptrs = append(ptrs, ptr)
}
// Fake out the rest of the chains to populate newPtrs
for ptr := range mergedChains.byMostRecent {
newPtrs[ptr] = true
}
mergedNodeCache := newNodeCacheStandard(cr.fbo.folderBranch)
nodeMap, _, err := cr.fbo.blocks.SearchForNodes(
ctx, mergedNodeCache, ptrs, newPtrs,
mergedChains.mostRecentChainMDInfo,
mergedChains.mostRecentChainMDInfo.GetRootDirEntry().BlockPointer)
if err != nil {
return nil, err
}
for _, ptr := range doubleRenames {
// Find the merged paths
node, ok := nodeMap[ptr]
if !ok || node == nil {
return nil, fmt.Errorf("Couldn't find merged path for "+
"doubly-renamed pointer %v", ptr)
}
original, err :=
mergedChains.originalFromMostRecentOrSame(ptr)
if err != nil {
return nil, err
}
unmergedInfo, ok := unmergedChains.renamedOriginals[original]
if !ok {
return nil, fmt.Errorf("fixRenameConflicts: can't find the "+
"unmerged rename info for %v during double-rename resolution",
original)
}
mergedInfo, ok := mergedChains.renamedOriginals[original]
if !ok {
return nil, fmt.Errorf("fixRenameConflicts: can't find the "+
"merged rename info for %v during double-rename resolution",
original)
}
// If any node on this path matches the renamed pointer,
// we have a cycle.
chain, ok := unmergedChains.byOriginal[unmergedInfo.originalNewParent]
if !ok {
return nil, fmt.Errorf("fixRenameConflicts: no chain for "+
"parent %v", unmergedInfo.originalNewParent)
}
// For directories, the symlinks traverse down the merged path
// to the first common node, and then back up to the new
// parent/name. TODO: what happens when some element along
// the merged path also got renamed by the unmerged branch?
// The symlink would likely be wrong in that case.
mergedPathOldParent, ok := mergedPaths[chain.mostRecent]
if !ok {
return nil, fmt.Errorf("fixRenameConflicts: couldn't find "+
"merged path for old parent %v", chain.mostRecent)
}
mergedPathNewParent := mergedNodeCache.PathFromNode(node)
symPath := "./"
newParentStart := 0
outer:
for i := len(mergedPathOldParent.path) - 1; i >= 0; i-- {
mostRecent := mergedPathOldParent.path[i].BlockPointer
for j, pnode := range mergedPathNewParent.path {
original, err :=
unmergedChains.originalFromMostRecentOrSame(mostRecent)
if err != nil {
return nil, err
}
mergedMostRecent, err :=
mergedChains.mostRecentFromOriginalOrSame(original)
if err != nil {
return nil, err
}
if pnode.BlockPointer == mergedMostRecent {
newParentStart = j
break outer
}
}
symPath += "../"
}
// Move up directories starting from beyond the common parent,
// to right before the actual node.
for i := newParentStart + 1; i < len(mergedPathNewParent.path)-1; i++ {
symPath += mergedPathNewParent.path[i].Name + "/"
}
symPath += mergedInfo.newName
err = cr.convertCreateIntoSymlinkOrCopy(ctx, original, unmergedInfo,
chain, unmergedChains, mergedChains, symPath)
if err != nil {
return nil, err
}
}
for ptr, pathNodes := range forkedFromMergedRenames {
// Find the merged paths
node, ok := nodeMap[ptr]
if !ok || node == nil {
return nil, fmt.Errorf("Couldn't find merged path for "+
"forked parent pointer %v", ptr)
}
mergedPathNewParent := mergedNodeCache.PathFromNode(node)
for _, pNode := range pathNodes {
mergedPath := mergedPathNewParent.ChildPath(
pNode.Name, pNode.BlockPointer)
mergedPaths[pNode.BlockPointer] = mergedPath
}
}
return newUnmergedPaths, nil
}
// addMergedRecreates drops any unmerged operations that remove a node
// that was modified in the merged branch, and adds a create op to the
// merged chain so that the node will be re-created locally.
func (cr *ConflictResolver) addMergedRecreates(ctx context.Context,
unmergedChains, mergedChains *crChains,
mostRecentMergedWriterInfo writerInfo) error {
for _, unmergedChain := range unmergedChains.byMostRecent {
// First check for nodes that have been deleted in the unmerged
// branch, but modified in the merged branch, and drop those
// unmerged operations.
for _, untypedOp := range unmergedChain.ops {
ro, ok := untypedOp.(*rmOp)
if !ok {
continue
}
// Perhaps the rm target has been renamed somewhere else,
// before eventually being deleted. In this case, we have
// to look up the original by iterating over
// renamedOriginals.
if len(ro.Unrefs()) == 0 {
for original, info := range unmergedChains.renamedOriginals {
if info.originalOldParent == unmergedChain.original &&
info.oldName == ro.OldName &&
unmergedChains.isDeleted(original) {
ro.AddUnrefBlock(original)
break
}
}
}
for _, ptr := range ro.Unrefs() {
unrefOriginal, err :=
unmergedChains.originalFromMostRecentOrSame(ptr)
if err != nil {
return err
}
if c, ok := mergedChains.byOriginal[unrefOriginal]; ok {
ro.dropThis = true
// Need to prepend a create here to the merged parent,
// in order catch any conflicts.
parentOriginal := unmergedChain.original
name := ro.OldName
if newParent, newName, ok :=
mergedChains.renamedParentAndName(unrefOriginal); ok {
// It was renamed in the merged branch, so
// recreate with the new parent and new name.
parentOriginal = newParent
name = newName
} else if info, ok :=
unmergedChains.renamedOriginals[unrefOriginal]; ok {
// It was only renamed in the old parent, so
// use the old parent and original name.
parentOriginal = info.originalOldParent
name = info.oldName
}
chain, ok := mergedChains.byOriginal[parentOriginal]
if !ok {
return fmt.Errorf("Couldn't find chain for parent %v "+
"of merged entry %v we're trying to recreate",
parentOriginal, unrefOriginal)
}
t := Dir
if c.isFile() {
// TODO: how to fix this up for executables
// and symlinks? Only matters for checking
// conflicts if something with the same name
// is created on the unmerged branch.
t = File
}
co, err := newCreateOp(name, chain.original, t)
if err != nil {
return err
}
err = co.Dir.setRef(chain.original)
if err != nil {
return err
}
co.AddRefBlock(c.mostRecent)
co.setWriterInfo(mostRecentMergedWriterInfo)
chain.ops = append([]op{co}, chain.ops...)
cr.log.CDebugf(ctx, "Re-created rm'd merge-modified node "+
"%v with operation %s in parent %v", unrefOriginal, co,
parentOriginal)
}
}
}
}
return nil
}
// getActionsToMerge returns the set of actions needed to merge each
// unmerged chain of operations, in a map keyed by the tail pointer of
// the corresponding merged path.
func (cr *ConflictResolver) getActionsToMerge(
ctx context.Context, unmergedChains, mergedChains *crChains,
mergedPaths map[BlockPointer]path) (
map[BlockPointer]crActionList, error) {
actionMap := make(map[BlockPointer]crActionList)
for unmergedMostRecent, unmergedChain := range unmergedChains.byMostRecent {
original := unmergedChain.original
// If this is a file that has been deleted in the merged
// branch, a corresponding recreate op will take care of it,
// no need to do anything here.
// We don't need the "ok" value from this lookup because it's
// fine to pass a nil mergedChain into crChain.getActionsToMerge.
mergedChain := mergedChains.byOriginal[original]
mergedPath, ok := mergedPaths[unmergedMostRecent]
if !ok {
// This most likely means that the file was created or
// deleted in the unmerged branch and thus has no
// corresponding merged path yet.
continue
}
if !mergedPath.isValid() {
cr.log.CWarningf(ctx, "Ignoring invalid merged path for %v "+
"(original=%v)", unmergedMostRecent, original)
continue
}
actions, err := unmergedChain.getActionsToMerge(
ctx, cr.config.ConflictRenamer(), mergedPath,
mergedChain)
if err != nil {
return nil, err
}
if len(actions) > 0 {
actionMap[mergedPath.tailPointer()] = actions
}
}
return actionMap, nil
}
// collapseActions combines file updates with their parent directory
// updates, because conflict resolution only happens within a
// directory (i.e., files are merged directly, they are just
// renamed/copied). It also collapses each action list to get rid of
// redundant actions. It returns a slice of additional unmerged paths
// that should be included in the overall list of unmergedPaths.
func collapseActions(unmergedChains *crChains, unmergedPaths []path,
mergedPaths map[BlockPointer]path,
actionMap map[BlockPointer]crActionList) (newUnmergedPaths []path) {
for unmergedMostRecent, chain := range unmergedChains.byMostRecent {
// Find the parent directory path and combine
p, ok := mergedPaths[unmergedMostRecent]
if !ok {
continue
}
fileActions := actionMap[p.tailPointer()]
// If this is a directory with setAttr(mtime)-related actions,
// just those action should be collapsed into the parent.
if !chain.isFile() {
var parentActions crActionList
var otherDirActions crActionList
for _, action := range fileActions {
moved := false
switch realAction := action.(type) {
case *copyUnmergedAttrAction:
if realAction.attr[0] == mtimeAttr && !realAction.moved {
realAction.moved = true
parentActions = append(parentActions, realAction)
moved = true
}
case *renameUnmergedAction:
if realAction.causedByAttr == mtimeAttr &&
!realAction.moved {
realAction.moved = true
parentActions = append(parentActions, realAction)
moved = true
}
}
if !moved {
otherDirActions = append(otherDirActions, action)
}
}
if len(parentActions) == 0 {
// A directory with no mtime actions, so treat it
// normally.
continue
}
fileActions = parentActions
if len(otherDirActions) > 0 {
actionMap[p.tailPointer()] = otherDirActions
} else {
delete(actionMap, p.tailPointer())
}
} else {
// Mark the copyUnmergedAttrActions as moved, so they
// don't get moved again by the parent.
for _, action := range fileActions {
if realAction, ok := action.(*copyUnmergedAttrAction); ok {
realAction.moved = true
}
}
}
parentPath := *p.parentPath()
mergedParent := parentPath.tailPointer()
parentActions, wasParentActions := actionMap[mergedParent]
combinedActions := append(parentActions, fileActions...)
actionMap[mergedParent] = combinedActions
if chain.isFile() {
mergedPaths[unmergedMostRecent] = parentPath
delete(actionMap, p.tailPointer())
}
if !wasParentActions {
// The parent isn't yet represented in our data
// structures, so we have to make sure its actions get
// executed.
//
// Find the unmerged path to get the unmerged parent.
for _, unmergedPath := range unmergedPaths {
if unmergedPath.tailPointer() != unmergedMostRecent {
continue
}
unmergedParentPath := *unmergedPath.parentPath()
unmergedParent := unmergedParentPath.tailPointer()
unmergedParentChain :=
unmergedChains.byMostRecent[unmergedParent]
// If this is a file, only add a new unmerged path if
// the parent has ops; otherwise it will confuse the
// resolution code and lead to stray blocks.
if !chain.isFile() || len(unmergedParentChain.ops) > 0 {
newUnmergedPaths =
append(newUnmergedPaths, unmergedParentPath)
}
// File merged paths were already updated above.
if !chain.isFile() {
mergedPaths[unmergedParent] = parentPath
}
break
}
}
}
for ptr, actions := range actionMap {
actionMap[ptr] = actions.collapse()
}
return newUnmergedPaths
}
func (cr *ConflictResolver) computeActions(ctx context.Context,
unmergedChains, mergedChains *crChains, unmergedPaths []path,
mergedPaths map[BlockPointer]path, recreateOps []*createOp,
mostRecentMergedWriterInfo writerInfo) (
map[BlockPointer]crActionList, []path, error) {
// Process all the recreateOps, adding them to the appropriate
// unmerged chains.
newUnmergedPaths, err := cr.addRecreateOpsToUnmergedChains(
ctx, recreateOps, unmergedChains, mergedChains, mergedPaths)
if err != nil {
return nil, nil, err
}
// Fix any rename cycles by turning the corresponding unmerged
// createOp into a symlink entry type.
moreNewUnmergedPaths, err := cr.fixRenameConflicts(ctx, unmergedChains,
mergedChains, mergedPaths)
if err != nil {
return nil, nil, err
}
newUnmergedPaths = append(newUnmergedPaths, moreNewUnmergedPaths...)
// Recreate any modified merged nodes that were rm'd in the
// unmerged branch.
if err := cr.addMergedRecreates(
ctx, unmergedChains, mergedChains,
mostRecentMergedWriterInfo); err != nil {
return nil, nil, err
}
actionMap, err := cr.getActionsToMerge(
ctx, unmergedChains, mergedChains, mergedPaths)
if err != nil {
return nil, nil, err
}
// Finally, merged the file actions back into their parent
// directory action list, and collapse everything together.
moreNewUnmergedPaths =
collapseActions(unmergedChains, unmergedPaths, mergedPaths, actionMap)
return actionMap, append(newUnmergedPaths, moreNewUnmergedPaths...), nil
}
// fileBlockMap maps latest merged block pointer to a map of final
// merged name -> file block.
type fileBlockMap map[BlockPointer]map[string]*FileBlock
func (cr *ConflictResolver) makeFileBlockDeepCopy(ctx context.Context,
lState *lockState, chains *crChains, mergedMostRecent BlockPointer,
parentPath path, name string, ptr BlockPointer, blocks fileBlockMap,
dirtyBcache DirtyBlockCache) (BlockPointer, error) {
kmd := chains.mostRecentChainMDInfo
file := parentPath.ChildPath(name, ptr)
oldInfos, err := cr.fbo.blocks.getIndirectFileBlockInfosLocked(
ctx, lState, kmd, file)
if err != nil {
return BlockPointer{}, err
}
newPtr, allChildPtrs, err := cr.fbo.blocks.deepCopyFileLocked(
ctx, lState, kmd, file, dirtyBcache, cr.config.DataVersion())
if err != nil {
return BlockPointer{}, err
}
block, err := dirtyBcache.Get(cr.fbo.id(), newPtr, cr.fbo.branch())
if err != nil {
return BlockPointer{}, err
}
fblock, isFileBlock := block.(*FileBlock)
if !isFileBlock {
return BlockPointer{}, NotFileBlockError{ptr, cr.fbo.branch(), file}
}
// Mark this as having been created during this chain, so that
// later during block accounting we can infer the origin of the
// block.
chains.createdOriginals[newPtr] = true
// If this file was created within the branch, we should clean up
// all the old block pointers.
original, err := chains.originalFromMostRecentOrSame(ptr)
if err != nil {
return BlockPointer{}, err
}
newlyCreated := chains.isCreated(original)
if newlyCreated {
chains.toUnrefPointers[original] = true
for _, oldInfo := range oldInfos {
chains.toUnrefPointers[oldInfo.BlockPointer] = true
}
}
if _, ok := blocks[mergedMostRecent]; !ok {
blocks[mergedMostRecent] = make(map[string]*FileBlock)
}
for _, childPtr := range allChildPtrs {
chains.createdOriginals[childPtr] = true
}
blocks[mergedMostRecent][name] = fblock
return newPtr, nil
}
func (cr *ConflictResolver) doOneAction(
ctx context.Context, lState *lockState,
unmergedChains, mergedChains *crChains, unmergedPath path,
mergedPaths map[BlockPointer]path, chargedTo keybase1.UserOrTeamID,
actionMap map[BlockPointer]crActionList, lbc localBcache,
doneActions map[BlockPointer]bool, newFileBlocks fileBlockMap,
dirtyBcache DirtyBlockCache) error {
unmergedMostRecent := unmergedPath.tailPointer()
unmergedChain, ok :=
unmergedChains.byMostRecent[unmergedMostRecent]
if !ok {
return fmt.Errorf("Couldn't find unmerged chain for %v",
unmergedMostRecent)
}
// If this is a file that has been deleted in the merged
// branch, a corresponding recreate op will take care of it,
// no need to do anything here.
// find the corresponding merged path
mergedPath, ok := mergedPaths[unmergedMostRecent]
if !ok {
// This most likely means that the file was created or
// deleted in the unmerged branch and thus has no
// corresponding merged path yet.
return nil
}
if unmergedChain.isFile() {
// The unmerged path is actually the parent (the merged
// path was already corrected above).
unmergedPath = *unmergedPath.parentPath()
}
// Now get the directory blocks. For unmerged directories, we
// can use a nil local block cache, because unmerged blocks
// should never be changed during the CR process (since
// they're just going away). This call will lock `blockLock`,
// and the subsequent `newDirData` calls can assume it's
// locked already.
var unmergedDir *dirData
unmergedDir, cleanupFn := cr.fbo.blocks.newDirDataWithLBC(
lState, unmergedPath, chargedTo,
unmergedChains.mostRecentChainMDInfo, nil)
defer cleanupFn()
if unmergedPath.tailPointer() == mergedPath.tailPointer() {
// recreateOps update the merged paths using original
// pointers; but if other stuff happened in the merged
// block before it was deleted (such as other removes) we
// want to preserve those. Therefore, we don't want the
// unmerged block to remain in the local block cache.
// Below we'll replace it with a new one instead.
delete(lbc, unmergedPath.tailPointer())
cr.log.CDebugf(ctx, "Removing block for %v from the local cache",
unmergedPath.tailPointer())
}
_, blockExists := lbc[mergedPath.tailPointer()]
// If this is a recreate op and we haven't yet made a new
// block for it, then make a new one and put it in the local
// block cache.
if mergedChains.isDeleted(mergedPath.tailPointer()) && !blockExists {
lbc[mergedPath.tailPointer()] = NewDirBlock().(*DirBlock)
}
mergedDir := cr.fbo.blocks.newDirDataWithLBCLocked(
lState, mergedPath, chargedTo,
mergedChains.mostRecentChainMDInfo, lbc)
// Force the top block into the `lbc`. `folderUpdatePrepper`
// requires this, even if the block isn't modified, to
// distinguish it from a file block.
_, err := mergedDir.getTopBlock(ctx, blockWrite)
if err != nil {
return err
}
actions := actionMap[mergedPath.tailPointer()]
if len(actions) > 0 && !doneActions[mergedPath.tailPointer()] {
// Make sure we don't try to execute the same actions twice.
doneActions[mergedPath.tailPointer()] = true
// Any file block copies, keyed by their new temporary block
// IDs, and later we will ready them.
unmergedFetcher := func(ctx context.Context, name string,
ptr BlockPointer) (BlockPointer, error) {
return cr.makeFileBlockDeepCopy(ctx, lState, unmergedChains,
mergedPath.tailPointer(), unmergedPath, name, ptr,
newFileBlocks, dirtyBcache)
}
mergedFetcher := func(ctx context.Context, name string,
ptr BlockPointer) (BlockPointer, error) {
return cr.makeFileBlockDeepCopy(ctx, lState, mergedChains,
mergedPath.tailPointer(), mergedPath, name,
ptr, newFileBlocks, dirtyBcache)
}
// Execute each action and save the modified ops back into
// each chain.
for _, action := range actions {
swap, newPtr, err := action.swapUnmergedBlock(
ctx, unmergedChains, mergedChains, unmergedDir)
if err != nil {
return err
}
uDir := unmergedDir
if swap {
cr.log.CDebugf(ctx, "Swapping out dir %v for %v",
newPtr, unmergedPath.tailPointer())
if newPtr == zeroPtr {
// Use the merged `dirData`.
uDir = mergedDir
} else {
// Use the specified `dirData`, and supply a
// `nil` local block cache to ensure that a)
// only clean blocks are used, as blocks in
// the `lbc` might have already been touched
// by previous actions, and b) no new blocks
// are cached.
newPath := path{
FolderBranch: mergedPath.FolderBranch,
path: []pathNode{{
newPtr, mergedPath.tailName()}},
}
uDir = cr.fbo.blocks.newDirDataWithLBCLocked(
lState, newPath, chargedTo,
mergedChains.mostRecentChainMDInfo, nil)
}
}
unrefs, err := action.do(
ctx, unmergedFetcher, mergedFetcher, uDir, mergedDir)
if err != nil {
return err
}
for _, info := range unrefs {
unmergedChains.toUnrefPointers[info.BlockPointer] = true
}
}
}
// Now update the ops related to this exact path (not the ops
// for its parent!).
for _, action := range actions {
// unmergedMostRecent is for the correct pointer, but
// mergedPath may be for the parent in the case of files
// so we need to find the real mergedMostRecent pointer.
mergedMostRecent := unmergedChain.original
mergedChain, ok := mergedChains.byOriginal[unmergedChain.original]
if ok {
mergedMostRecent = mergedChain.mostRecent
}
err := action.updateOps(
ctx, unmergedMostRecent, mergedMostRecent,
unmergedDir, mergedDir, unmergedChains, mergedChains)
if err != nil {
return err
}
}
return nil
}
func (cr *ConflictResolver) doActions(ctx context.Context,
lState *lockState, unmergedChains, mergedChains *crChains,
unmergedPaths []path, mergedPaths map[BlockPointer]path,
actionMap map[BlockPointer]crActionList, lbc localBcache,
newFileBlocks fileBlockMap, dirtyBcache DirtyBlockCache) error {
mergedMD := mergedChains.mostRecentChainMDInfo
chargedTo, err := chargedToForTLF(
ctx, cr.config.KBPKI(), cr.config.KBPKI(), mergedMD.GetTlfHandle())
if err != nil {
return err
}
// For each set of actions:
// * Find the corresponding chains
// * Make a reference to each slice of ops
// * Get the unmerged block.
// * Get the merged block if it's not already in the local cache, and
// make a copy.
// * Get the merged block
// * Do each action, updating the ops references to the returned ones
// At the end, the local block cache should contain all the
// updated merged blocks. A future phase will update the pointers
// in standard Merkle-tree-fashion.
doneActions := make(map[BlockPointer]bool)
for _, unmergedPath := range unmergedPaths {
err := cr.doOneAction(
ctx, lState, unmergedChains, mergedChains, unmergedPath,
mergedPaths, chargedTo, actionMap, lbc, doneActions, newFileBlocks,
dirtyBcache)
if err != nil {
return err
}
}
return nil
}
type crRenameHelperKey struct {
parentOriginal BlockPointer
name string
}
// makeRevertedOps changes the BlockPointers of the corresponding
// operations for the given set of paths back to their originals,
// which allows other parts of conflict resolution to more easily
// build up the local and remote notifications needed. Also, it
// reverts rm/create pairs back into complete rename operations, for
// the purposes of notification, so this should only be called after
// all conflicts and actions have been resolved. It returns the
// complete slice of reverted operations.
func (cr *ConflictResolver) makeRevertedOps(ctx context.Context,
lState *lockState, sortedPaths []path, chains *crChains,
otherChains *crChains) ([]op, error) {
var ops []op
// Build a map of directory {original, name} -> renamed original.
// This will help us map create ops to the corresponding old
// parent.
renames := make(map[crRenameHelperKey]BlockPointer)
for original, ri := range chains.renamedOriginals {
renames[crRenameHelperKey{ri.originalNewParent, ri.newName}] = original
}
// Insert the operations starting closest to the root, so
// necessary directories are created first.
for i := len(sortedPaths) - 1; i >= 0; i-- {
ptr := sortedPaths[i].tailPointer()
chain, ok := chains.byMostRecent[ptr]
if !ok {
return nil, fmt.Errorf("makeRevertedOps: Couldn't find chain "+
"for %v", ptr)
}
chainLoop:
for _, op := range chain.ops {
// Skip any rms that were part of a rename
if rop, ok := op.(*rmOp); ok && len(rop.Unrefs()) == 0 {
continue
}
// Turn the create half of a rename back into a full rename.
if cop, ok := op.(*createOp); ok && cop.renamed {
renameOriginal, ok := renames[crRenameHelperKey{
chain.original, cop.NewName}]
if !ok {
if cop.crSymPath != "" || cop.Type == Sym {
// For symlinks created by the CR process, we
// expect the rmOp to have been removed. For
// existing symlinks that were simply moved,
// there is no benefit in combining their
// create and rm ops back together since there
// is no corresponding node.
continue
}
return nil, fmt.Errorf("Couldn't find corresponding "+
"renamed original for %v, %s",
chain.original, cop.NewName)
}
if otherChains.isDeleted(renameOriginal) ||
chains.isCreated(renameOriginal) {
// If we are re-instating a deleted node, or
// dealing with a node that was created entirely
// in this branch, just use the create op.
op = chains.copyOpAndRevertUnrefsToOriginals(cop)
if cop.Type != Dir {
renameMostRecent, err :=
chains.mostRecentFromOriginalOrSame(renameOriginal)
if err != nil {
return nil, err
}
err = cr.addChildBlocksIfIndirectFile(ctx, lState,
chains, cop.getFinalPath().ChildPath(
cop.NewName, renameMostRecent), op)
if err != nil {
return nil, err
}
}
} else {
ri, ok := chains.renamedOriginals[renameOriginal]
if !ok {
return nil, fmt.Errorf("Couldn't find the rename info "+
"for original %v", renameOriginal)
}
rop, err := newRenameOp(ri.oldName, ri.originalOldParent,
ri.newName, ri.originalNewParent, renameOriginal,
cop.Type)
if err != nil {
return nil, err
}
// Set the Dir.Ref fields to be the same as the Unref
// -- they will be fixed up later.
rop.AddSelfUpdate(ri.originalOldParent)
if ri.originalNewParent != ri.originalOldParent {
rop.AddSelfUpdate(ri.originalNewParent)
}
for _, ptr := range cop.Unrefs() {
origPtr, err := chains.originalFromMostRecentOrSame(ptr)
if err != nil {
return nil, err
}
rop.AddUnrefBlock(origPtr)
}
op = rop
// If this renames from a source that's been
// deleted by a previous op, we should replace the
// delete with this.
for i, prevOp := range ops {
rmop, ok := prevOp.(*rmOp)
if !ok {
continue
}
if rop.OldDir.Unref == rmop.Dir.Unref &&
rop.OldName == rmop.OldName {
ops[i] = op
continue chainLoop
}
}
}
} else {
op = chains.copyOpAndRevertUnrefsToOriginals(op)
// The dir of renamed setAttrOps must be reverted to
// the new parent's original pointer.
if sao, ok := op.(*setAttrOp); ok {
if newDir, _, ok :=
otherChains.renamedParentAndName(sao.File); ok {
err := sao.Dir.setUnref(newDir)
if err != nil {
return nil, err
}
}
}
}
ops = append(ops, op)
}
}
return ops, nil
}
// createResolvedMD creates a MD update that will be merged into the
// main folder as the resolving commit. It contains all of the
// unmerged operations, as well as a "dummy" operation at the end
// which will catch all of the BlockPointer updates. A later phase
// will move all of those updates into their proper locations within
// the other operations.
func (cr *ConflictResolver) createResolvedMD(ctx context.Context,
lState *lockState, unmergedPaths []path,
unmergedChains, mergedChains *crChains,
mostRecentMergedMD ImmutableRootMetadata) (*RootMetadata, error) {
err := cr.checkDone(ctx)
if err != nil {
return nil, err
}
newMD, err := mostRecentMergedMD.MakeSuccessor(
ctx, cr.config.MetadataVersion(), cr.config.Codec(),
cr.config.KeyManager(), cr.config.KBPKI(),
cr.config.KBPKI(), mostRecentMergedMD.MdID(), true)
if err != nil {
return nil, err
}
var newPaths []path
for original, chain := range unmergedChains.byOriginal {
added := false
for i, op := range chain.ops {
if cop, ok := op.(*createOp); ok {
// We need to add in any creates that happened
// within newly-created directories (which aren't
// being merged with other newly-created directories),
// to ensure that the overall Refs are correct and
// that future CR processes can check those create ops
// for conflicts.
if unmergedChains.isCreated(original) &&
!mergedChains.isCreated(original) {
// Shallowly copy the create op and update its
// directory to the most recent pointer -- this won't
// work with the usual revert ops process because that
// skips chains which are newly-created within this
// branch.
newCreateOp := *cop
newCreateOp.Dir, err = makeBlockUpdate(
chain.mostRecent, chain.mostRecent)
if err != nil {
return nil, err
}
chain.ops[i] = &newCreateOp
if !added {
newPaths = append(newPaths, path{
FolderBranch: cr.fbo.folderBranch,
path: []pathNode{{
BlockPointer: chain.mostRecent}},
})
added = true
}
}
if cop.Type == Dir || len(cop.Refs()) == 0 {
continue
}
// Add any direct file blocks too into each create op,
// which originated in later unmerged syncs.
ptr, err :=
unmergedChains.mostRecentFromOriginalOrSame(cop.Refs()[0])
if err != nil {
return nil, err
}
trackSyncPtrChangesInCreate(
ptr, chain, unmergedChains, cop.NewName)
}
}
}
if len(newPaths) > 0 {
// Put the new paths at the beginning so they are processed
// last in sorted order.
unmergedPaths = append(newPaths, unmergedPaths...)
}
ops, err := cr.makeRevertedOps(
ctx, lState, unmergedPaths, unmergedChains, mergedChains)
if err != nil {
return nil, err
}
cr.log.CDebugf(ctx, "Remote notifications: %v", ops)
for _, op := range ops {
cr.log.CDebugf(ctx, "%s: refs %v", op, op.Refs())
newMD.AddOp(op)
}
// Add a final dummy operation to collect all of the block updates.
newMD.AddOp(newResolutionOp())
return newMD, nil
}
// resolveOnePath figures out the new merged path, in the resolved
// folder, for a given unmerged pointer. For each node on the path,
// see if the node has been renamed. If so, see if there's a
// resolution for it yet. If there is, complete the path using that
// resolution. If not, recurse.
func (cr *ConflictResolver) resolveOnePath(ctx context.Context,
unmergedMostRecent BlockPointer,
unmergedChains, mergedChains, resolvedChains *crChains,
mergedPaths, resolvedPaths map[BlockPointer]path) (path, error) {
if p, ok := resolvedPaths[unmergedMostRecent]; ok {
return p, nil
}
// There should always be a merged path, because we should only be
// calling this with pointers that were updated in the unmerged
// branch.
resolvedPath, ok := mergedPaths[unmergedMostRecent]
if !ok {
var ptrsToAppend []BlockPointer
var namesToAppend []string
next := unmergedMostRecent
for len(mergedPaths[next].path) == 0 {
newPtrs := make(map[BlockPointer]bool)
ptrs := []BlockPointer{unmergedMostRecent}
for ptr := range unmergedChains.byMostRecent {
newPtrs[ptr] = true
}
mdInfo := unmergedChains.mostRecentChainMDInfo
nodeMap, cache, err := cr.fbo.blocks.SearchForNodes(
ctx, cr.fbo.nodeCache, ptrs, newPtrs,
mdInfo, mdInfo.GetRootDirEntry().BlockPointer)
if err != nil {
return path{}, err
}
n := nodeMap[unmergedMostRecent]
if n == nil {
return path{}, fmt.Errorf("resolveOnePath: Couldn't find "+
"merged path for %v", unmergedMostRecent)
}
p := cache.PathFromNode(n)
ptrsToAppend = append(ptrsToAppend, next)
namesToAppend = append(namesToAppend, p.tailName())
next = p.parentPath().tailPointer()
}
resolvedPath = mergedPaths[next]
for i, ptr := range ptrsToAppend {
resolvedPath = resolvedPath.ChildPath(namesToAppend[i], ptr)
}
}
i := len(resolvedPath.path) - 1
for i >= 0 {
mergedMostRecent := resolvedPath.path[i].BlockPointer
original, err :=
mergedChains.originalFromMostRecentOrSame(mergedMostRecent)
if err != nil {
return path{}, err
}
origNewParent, newName, renamed :=
resolvedChains.renamedParentAndName(original)
if !renamed {
i--
continue
}
unmergedNewParent, err :=
unmergedChains.mostRecentFromOriginalOrSame(origNewParent)
if err != nil {
return path{}, err
}
// Is the new parent resolved yet?
parentPath, err := cr.resolveOnePath(ctx, unmergedNewParent,
unmergedChains, mergedChains, resolvedChains, mergedPaths,
resolvedPaths)
if err != nil {
return path{}, err
}
// Reset the resolved path
newPathLen := len(parentPath.path) + len(resolvedPath.path) - i
newResolvedPath := path{
FolderBranch: resolvedPath.FolderBranch,
path: make([]pathNode, newPathLen),
}
copy(newResolvedPath.path[:len(parentPath.path)], parentPath.path)
copy(newResolvedPath.path[len(parentPath.path):], resolvedPath.path[i:])
i = len(parentPath.path) - 1
newResolvedPath.path[i+1].Name = newName
resolvedPath = newResolvedPath
}
resolvedPaths[unmergedMostRecent] = resolvedPath
return resolvedPath, nil
}
type rootMetadataWithKeyAndTimestamp struct {
*RootMetadata
key kbfscrypto.VerifyingKey
localTimestamp time.Time
}
func (rmd rootMetadataWithKeyAndTimestamp) LastModifyingWriterVerifyingKey() kbfscrypto.VerifyingKey {
return rmd.key
}
func (rmd rootMetadataWithKeyAndTimestamp) LocalTimestamp() time.Time {
return rmd.localTimestamp
}
// makePostResolutionPaths returns the full paths to each unmerged
// pointer, taking into account any rename operations that occurred in
// the merged branch.
func (cr *ConflictResolver) makePostResolutionPaths(ctx context.Context,
md *RootMetadata, unmergedChains, mergedChains *crChains,
mergedPaths map[BlockPointer]path) (map[BlockPointer]path, error) {
err := cr.checkDone(ctx)
if err != nil {
return nil, err
}
session, err := cr.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return nil, err
}
// No need to run any identifies on these chains, since we
// have already finished all actions.
resolvedChains, err := newCRChains(
ctx, cr.config.Codec(),
[]chainMetadata{rootMetadataWithKeyAndTimestamp{md,
session.VerifyingKey, cr.config.Clock().Now()}},
&cr.fbo.blocks, false)
if err != nil {
return nil, err
}
// If there are no renames, we don't need to fix any of the paths
if len(resolvedChains.renamedOriginals) == 0 {
return mergedPaths, nil
}
resolvedPaths := make(map[BlockPointer]path)
for ptr, oldP := range mergedPaths {
p, err := cr.resolveOnePath(ctx, ptr, unmergedChains, mergedChains,
resolvedChains, mergedPaths, resolvedPaths)
if err != nil {
return nil, err
}
cr.log.CDebugf(ctx, "Resolved path for %v from %v to %v",
ptr, oldP.path, p.path)
}
return resolvedPaths, nil
}
// getOpsForLocalNotification returns the set of operations that this
// node will need to send local notifications for, in order to
// transition from the staged state to the merged state.
func (cr *ConflictResolver) getOpsForLocalNotification(ctx context.Context,
lState *lockState, md *RootMetadata,
unmergedChains, mergedChains *crChains,
updates map[BlockPointer]BlockPointer) (
[]op, error) {
dummyOp := newResolutionOp()
newPtrs := make(map[BlockPointer]bool)
for mergedMostRecent, newMostRecent := range updates {
// `updates` contains the pointer updates needed for devices
// on the merged branch to update; we have to find the
// original of the entire branch to find the corresponding
// unmerged most recent.
original, err :=
mergedChains.originalFromMostRecentOrSame(mergedMostRecent)
if err != nil {
return nil, err
}
chain, ok := unmergedChains.byOriginal[original]
if ok {
// If this unmerged node was updated in the resolution,
// track that update here.
dummyOp.AddUpdate(chain.mostRecent, newMostRecent)
} else {
dummyOp.AddUpdate(original, newMostRecent)
}
newPtrs[newMostRecent] = true
}
var ptrs []BlockPointer
chainsToUpdate := make(map[BlockPointer]BlockPointer)
chainsToAdd := make(map[BlockPointer]*crChain)
for ptr, chain := range mergedChains.byMostRecent {
if newMostRecent, ok := updates[chain.original]; ok {
ptrs = append(ptrs, newMostRecent)
chainsToUpdate[chain.mostRecent] = newMostRecent
// This update was already handled above.
continue
}
// If the node changed in both branches, but NOT in the
// resolution, make sure the local notification uses the
// unmerged most recent pointer as the unref.
original := chain.original
if c, ok := unmergedChains.byOriginal[chain.original]; ok {
original = c.mostRecent
updates[chain.original] = chain.mostRecent
// If the node pointer didn't change in the merged chain
// (e.g., due to a setattr), fast forward its most-recent
// pointer to be the unmerged most recent pointer, so that
// local notifications work correctly.
if chain.original == chain.mostRecent {
ptrs = append(ptrs, c.mostRecent)
chainsToAdd[c.mostRecent] = chain
delete(mergedChains.byMostRecent, chain.mostRecent)
chain.mostRecent = c.mostRecent
}
}
newPtrs[ptr] = true
dummyOp.AddUpdate(original, chain.mostRecent)
updates[original] = chain.mostRecent
ptrs = append(ptrs, chain.mostRecent)
}
for ptr, chain := range chainsToAdd {
mergedChains.byMostRecent[ptr] = chain
}
// If any nodes changed only in the unmerged branch, make sure we
// update the pointers in the local ops (e.g., renameOp.Renamed)
// to the latest local most recent.
for original, chain := range unmergedChains.byOriginal {
if _, ok := updates[original]; !ok {
updates[original] = chain.mostRecent
}
}
// Update the merged chains so they all have the new most recent
// pointer.
for mostRecent, newMostRecent := range chainsToUpdate {
chain, ok := mergedChains.byMostRecent[mostRecent]
if !ok {
continue
}
delete(mergedChains.byMostRecent, mostRecent)
chain.mostRecent = newMostRecent
mergedChains.byMostRecent[newMostRecent] = chain
}
// We need to get the complete set of updated merged paths, so
// that we can correctly order the chains from the root outward.
mergedNodeCache := newNodeCacheStandard(cr.fbo.folderBranch)
nodeMap, _, err := cr.fbo.blocks.SearchForNodes(
ctx, mergedNodeCache, ptrs, newPtrs,
md, md.data.Dir.BlockPointer)
if err != nil {
return nil, err
}
mergedPaths := make([]path, 0, len(nodeMap))
for _, node := range nodeMap {
if node == nil {
continue
}
mergedPaths = append(mergedPaths, mergedNodeCache.PathFromNode(node))
}
sort.Sort(crSortedPaths(mergedPaths))
ops, err := cr.makeRevertedOps(
ctx, lState, mergedPaths, mergedChains, unmergedChains)
if err != nil {
return nil, err
}
newOps, err := fixOpPointersForUpdate(ops, updates, mergedChains)
if err != nil {
return nil, err
}
newOps[0] = dummyOp
return newOps, err
}
// finalizeResolution finishes the resolution process, making the
// resolution visible to any nodes on the merged branch, and taking
// the local node out of staged mode.
func (cr *ConflictResolver) finalizeResolution(ctx context.Context,
lState *lockState, md *RootMetadata,
unmergedChains, mergedChains *crChains,
updates map[BlockPointer]BlockPointer,
bps *blockPutState, blocksToDelete []kbfsblock.ID, writerLocked bool) error {
err := cr.checkDone(ctx)
if err != nil {
return err
}
// Fix up all the block pointers in the merged ops to work well
// for local notifications. Make a dummy op at the beginning to
// convert all the merged most recent pointers into unmerged most
// recent pointers.
newOps, err := cr.getOpsForLocalNotification(
ctx, lState, md, unmergedChains,
mergedChains, updates)
if err != nil {
return err
}
cr.log.CDebugf(ctx, "Local notifications: %v", newOps)
if writerLocked {
return cr.fbo.finalizeResolutionLocked(
ctx, lState, md, bps, newOps, blocksToDelete)
}
return cr.fbo.finalizeResolution(
ctx, lState, md, bps, newOps, blocksToDelete)
}
// completeResolution pushes all the resolved blocks to the servers,
// computes all remote and local notifications, and finalizes the
// resolution process.
func (cr *ConflictResolver) completeResolution(ctx context.Context,
lState *lockState, unmergedChains, mergedChains *crChains,
unmergedPaths []path, mergedPaths map[BlockPointer]path,
mostRecentUnmergedMD, mostRecentMergedMD ImmutableRootMetadata,
lbc localBcache, newFileBlocks fileBlockMap, dirtyBcache DirtyBlockCache,
writerLocked bool) (err error) {
md, err := cr.createResolvedMD(
ctx, lState, unmergedPaths, unmergedChains,
mergedChains, mostRecentMergedMD)
if err != nil {
return err
}
resolvedPaths, err := cr.makePostResolutionPaths(ctx, md, unmergedChains,
mergedChains, mergedPaths)
if err != nil {
return err
}
err = cr.checkDone(ctx)
if err != nil {
return err
}
// Find any paths that don't have any ops associated with them,
// and avoid making new blocks for them in the resolution.
// Without this, we will end up with an extraneous block update
// for the directory with no ops. Then, if this resolution ends
// up going through ANOTHER resolution later, which sees no ops
// need resolving and short-circuits the resolution process, we
// could end up accidentally unreferencing a merged directory
// block that's still in use. See KBFS-2825 for details.
hasChildOps := make(map[BlockPointer]bool)
for _, p := range unmergedPaths {
chain := unmergedChains.byMostRecent[p.tailPointer()]
if len(chain.ops) == 0 {
continue
}
for _, pn := range p.path {
hasChildOps[pn.BlockPointer] = true
}
}
for ptr := range resolvedPaths {
if !hasChildOps[ptr] {
cr.log.CDebugf(ctx,
"Removing resolved path for op-less unmerged block pointer %v",
ptr)
delete(resolvedPaths, ptr)
}
}
updates, bps, blocksToDelete, err := cr.prepper.prepUpdateForPaths(
ctx, lState, md, unmergedChains, mergedChains,
mostRecentUnmergedMD, mostRecentMergedMD, resolvedPaths, lbc,
newFileBlocks, dirtyBcache, prepFolderCopyIndirectFileBlocks)
if err != nil {
return err
}
// Can only do this after prepUpdateForPaths, since
// prepUpdateForPaths calls fixOpPointersForUpdate, and the ops
// may be invalid until then.
err = md.data.checkValid()
if err != nil {
return err
}
defer func() {
if err != nil {
cr.fbo.fbm.cleanUpBlockState(
md.ReadOnly(), bps, blockDeleteOnMDFail)
}
}()
err = cr.checkDone(ctx)
if err != nil {
return err
}
// Put all the blocks. TODO: deal with recoverable block errors?
cacheType := DiskBlockAnyCache
if cr.config.IsSyncedTlf(md.TlfID()) {
cacheType = DiskBlockSyncCache
}
_, err = doBlockPuts(
ctx, cr.config.BlockServer(), cr.config.BlockCache(),
cr.config.Reporter(), cr.log, cr.deferLog, md.TlfID(),
md.GetTlfHandle().GetCanonicalName(), *bps, cacheType)
if err != nil {
return err
}
err = cr.finalizeResolution(ctx, lState, md, unmergedChains,
mergedChains, updates, bps, blocksToDelete, writerLocked)
if err != nil {
return err
}
return nil
}
// maybeUnstageAfterFailure abandons this branch if there was a
// conflict resolution failure due to missing blocks, caused by a
// concurrent GCOp on the main branch.
func (cr *ConflictResolver) maybeUnstageAfterFailure(ctx context.Context,
lState *lockState, mergedMDs []ImmutableRootMetadata, err error) error {
// Make sure the error is related to a missing block.
_, isBlockNotFound := err.(kbfsblock.ServerErrorBlockNonExistent)
_, isBlockDeleted := err.(kbfsblock.ServerErrorBlockDeleted)
if !isBlockNotFound && !isBlockDeleted {
return err
}
// Make sure there was a GCOp on the main branch.
foundGCOp := false
outer:
for _, rmd := range mergedMDs {
for _, op := range rmd.data.Changes.Ops {
if _, ok := op.(*GCOp); ok {
foundGCOp = true
break outer
}
}
}
if !foundGCOp {
return err
}
cr.log.CDebugf(ctx, "Unstaging due to a failed resolution: %v", err)
reportedError := CRAbandonStagedBranchError{err, cr.fbo.unmergedBID}
unstageErr := cr.fbo.unstageAfterFailedResolution(ctx, lState)
if unstageErr != nil {
cr.log.CDebugf(ctx, "Couldn't unstage: %v", unstageErr)
return err
}
head := cr.fbo.getTrustedHead(ctx, lState, mdNoCommit)
if head == (ImmutableRootMetadata{}) {
panic("maybeUnstageAfterFailure: head is nil (should be impossible)")
}
handle := head.GetTlfHandle()
cr.config.Reporter().ReportErr(
ctx, handle.GetCanonicalName(), handle.Type(), WriteMode, reportedError)
return nil
}
// CRWrapError wraps an error that happens during conflict resolution.
type CRWrapError struct {
err error
}
// Error implements the error interface for CRWrapError.
func (e CRWrapError) Error() string {
return "Conflict resolution error: " + e.err.Error()
}
func (cr *ConflictResolver) doResolve(ctx context.Context, ci conflictInput) {
var err error
ctx = cr.config.MaybeStartTrace(ctx, "CR.doResolve",
fmt.Sprintf("%s %+v", cr.fbo.folderBranch, ci))
defer func() { cr.config.MaybeFinishTrace(ctx, err) }()
cr.log.CDebugf(ctx, "Starting conflict resolution with input %+v", ci)
lState := makeFBOLockState()
defer func() {
cr.deferLog.CDebugf(ctx, "Finished conflict resolution: %+v", err)
if err != nil {
head := cr.fbo.getTrustedHead(ctx, lState, mdNoCommit)
if head == (ImmutableRootMetadata{}) {
panic("doResolve: head is nil (should be impossible)")
}
handle := head.GetTlfHandle()
cr.config.Reporter().ReportErr(
ctx, handle.GetCanonicalName(), handle.Type(),
WriteMode, CRWrapError{err})
if err == context.Canceled {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
cr.canceledCount++
// TODO: decrease threshold for pending local squashes?
if cr.canceledCount > cr.maxRevsThreshold {
cr.lockNextTime = true
}
}
} else {
// We finished successfully, so no need to lock next time.
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
cr.lockNextTime = false
cr.canceledCount = 0
}
}()
// Canceled before we even got started?
err = cr.checkDone(ctx)
if err != nil {
return
}
var mergedMDs []ImmutableRootMetadata
defer func() {
if err != nil {
// writerLock is definitely unlocked by here.
err = cr.maybeUnstageAfterFailure(ctx, lState, mergedMDs, err)
}
}()
// Check if we need to deploy the nuclear option and completely
// block unmerged writes while we try to resolve.
doLock := func() bool {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
return cr.lockNextTime
}()
if doLock {
cr.log.CDebugf(ctx, "Blocking unmerged writes due to large amounts "+
"of unresolved state")
cr.fbo.blockUnmergedWrites(lState)
defer cr.fbo.unblockUnmergedWrites(lState)
err = cr.checkDone(ctx)
if err != nil {
return
}
// Sync everything from memory to the journal.
err = cr.fbo.syncAllLocked(ctx, lState, NoExcl)
if err != nil {
return
}
// Don't let us hold the lock for too long though
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, crMaxWriteLockTime)
defer cancel()
cr.log.CDebugf(ctx, "Unmerged writes blocked")
} else {
// Sync everything from memory to the journal.
err = cr.fbo.syncAllUnlocked(ctx, lState)
if err != nil {
return
}
}
// Step 1: Build the chains for each branch, as well as the paths
// and necessary extra recreate ops. The result of this step is:
// * A set of conflict resolution "chains" for both the unmerged and
// merged branches
// * A map containing, for each changed unmerged node, the full path to
// the corresponding merged node.
// * A set of "recreate" ops that must be applied on the merged branch
// to recreate any directories that were modified in the unmerged
// branch but removed in the merged branch.
unmergedChains, mergedChains, unmergedPaths, mergedPaths, recOps,
unmergedMDs, mergedMDs, err :=
cr.buildChainsAndPaths(ctx, lState, doLock)
if err != nil {
return
}
if len(unmergedMDs) == 0 {
// TODO: This is probably due to an extra Resolve() call that
// got queued during a resolution (but too late to cancel it),
// and executed after the resolution completed successfully.
cr.log.CDebugf(ctx, "No unmerged updates at all, so we must not be "+
"unmerged after all")
return
}
if len(mergedPaths) == 0 || len(mergedMDs) == 0 {
var mostRecentMergedMD ImmutableRootMetadata
if len(mergedMDs) > 0 {
mostRecentMergedMD = mergedMDs[len(mergedMDs)-1]
} else {
branchPoint := unmergedMDs[0].Revision() - 1
mostRecentMergedMD, err = getSingleMD(ctx, cr.config, cr.fbo.id(),
kbfsmd.NullBranchID, branchPoint, kbfsmd.Merged, nil)
if err != nil {
return
}
}
// TODO: All the other variables returned by
// buildChainsAndPaths may also be nil, in which case
// completeResolution will deref a nil pointer. Fix
// this!
//
// nothing to do
cr.log.CDebugf(ctx, "No updates to resolve, so finishing")
lbc := make(localBcache)
newFileBlocks := make(fileBlockMap)
err = cr.completeResolution(ctx, lState, unmergedChains,
mergedChains, unmergedPaths, mergedPaths,
unmergedMDs[len(unmergedMDs)-1], mostRecentMergedMD, lbc,
newFileBlocks, nil, doLock)
return
}
err = cr.checkDone(ctx)
if err != nil {
return
}
if status, _, err := cr.fbo.status.getStatus(ctx, nil); err == nil {
if statusString, err := json.Marshal(status); err == nil {
ci := func() conflictInput {
cr.inputLock.Lock()
defer cr.inputLock.Unlock()
return cr.currInput
}()
cr.log.CInfof(ctx, "Current status during conflict resolution "+
"(input %v): %s", ci, statusString)
}
}
cr.log.CDebugf(ctx, "Recreate ops: %s", recOps)
mostRecentMergedMD := mergedMDs[len(mergedMDs)-1]
mostRecentMergedWriterInfo := newWriterInfo(
mostRecentMergedMD.LastModifyingWriter(),
mostRecentMergedMD.LastModifyingWriterVerifyingKey(),
mostRecentMergedMD.Revision())
// Step 2: Figure out which actions need to be taken in the merged
// branch to best reflect the unmerged changes. The result of
// this step is a map containing, for each node in the merged path
// that will be updated during conflict resolution, a set of
// "actions" to be applied to the merged branch. Each of these
// actions contains the logic needed to manipulate the data into
// the final merged state, including the resolution of any
// conflicts that occurred between the two branches.
actionMap, newUnmergedPaths, err := cr.computeActions(
ctx, unmergedChains, mergedChains, unmergedPaths, mergedPaths,
recOps, mostRecentMergedWriterInfo)
if err != nil {
return
}
// Insert the new unmerged paths as needed
if len(newUnmergedPaths) > 0 {
unmergedPaths = append(unmergedPaths, newUnmergedPaths...)
sort.Sort(crSortedPaths(unmergedPaths))
}
err = cr.checkDone(ctx)
if err != nil {
return
}
cr.log.CDebugf(ctx, "Action map: %v", actionMap)
// Step 3: Apply the actions by looking up the corresponding
// unmerged dir entry and copying it to a copy of the
// corresponding merged block. Keep these dirty block copies in a
// local dirty cache, keyed by corresponding merged most recent
// pointer.
//
// At the same time, construct two sets of ops: one that will be
// put into the final MD object that gets merged, and one that
// needs to be played through as notifications locally to get any
// local caches synchronized with the final merged state.
//
// * This will be taken care of by each crAction.updateOps()
// method, which modifies the unmerged and merged ops for a
// particular chain. After all the crActions are applied, the
// "unmerged" ops need to be pushed as part of the MD update,
// while the "merged" ops need to be applied locally.
// lbc contains the modified directory blocks we need to sync
lbc := make(localBcache)
// newFileBlocks contains the copies of the file blocks we need to
// sync. If a block is indirect, we need to put it and add new
// references for all indirect pointers inside it. If it is not
// an indirect block, just add a new reference to the block.
newFileBlocks := make(fileBlockMap)
dirtyBcache := simpleDirtyBlockCacheStandard()
// Simple dirty bcaches don't need to be shut down.
err = cr.doActions(ctx, lState, unmergedChains, mergedChains,
unmergedPaths, mergedPaths, actionMap, lbc, newFileBlocks, dirtyBcache)
if err != nil {
return
}
err = cr.checkDone(ctx)
if err != nil {
return
}
cr.log.CDebugf(ctx, "Executed all actions, %d updated directory blocks",
len(lbc))
// Step 4: finish up by syncing all the blocks, computing and
// putting the final resolved MD, and issuing all the local
// notifications.
err = cr.completeResolution(ctx, lState, unmergedChains, mergedChains,
unmergedPaths, mergedPaths, unmergedMDs[len(unmergedMDs)-1],
mostRecentMergedMD, lbc, newFileBlocks, dirtyBcache, doLock)
if err != nil {
return
}
// TODO: If conflict resolution fails after some blocks were put,
// remember these and include them in the later resolution so they
// don't count against the quota forever. (Though of course if we
// completely fail, we'll need to rely on a future complete scan
// to clean up the quota anyway . . .)
}
| 1 | 20,966 | Please put this down with the other "github.com" imports. | keybase-kbfs | go |
@@ -67,7 +67,7 @@ void nano::block_processor::add (std::shared_ptr<nano::block> block_a, uint64_t
add (info);
}
-void nano::block_processor::add (nano::unchecked_info const & info_a)
+void nano::block_processor::add (nano::unchecked_info const & info_a, bool push_front_preference)
{
if (!nano::work_validate (info_a.block->root (), info_a.block->block_work ()))
{ | 1 | #include <nano/lib/timer.hpp>
#include <nano/node/blockprocessor.hpp>
#include <nano/node/node.hpp>
#include <nano/secure/blockstore.hpp>
#include <boost/format.hpp>
#include <cassert>
std::chrono::milliseconds constexpr nano::block_processor::confirmation_request_delay;
nano::block_processor::block_processor (nano::node & node_a, nano::write_database_queue & write_database_queue_a) :
generator (node_a.config, node_a.store, node_a.wallets, node_a.vote_processor, node_a.votes_cache, node_a.network),
stopped (false),
active (false),
next_log (std::chrono::steady_clock::now ()),
node (node_a),
write_database_queue (write_database_queue_a)
{
}
nano::block_processor::~block_processor ()
{
stop ();
}
void nano::block_processor::stop ()
{
generator.stop ();
{
nano::lock_guard<std::mutex> lock (mutex);
stopped = true;
}
condition.notify_all ();
}
void nano::block_processor::flush ()
{
node.checker.flush ();
nano::unique_lock<std::mutex> lock (mutex);
while (!stopped && (have_blocks () || active))
{
condition.wait (lock);
}
blocks_filter.clear ();
}
size_t nano::block_processor::size ()
{
nano::unique_lock<std::mutex> lock (mutex);
return (blocks.size () + state_blocks.size () + forced.size ());
}
bool nano::block_processor::full ()
{
return size () > node.flags.block_processor_full_size;
}
bool nano::block_processor::half_full ()
{
return size () > node.flags.block_processor_full_size / 2;
}
void nano::block_processor::add (std::shared_ptr<nano::block> block_a, uint64_t origination)
{
nano::unchecked_info info (block_a, 0, origination, nano::signature_verification::unknown);
add (info);
}
void nano::block_processor::add (nano::unchecked_info const & info_a)
{
if (!nano::work_validate (info_a.block->root (), info_a.block->block_work ()))
{
{
auto hash (info_a.block->hash ());
auto filter_hash (filter_item (hash, info_a.block->block_signature ()));
nano::lock_guard<std::mutex> lock (mutex);
if (blocks_filter.find (filter_hash) == blocks_filter.end ())
{
if (info_a.verified == nano::signature_verification::unknown && (info_a.block->type () == nano::block_type::state || info_a.block->type () == nano::block_type::open || !info_a.account.is_zero ()))
{
state_blocks.push_back (info_a);
}
else
{
blocks.push_back (info_a);
}
blocks_filter.insert (filter_hash);
}
}
condition.notify_all ();
}
else
{
node.logger.try_log ("nano::block_processor::add called for hash ", info_a.block->hash ().to_string (), " with invalid work ", nano::to_string_hex (info_a.block->block_work ()));
assert (false && "nano::block_processor::add called with invalid work");
}
}
void nano::block_processor::force (std::shared_ptr<nano::block> block_a)
{
{
nano::lock_guard<std::mutex> lock (mutex);
forced.push_back (block_a);
}
condition.notify_all ();
}
void nano::block_processor::wait_write ()
{
nano::lock_guard<std::mutex> lock (mutex);
awaiting_write = true;
}
void nano::block_processor::process_blocks ()
{
nano::unique_lock<std::mutex> lock (mutex);
while (!stopped)
{
if (have_blocks ())
{
active = true;
lock.unlock ();
process_batch (lock);
lock.lock ();
active = false;
}
else
{
condition.notify_all ();
condition.wait (lock);
}
}
}
bool nano::block_processor::should_log (bool first_time)
{
auto result (false);
auto now (std::chrono::steady_clock::now ());
if (first_time || next_log < now)
{
next_log = now + std::chrono::seconds (15);
result = true;
}
return result;
}
bool nano::block_processor::have_blocks ()
{
assert (!mutex.try_lock ());
return !blocks.empty () || !forced.empty () || !state_blocks.empty ();
}
void nano::block_processor::verify_state_blocks (nano::unique_lock<std::mutex> & lock_a, size_t max_count)
{
assert (!mutex.try_lock ());
nano::timer<std::chrono::milliseconds> timer_l (nano::timer_state::started);
std::deque<nano::unchecked_info> items;
if (state_blocks.size () <= max_count)
{
items.swap (state_blocks);
}
else
{
for (auto i (0); i < max_count; ++i)
{
items.push_back (state_blocks.front ());
state_blocks.pop_front ();
}
assert (!state_blocks.empty ());
}
lock_a.unlock ();
if (!items.empty ())
{
auto size (items.size ());
std::vector<nano::block_hash> hashes;
hashes.reserve (size);
std::vector<unsigned char const *> messages;
messages.reserve (size);
std::vector<size_t> lengths;
lengths.reserve (size);
std::vector<nano::account> accounts;
accounts.reserve (size);
std::vector<unsigned char const *> pub_keys;
pub_keys.reserve (size);
std::vector<nano::signature> blocks_signatures;
blocks_signatures.reserve (size);
std::vector<unsigned char const *> signatures;
signatures.reserve (size);
std::vector<int> verifications;
verifications.resize (size, 0);
for (auto i (0); i < size; ++i)
{
auto & item (items[i]);
hashes.push_back (item.block->hash ());
messages.push_back (hashes.back ().bytes.data ());
lengths.push_back (sizeof (decltype (hashes)::value_type));
nano::account account (item.block->account ());
if (!item.block->link ().is_zero () && node.ledger.is_epoch_link (item.block->link ()))
{
account = node.ledger.epoch_signer (item.block->link ());
}
else if (!item.account.is_zero ())
{
account = item.account;
}
accounts.push_back (account);
pub_keys.push_back (accounts.back ().bytes.data ());
blocks_signatures.push_back (item.block->block_signature ());
signatures.push_back (blocks_signatures.back ().bytes.data ());
}
nano::signature_check_set check = { size, messages.data (), lengths.data (), pub_keys.data (), signatures.data (), verifications.data () };
node.checker.verify (check);
lock_a.lock ();
for (auto i (0); i < size; ++i)
{
assert (verifications[i] == 1 || verifications[i] == 0);
auto & item (items.front ());
if (!item.block->link ().is_zero () && node.ledger.is_epoch_link (item.block->link ()))
{
// Epoch blocks
if (verifications[i] == 1)
{
item.verified = nano::signature_verification::valid_epoch;
blocks.push_back (std::move (item));
}
else
{
// Possible regular state blocks with epoch link (send subtype)
item.verified = nano::signature_verification::unknown;
blocks.push_back (std::move (item));
}
}
else if (verifications[i] == 1)
{
// Non epoch blocks
item.verified = nano::signature_verification::valid;
blocks.push_back (std::move (item));
}
else
{
blocks_filter.erase (filter_item (hashes[i], blocks_signatures[i]));
requeue_invalid (hashes[i], item);
}
items.pop_front ();
}
if (node.config.logging.timing_logging ())
{
node.logger.try_log (boost::str (boost::format ("Batch verified %1% state blocks in %2% %3%") % size % timer_l.stop ().count () % timer_l.unit ()));
}
}
else
{
lock_a.lock ();
}
}
void nano::block_processor::process_batch (nano::unique_lock<std::mutex> & lock_a)
{
nano::timer<std::chrono::milliseconds> timer_l;
lock_a.lock ();
timer_l.start ();
// Limit state blocks verification time
{
if (!state_blocks.empty ())
{
size_t max_verification_batch (node.flags.block_processor_verification_size != 0 ? node.flags.block_processor_verification_size : 2048 * (node.config.signature_checker_threads + 1));
while (!state_blocks.empty () && timer_l.before_deadline (std::chrono::seconds (2)))
{
verify_state_blocks (lock_a, max_verification_batch);
}
}
}
lock_a.unlock ();
auto scoped_write_guard = write_database_queue.wait (nano::writer::process_batch);
auto transaction (node.store.tx_begin_write ({ nano::tables::accounts, nano::tables::cached_counts, nano::tables::change_blocks, nano::tables::frontiers, nano::tables::open_blocks, nano::tables::pending, nano::tables::receive_blocks, nano::tables::representation, nano::tables::send_blocks, nano::tables::state_blocks, nano::tables::unchecked }, { nano::tables::confirmation_height }));
timer_l.restart ();
lock_a.lock ();
// Processing blocks
auto first_time (true);
unsigned number_of_blocks_processed (0), number_of_forced_processed (0);
while ((!blocks.empty () || !forced.empty ()) && (timer_l.before_deadline (node.config.block_processor_batch_max_time) || (number_of_blocks_processed < node.flags.block_processor_batch_size)) && !awaiting_write)
{
auto log_this_record (false);
if (node.config.logging.timing_logging ())
{
if (should_log (first_time))
{
log_this_record = true;
}
}
else
{
if (((blocks.size () + state_blocks.size () + forced.size ()) > 64 && should_log (false)))
{
log_this_record = true;
}
}
if (log_this_record)
{
first_time = false;
node.logger.always_log (boost::str (boost::format ("%1% blocks (+ %2% state blocks) (+ %3% forced) in processing queue") % blocks.size () % state_blocks.size () % forced.size ()));
}
nano::unchecked_info info;
nano::block_hash hash (0);
bool force (false);
if (forced.empty ())
{
info = blocks.front ();
blocks.pop_front ();
hash = info.block->hash ();
blocks_filter.erase (filter_item (hash, info.block->block_signature ()));
}
else
{
info = nano::unchecked_info (forced.front (), 0, nano::seconds_since_epoch (), nano::signature_verification::unknown);
forced.pop_front ();
hash = info.block->hash ();
force = true;
number_of_forced_processed++;
}
lock_a.unlock ();
if (force)
{
auto successor (node.ledger.successor (transaction, info.block->qualified_root ()));
if (successor != nullptr && successor->hash () != hash)
{
// Replace our block with the winner and roll back any dependent blocks
node.logger.always_log (boost::str (boost::format ("Rolling back %1% and replacing with %2%") % successor->hash ().to_string () % hash.to_string ()));
std::vector<std::shared_ptr<nano::block>> rollback_list;
if (node.ledger.rollback (transaction, successor->hash (), rollback_list))
{
node.logger.always_log (nano::severity_level::error, boost::str (boost::format ("Failed to roll back %1% because it or a successor was confirmed") % successor->hash ().to_string ()));
}
else
{
node.logger.always_log (boost::str (boost::format ("%1% blocks rolled back") % rollback_list.size ()));
}
// Deleting from votes cache & wallet work watcher, stop active transaction
for (auto & i : rollback_list)
{
node.votes_cache.remove (i->hash ());
node.wallets.watcher->remove (i);
// Stop all rolled back active transactions except initial
if (i->hash () != successor->hash ())
{
node.active.erase (*i);
}
}
}
}
number_of_blocks_processed++;
process_one (transaction, info);
lock_a.lock ();
/* Verify more state blocks if blocks deque is empty
Because verification is long process, avoid large deque verification inside of write transaction */
if (blocks.empty () && !state_blocks.empty ())
{
verify_state_blocks (lock_a, 256 * (node.config.signature_checker_threads + 1));
}
}
awaiting_write = false;
lock_a.unlock ();
if (node.config.logging.timing_logging () && number_of_blocks_processed != 0)
{
node.logger.always_log (boost::str (boost::format ("Processed %1% blocks (%2% blocks were forced) in %3% %4%") % number_of_blocks_processed % number_of_forced_processed % timer_l.stop ().count () % timer_l.unit ()));
}
}
void nano::block_processor::process_live (nano::block_hash const & hash_a, std::shared_ptr<nano::block> block_a, const bool watch_work_a)
{
// Add to work watcher to prevent dropping the election
if (watch_work_a)
{
node.wallets.watcher->add (block_a);
}
// Start collecting quorum on block
node.active.insert (block_a, false);
// Announce block contents to the network
node.network.flood_block (block_a, false);
if (node.config.enable_voting && node.wallets.rep_counts ().voting > 0)
{
// Announce our weighted vote to the network
generator.add (hash_a);
}
}
nano::process_return nano::block_processor::process_one (nano::write_transaction const & transaction_a, nano::unchecked_info info_a, const bool watch_work_a)
{
nano::process_return result;
auto hash (info_a.block->hash ());
result = node.ledger.process (transaction_a, *(info_a.block), info_a.verified);
switch (result.code)
{
case nano::process_result::progress:
{
release_assert (info_a.account.is_zero () || info_a.account == result.account);
if (node.config.logging.ledger_logging ())
{
std::string block;
info_a.block->serialize_json (block, node.config.logging.single_line_record ());
node.logger.try_log (boost::str (boost::format ("Processing block %1%: %2%") % hash.to_string () % block));
}
if (info_a.modified > nano::seconds_since_epoch () - 300 && node.block_arrival.recent (hash))
{
process_live (hash, info_a.block, watch_work_a);
}
queue_unchecked (transaction_a, hash);
break;
}
case nano::process_result::gap_previous:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Gap previous for: %1%") % hash.to_string ()));
}
info_a.verified = result.verified;
if (info_a.modified == 0)
{
info_a.modified = nano::seconds_since_epoch ();
}
nano::unchecked_key unchecked_key (info_a.block->previous (), hash);
auto exists = node.store.unchecked_exists (transaction_a, unchecked_key);
node.store.unchecked_put (transaction_a, unchecked_key, info_a);
if (!exists)
{
++node.ledger.cache.unchecked_count;
}
node.gap_cache.add (hash);
node.stats.inc (nano::stat::type::ledger, nano::stat::detail::gap_previous);
break;
}
case nano::process_result::gap_source:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Gap source for: %1%") % hash.to_string ()));
}
info_a.verified = result.verified;
if (info_a.modified == 0)
{
info_a.modified = nano::seconds_since_epoch ();
}
nano::unchecked_key unchecked_key (node.ledger.block_source (transaction_a, *(info_a.block)), hash);
auto exists = node.store.unchecked_exists (transaction_a, unchecked_key);
node.store.unchecked_put (transaction_a, unchecked_key, info_a);
if (!exists)
{
++node.ledger.cache.unchecked_count;
}
node.gap_cache.add (hash);
node.stats.inc (nano::stat::type::ledger, nano::stat::detail::gap_source);
break;
}
case nano::process_result::old:
{
if (node.config.logging.ledger_duplicate_logging ())
{
node.logger.try_log (boost::str (boost::format ("Old for: %1%") % hash.to_string ()));
}
queue_unchecked (transaction_a, hash);
node.active.update_difficulty (info_a.block, transaction_a);
node.stats.inc (nano::stat::type::ledger, nano::stat::detail::old);
break;
}
case nano::process_result::bad_signature:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Bad signature for: %1%") % hash.to_string ()));
}
requeue_invalid (hash, info_a);
break;
}
case nano::process_result::negative_spend:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Negative spend for: %1%") % hash.to_string ()));
}
break;
}
case nano::process_result::unreceivable:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Unreceivable for: %1%") % hash.to_string ()));
}
break;
}
case nano::process_result::fork:
{
node.process_fork (transaction_a, info_a.block);
node.stats.inc (nano::stat::type::ledger, nano::stat::detail::fork);
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Fork for: %1% root: %2%") % hash.to_string () % info_a.block->root ().to_string ()));
}
break;
}
case nano::process_result::opened_burn_account:
{
node.logger.always_log (boost::str (boost::format ("*** Rejecting open block for burn account ***: %1%") % hash.to_string ()));
break;
}
case nano::process_result::balance_mismatch:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Balance mismatch for: %1%") % hash.to_string ()));
}
break;
}
case nano::process_result::representative_mismatch:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Representative mismatch for: %1%") % hash.to_string ()));
}
break;
}
case nano::process_result::block_position:
{
if (node.config.logging.ledger_logging ())
{
node.logger.try_log (boost::str (boost::format ("Block %1% cannot follow predecessor %2%") % hash.to_string () % info_a.block->previous ().to_string ()));
}
break;
}
}
return result;
}
nano::process_return nano::block_processor::process_one (nano::write_transaction const & transaction_a, std::shared_ptr<nano::block> block_a, const bool watch_work_a)
{
nano::unchecked_info info (block_a, block_a->account (), 0, nano::signature_verification::unknown);
auto result (process_one (transaction_a, info, watch_work_a));
return result;
}
void nano::block_processor::queue_unchecked (nano::write_transaction const & transaction_a, nano::block_hash const & hash_a)
{
auto unchecked_blocks (node.store.unchecked_get (transaction_a, hash_a));
for (auto & info : unchecked_blocks)
{
if (!node.flags.disable_block_processor_unchecked_deletion)
{
if (!node.store.unchecked_del (transaction_a, nano::unchecked_key (hash_a, info.block->hash ())))
{
assert (node.ledger.cache.unchecked_count > 0);
--node.ledger.cache.unchecked_count;
}
}
add (info);
}
node.gap_cache.erase (hash_a);
}
nano::block_hash nano::block_processor::filter_item (nano::block_hash const & hash_a, nano::signature const & signature_a)
{
static nano::random_constants constants;
nano::block_hash result;
blake2b_state state;
blake2b_init (&state, sizeof (result.bytes));
blake2b_update (&state, constants.not_an_account.bytes.data (), constants.not_an_account.bytes.size ());
blake2b_update (&state, signature_a.bytes.data (), signature_a.bytes.size ());
blake2b_update (&state, hash_a.bytes.data (), hash_a.bytes.size ());
blake2b_final (&state, result.bytes.data (), sizeof (result.bytes));
return result;
}
void nano::block_processor::requeue_invalid (nano::block_hash const & hash_a, nano::unchecked_info const & info_a)
{
assert (hash_a == info_a.block->hash ());
auto attempt (node.bootstrap_initiator.current_attempt ());
if (attempt != nullptr && attempt->mode == nano::bootstrap_mode::lazy)
{
attempt->lazy_requeue (hash_a, info_a.block->previous (), info_a.confirmed);
}
}
| 1 | 16,272 | Minor but probably want `push_front_preference` to have a trailing `_a` to be consistent with the other parameter | nanocurrency-nano-node | cpp |
@@ -53,8 +53,16 @@ public class InclusiveManifestEvaluator {
}
public InclusiveManifestEvaluator(PartitionSpec spec, Expression rowFilter) {
+ this(spec, rowFilter, true);
+ }
+
+ public InclusiveManifestEvaluator(PartitionSpec spec, Expression rowFilter, boolean caseSensitive) {
this.struct = spec.partitionType();
- this.expr = Binder.bind(struct, rewriteNot(Projections.inclusive(spec).project(rowFilter)), true);
+ this.expr = Binder.bind(
+ struct,
+ rewriteNot(Projections.inclusive(spec, caseSensitive).project(rowFilter)),
+ caseSensitive
+ );
}
/** | 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 com.netflix.iceberg.expressions;
import com.netflix.iceberg.ManifestFile;
import com.netflix.iceberg.ManifestFile.PartitionFieldSummary;
import com.netflix.iceberg.PartitionSpec;
import com.netflix.iceberg.expressions.ExpressionVisitors.BoundExpressionVisitor;
import com.netflix.iceberg.types.Conversions;
import com.netflix.iceberg.types.Types.StructType;
import java.nio.ByteBuffer;
import java.util.List;
import static com.netflix.iceberg.expressions.Expressions.rewriteNot;
/**
* Evaluates an {@link Expression} on a {@link ManifestFile} to test whether the file contains
* matching partitions.
* <p>
* This evaluation is inclusive: it returns true if a file may match and false if it cannot match.
* <p>
* Files are passed to {@link #eval(ManifestFile)}, which returns true if the manifest may contain
* data files that match the partition expression. Manifest files may be skipped if and only if the
* return value of {@code eval} is false.
*/
public class InclusiveManifestEvaluator {
private final StructType struct;
private final Expression expr;
private transient ThreadLocal<ManifestEvalVisitor> visitors = null;
private ManifestEvalVisitor visitor() {
if (visitors == null) {
this.visitors = ThreadLocal.withInitial(ManifestEvalVisitor::new);
}
return visitors.get();
}
public InclusiveManifestEvaluator(PartitionSpec spec, Expression rowFilter) {
this.struct = spec.partitionType();
this.expr = Binder.bind(struct, rewriteNot(Projections.inclusive(spec).project(rowFilter)), true);
}
/**
* Test whether the file may contain records that match the expression.
*
* @param manifest a manifest file
* @return false if the file cannot contain rows that match the expression, true otherwise.
*/
public boolean eval(ManifestFile manifest) {
return visitor().eval(manifest);
}
private static final boolean ROWS_MIGHT_MATCH = true;
private static final boolean ROWS_CANNOT_MATCH = false;
private class ManifestEvalVisitor extends BoundExpressionVisitor<Boolean> {
private List<PartitionFieldSummary> stats = null;
private boolean eval(ManifestFile manifest) {
this.stats = manifest.partitions();
if (stats == null) {
return ROWS_MIGHT_MATCH;
}
return ExpressionVisitors.visit(expr, this);
}
@Override
public Boolean alwaysTrue() {
return ROWS_MIGHT_MATCH; // all rows match
}
@Override
public Boolean alwaysFalse() {
return ROWS_CANNOT_MATCH; // all rows fail
}
@Override
public Boolean not(Boolean result) {
return !result;
}
@Override
public Boolean and(Boolean leftResult, Boolean rightResult) {
return leftResult && rightResult;
}
@Override
public Boolean or(Boolean leftResult, Boolean rightResult) {
return leftResult || rightResult;
}
@Override
public <T> Boolean isNull(BoundReference<T> ref) {
// no need to check whether the field is required because binding evaluates that case
// if the column has no null values, the expression cannot match
if (!stats.get(ref.pos()).containsNull()) {
return ROWS_CANNOT_MATCH;
}
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean notNull(BoundReference<T> ref) {
// containsNull encodes whether at least one partition value is null, lowerBound is null if
// all partition values are null.
ByteBuffer lowerBound = stats.get(ref.pos()).lowerBound();
if (lowerBound == null) {
return ROWS_CANNOT_MATCH; // all values are null
}
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean lt(BoundReference<T> ref, Literal<T> lit) {
ByteBuffer lowerBound = stats.get(ref.pos()).lowerBound();
if (lowerBound == null) {
return ROWS_CANNOT_MATCH; // values are all null
}
T lower = Conversions.fromByteBuffer(ref.type(), lowerBound);
int cmp = lit.comparator().compare(lower, lit.value());
if (cmp >= 0) {
return ROWS_CANNOT_MATCH;
}
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean ltEq(BoundReference<T> ref, Literal<T> lit) {
ByteBuffer lowerBound = stats.get(ref.pos()).lowerBound();
if (lowerBound == null) {
return ROWS_CANNOT_MATCH; // values are all null
}
T lower = Conversions.fromByteBuffer(ref.type(), lowerBound);
int cmp = lit.comparator().compare(lower, lit.value());
if (cmp > 0) {
return ROWS_CANNOT_MATCH;
}
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean gt(BoundReference<T> ref, Literal<T> lit) {
ByteBuffer upperBound = stats.get(ref.pos()).upperBound();
if (upperBound == null) {
return ROWS_CANNOT_MATCH; // values are all null
}
T upper = Conversions.fromByteBuffer(ref.type(), upperBound);
int cmp = lit.comparator().compare(upper, lit.value());
if (cmp <= 0) {
return ROWS_CANNOT_MATCH;
}
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean gtEq(BoundReference<T> ref, Literal<T> lit) {
ByteBuffer upperBound = stats.get(ref.pos()).upperBound();
if (upperBound == null) {
return ROWS_CANNOT_MATCH; // values are all null
}
T upper = Conversions.fromByteBuffer(ref.type(), upperBound);
int cmp = lit.comparator().compare(upper, lit.value());
if (cmp < 0) {
return ROWS_CANNOT_MATCH;
}
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean eq(BoundReference<T> ref, Literal<T> lit) {
PartitionFieldSummary fieldStats = stats.get(ref.pos());
if (fieldStats.lowerBound() == null) {
return ROWS_CANNOT_MATCH; // values are all null and literal cannot contain null
}
T lower = Conversions.fromByteBuffer(ref.type(), fieldStats.lowerBound());
int cmp = lit.comparator().compare(lower, lit.value());
if (cmp > 0) {
return ROWS_CANNOT_MATCH;
}
T upper = Conversions.fromByteBuffer(ref.type(), fieldStats.upperBound());
cmp = lit.comparator().compare(upper, lit.value());
if (cmp < 0) {
return ROWS_CANNOT_MATCH;
}
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean notEq(BoundReference<T> ref, Literal<T> lit) {
// because the bounds are not necessarily a min or max value, this cannot be answered using
// them. notEq(col, X) with (X, Y) doesn't guarantee that X is a value in col.
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean in(BoundReference<T> ref, Literal<T> lit) {
return ROWS_MIGHT_MATCH;
}
@Override
public <T> Boolean notIn(BoundReference<T> ref, Literal<T> lit) {
return ROWS_MIGHT_MATCH;
}
}
}
| 1 | 12,567 | Nit: the formatting is a bit off. I would expect this to be 2 indentations from `this.expr = ...` but this is 8 spaces, not 4. Also, most places leave the `);` on the last line of the method arguments. | apache-iceberg | java |
@@ -14,8 +14,8 @@
*/
package com.google.api.codegen.transformer.csharp;
-import com.google.api.codegen.transformer.ApiMethodTransformer;
import com.google.api.codegen.transformer.MethodTransformerContext;
+import com.google.api.codegen.transformer.StaticLangApiMethodTransformer;
import com.google.api.codegen.viewmodel.SimpleParamDocView;
import com.google.api.codegen.viewmodel.StaticLangApiMethodView;
import com.google.api.tools.framework.model.TypeRef; | 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.csharp;
import com.google.api.codegen.transformer.ApiMethodTransformer;
import com.google.api.codegen.transformer.MethodTransformerContext;
import com.google.api.codegen.viewmodel.SimpleParamDocView;
import com.google.api.codegen.viewmodel.StaticLangApiMethodView;
import com.google.api.tools.framework.model.TypeRef;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.apache.commons.lang3.NotImplementedException;
public class CSharpApiMethodTransformer extends ApiMethodTransformer {
@Override
protected void setServiceResponseTypeName(
MethodTransformerContext context, StaticLangApiMethodView.Builder methodViewBuilder) {
String responseTypeName =
context.getTypeTable().getAndSaveNicknameFor(context.getMethod().getOutputType());
methodViewBuilder.serviceResponseTypeName(responseTypeName);
}
@Override
public List<SimpleParamDocView> getRequestObjectParamDocs(
MethodTransformerContext context, TypeRef typeRef) {
switch (context.getMethodConfig().getGrpcStreamingType()) {
case NonStreaming:
SimpleParamDocView doc =
SimpleParamDocView.newBuilder()
.paramName("request")
.typeName(context.getTypeTable().getAndSaveNicknameFor(typeRef))
.lines(
ImmutableList.of(
"The request object containing all of the parameters for the API call."))
.build();
return ImmutableList.of(doc);
case BidiStreaming:
SimpleParamDocView callSettingsDoc =
SimpleParamDocView.newBuilder()
.paramName("callSettings")
.typeName("CallSettings")
.lines(ImmutableList.of("If not null, applies overrides to this RPC call."))
.build();
SimpleParamDocView streamingSettingsDoc =
SimpleParamDocView.newBuilder()
.paramName("streamingSettings")
.typeName("BidirectionalStreamingSettings")
.lines(
ImmutableList.of("If not null, applies streaming overrides to this RPC call."))
.build();
return ImmutableList.of(callSettingsDoc, streamingSettingsDoc);
default:
throw new NotImplementedException(
"Cannot handle streaming type: " + context.getMethodConfig().getGrpcStreamingType());
}
}
}
| 1 | 20,946 | Ack, @chrisdunelm snuck this class extension past me. This is not a pattern I want to have used... | googleapis-gapic-generator | java |
@@ -67,7 +67,16 @@ def main(global_config, config=None, **settings):
# Scan Kinto views.
kwargs = {}
flush_enabled = asbool(settings.get('flush_endpoint_enabled'))
- if not flush_enabled:
+
+ if flush_enabled:
+ config.add_api_capability(
+ "flush_endpoint",
+ description="The __flush__ endpoint can be used to remove all "
+ "data from all backends.",
+ url="http://kinto.readthedocs.org/en/latest/configuration/"
+ "settings.html#activating-the-flush-endpoint"
+ )
+ else:
kwargs['ignore'] = 'kinto.views.flush'
config.scan("kinto.views", **kwargs)
| 1 | import pkg_resources
import logging
import cliquet
from pyramid.config import Configurator
from pyramid.settings import asbool
from pyramid.security import Authenticated
from kinto.authorization import RouteFactory
# Module version, as defined in PEP-0396.
__version__ = pkg_resources.get_distribution(__package__).version
# Implemented HTTP API Version
HTTP_API_VERSION = '1.4'
# Main kinto logger
logger = logging.getLogger(__name__)
DEFAULT_SETTINGS = {
'retry_after_seconds': 3,
'cache_backend': 'cliquet.cache.memory',
'permission_backend': 'cliquet.permission.memory',
'storage_backend': 'cliquet.storage.memory',
'project_docs': 'https://kinto.readthedocs.org/',
'bucket_create_principals': Authenticated,
'multiauth.authorization_policy': (
'kinto.authorization.AuthorizationPolicy'),
'experimental_collection_schema_validation': 'False',
'http_api_version': HTTP_API_VERSION
}
def main(global_config, config=None, **settings):
if not config:
config = Configurator(settings=settings, root_factory=RouteFactory)
# Force project name, since it determines settings prefix.
config.add_settings({'cliquet.project_name': 'kinto'})
cliquet.initialize(config,
version=__version__,
default_settings=DEFAULT_SETTINGS)
settings = config.get_settings()
# In Kinto API 1.x, a default bucket is available.
# Force its inclusion if not specified in settings.
if 'kinto.plugins.default_bucket' not in settings['includes']:
config.include('kinto.plugins.default_bucket')
# Retro-compatibility with first Kinto clients.
config.registry.public_settings.add('cliquet.batch_max_requests')
# Expose capability
schema_enabled = asbool(
settings['experimental_collection_schema_validation']
)
if schema_enabled:
config.add_api_capability(
"schema",
description="Validates collection records with JSON schemas.",
url="http://kinto.readthedocs.org/en/latest/api/1.x/"
"collections.html#collection-json-schema")
# Scan Kinto views.
kwargs = {}
flush_enabled = asbool(settings.get('flush_endpoint_enabled'))
if not flush_enabled:
kwargs['ignore'] = 'kinto.views.flush'
config.scan("kinto.views", **kwargs)
app = config.make_wsgi_app()
# Install middleware (idempotent if disabled)
return cliquet.install_middlewares(app, settings)
| 1 | 8,935 | nitpick: I wonder if we should name it `flush` only (?) | Kinto-kinto | py |
@@ -0,0 +1,19 @@
+package hub
+
+import "github.com/prometheus/client_golang/prometheus"
+
+var (
+ tasksGauge = prometheus.NewGauge(prometheus.GaugeOpts{
+ Name: "sonm_tasks_current",
+ Help: "Number of currently running tasks",
+ })
+ dealsGauge = prometheus.NewGauge(prometheus.GaugeOpts{
+ Name: "sonm_deals_current",
+ Help: "Number of currently running tasks",
+ })
+)
+
+func init() {
+ prometheus.MustRegister(tasksGauge)
+ prometheus.MustRegister(dealsGauge)
+} | 1 | 1 | 6,229 | Why gauges, not counters? | sonm-io-core | go |
|
@@ -45,7 +45,7 @@ const (
// hash of origin cluster name and <server> is 6 characters hash of origin server pub key.
gwReplyPrefix = "_GR_."
gwReplyPrefixLen = len(gwReplyPrefix)
- gwHashLen = 6
+ gwHashLen = sysHashLen
gwClusterOffset = gwReplyPrefixLen
gwServerOffset = gwClusterOffset + gwHashLen + 1
gwSubjectOffset = gwServerOffset + gwHashLen + 1 | 1 | // Copyright 2018-2020 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"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"math/rand"
"net"
"net/url"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
)
const (
defaultSolicitGatewaysDelay = time.Second
defaultGatewayConnectDelay = time.Second
defaultGatewayReconnectDelay = time.Second
defaultGatewayRecentSubExpiration = 250 * time.Millisecond
defaultGatewayMaxRUnsubBeforeSwitch = 1000
oldGWReplyPrefix = "$GR."
oldGWReplyPrefixLen = len(oldGWReplyPrefix)
oldGWReplyStart = oldGWReplyPrefixLen + 5 // len of prefix above + len of hash (4) + "."
// The new prefix is "_GR_.<cluster>.<server>." where <cluster> is 6 characters
// hash of origin cluster name and <server> is 6 characters hash of origin server pub key.
gwReplyPrefix = "_GR_."
gwReplyPrefixLen = len(gwReplyPrefix)
gwHashLen = 6
gwClusterOffset = gwReplyPrefixLen
gwServerOffset = gwClusterOffset + gwHashLen + 1
gwSubjectOffset = gwServerOffset + gwHashLen + 1
// Gateway connections send PINGs regardless of traffic. The interval is
// either Options.PingInterval or this value, whichever is the smallest.
gwMaxPingInterval = 15 * time.Second
)
var (
gatewayConnectDelay = defaultGatewayConnectDelay
gatewayReconnectDelay = defaultGatewayReconnectDelay
gatewayMaxRUnsubBeforeSwitch = defaultGatewayMaxRUnsubBeforeSwitch
gatewaySolicitDelay = int64(defaultSolicitGatewaysDelay)
gatewayMaxPingInterval = gwMaxPingInterval
)
// Warning when user configures gateway TLS insecure
const gatewayTLSInsecureWarning = "TLS certificate chain and hostname of solicited gateways will not be verified. DO NOT USE IN PRODUCTION!"
// SetGatewaysSolicitDelay sets the initial delay before gateways
// connections are initiated.
// Used by tests.
func SetGatewaysSolicitDelay(delay time.Duration) {
atomic.StoreInt64(&gatewaySolicitDelay, int64(delay))
}
// ResetGatewaysSolicitDelay resets the initial delay before gateways
// connections are initiated to its default values.
// Used by tests.
func ResetGatewaysSolicitDelay() {
atomic.StoreInt64(&gatewaySolicitDelay, int64(defaultSolicitGatewaysDelay))
}
const (
gatewayCmdGossip byte = 1
gatewayCmdAllSubsStart byte = 2
gatewayCmdAllSubsComplete byte = 3
)
// GatewayInterestMode represents an account interest mode for a gateway connection
type GatewayInterestMode byte
// GatewayInterestMode values
const (
// optimistic is the default mode where a cluster will send
// to a gateway unless it is been told that there is no interest
// (this is for plain subscribers only).
Optimistic GatewayInterestMode = iota
// transitioning is when a gateway has to send too many
// no interest on subjects to the remote and decides that it is
// now time to move to modeInterestOnly (this is on a per account
// basis).
Transitioning
// interestOnly means that a cluster sends all it subscriptions
// interest to the gateway, which in return does not send a message
// unless it knows that there is explicit interest.
InterestOnly
)
func (im GatewayInterestMode) String() string {
switch im {
case Optimistic:
return "Optimistic"
case InterestOnly:
return "Interest-Only"
case Transitioning:
return "Transitioning"
default:
return "Unknown"
}
}
type srvGateway struct {
totalQSubs int64 //total number of queue subs in all remote gateways (used with atomic operations)
sync.RWMutex
enabled bool // Immutable, true if both a name and port are configured
name string // Name of the Gateway on this server
out map[string]*client // outbound gateways
outo []*client // outbound gateways maintained in an order suitable for sending msgs (currently based on RTT)
in map[uint64]*client // inbound gateways
remotes map[string]*gatewayCfg // Config of remote gateways
URLs refCountedUrlSet // Set of all Gateway URLs in the cluster
URL string // This server gateway URL (after possible random port is resolved)
info *Info // Gateway Info protocol
infoJSON []byte // Marshal'ed Info protocol
runknown bool // Rejects unknown (not configured) gateway connections
replyPfx []byte // Will be "$GNR.<1:reserved>.<8:cluster hash>.<8:server hash>."
// For backward compatibility
oldReplyPfx []byte
oldHash []byte
// We maintain the interest of subjects and queues per account.
// For a given account, entries in the map could be something like this:
// foo.bar {n: 3} // 3 subs on foo.bar
// foo.> {n: 6} // 6 subs on foo.>
// foo bar {n: 1, q: true} // 1 qsub on foo, queue bar
// foo baz {n: 3, q: true} // 3 qsubs on foo, queue baz
pasi struct {
// Protect map since accessed from different go-routine and avoid
// possible race resulting in RS+ being sent before RS- resulting
// in incorrect interest suppression.
// Will use while sending QSubs (on GW connection accept) and when
// switching to the send-all-subs mode.
sync.Mutex
m map[string]map[string]*sitally
}
// This is to track recent subscriptions for a given connection
rsubs sync.Map
resolver netResolver // Used to resolve host name before calling net.Dial()
sqbsz int // Max buffer size to send queue subs protocol. Used for testing.
recSubExp time.Duration // For how long do we check if there is a subscription match for a message with reply
}
// Subject interest tally. Also indicates if the key in the map is a
// queue or not.
type sitally struct {
n int32 // number of subscriptions directly matching
q bool // indicate that this is a queue
}
type gatewayCfg struct {
sync.RWMutex
*RemoteGatewayOpts
hash []byte
oldHash []byte
urls map[string]*url.URL
connAttempts int
tlsName string
implicit bool
varzUpdateURLs bool // Tells monitoring code to update URLs when varz is inspected.
}
// Struct for client's gateway related fields
type gateway struct {
name string
outbound bool
cfg *gatewayCfg
connectURL *url.URL // Needed when sending CONNECT after receiving INFO from remote
outsim *sync.Map // Per-account subject interest (or no-interest) (outbound conn)
insim map[string]*insie // Per-account subject no-interest sent or modeInterestOnly mode (inbound conn)
// Set/check in readLoop without lock. This is to know that an inbound has sent the CONNECT protocol first
connected bool
// Set to true if outbound is to a server that only knows about $GR, not $GNR
useOldPrefix bool
}
// Outbound subject interest entry.
type outsie struct {
sync.RWMutex
// Indicate that all subs should be stored. This is
// set to true when receiving the command from the
// remote that we are about to receive all its subs.
mode GatewayInterestMode
// If not nil, used for no-interest for plain subs.
// If a subject is present in this map, it means that
// the remote is not interested in that subject.
// When we have received the command that says that
// the remote has sent all its subs, this is set to nil.
ni map[string]struct{}
// Contains queue subscriptions when in optimistic mode,
// and all subs when pk is > 0.
sl *Sublist
// Number of queue subs
qsubs int
}
// Inbound subject interest entry.
// If `ni` is not nil, it stores the subjects for which an
// RS- was sent to the remote gateway. When a subscription
// is created, this is used to know if we need to send
// an RS+ to clear the no-interest in the remote.
// When an account is switched to modeInterestOnly (we send
// all subs of an account to the remote), then `ni` is nil and
// when all subs have been sent, mode is set to modeInterestOnly
type insie struct {
ni map[string]struct{} // Record if RS- was sent for given subject
mode GatewayInterestMode
}
type gwReplyMap struct {
ms string
exp int64
}
// clone returns a deep copy of the RemoteGatewayOpts object
func (r *RemoteGatewayOpts) clone() *RemoteGatewayOpts {
if r == nil {
return nil
}
clone := &RemoteGatewayOpts{
Name: r.Name,
URLs: deepCopyURLs(r.URLs),
}
if r.TLSConfig != nil {
clone.TLSConfig = r.TLSConfig.Clone()
clone.TLSTimeout = r.TLSTimeout
}
return clone
}
// Ensure that gateway is properly configured.
func validateGatewayOptions(o *Options) error {
if o.Gateway.Name == "" && o.Gateway.Port == 0 {
return nil
}
if o.Gateway.Name == "" {
return fmt.Errorf("gateway has no name")
}
if o.Gateway.Port == 0 {
return fmt.Errorf("gateway %q has no port specified (select -1 for random port)", o.Gateway.Name)
}
for i, g := range o.Gateway.Gateways {
if g.Name == "" {
return fmt.Errorf("gateway in the list %d has no name", i)
}
if len(g.URLs) == 0 {
return fmt.Errorf("gateway %q has no URL", g.Name)
}
}
return nil
}
// Computes a hash of 8 characters for the name.
// This will be used for routing of replies.
func getHash(name string) []byte {
sha := sha256.New()
sha.Write([]byte(name))
b := sha.Sum(nil)
for i := 0; i < gwHashLen; i++ {
b[i] = digits[int(b[i]%base)]
}
return b[:gwHashLen]
}
func getOldHash(name string) []byte {
sha := sha256.New()
sha.Write([]byte(name))
fullHash := []byte(fmt.Sprintf("%x", sha.Sum(nil)))
return fullHash[:4]
}
// Initialize the s.gateway structure. We do this even if the server
// does not have a gateway configured. In some part of the code, the
// server will check the number of outbound gateways, etc.. and so
// we don't have to check if s.gateway is nil or not.
func (s *Server) newGateway(opts *Options) error {
gateway := &srvGateway{
name: opts.Gateway.Name,
out: make(map[string]*client),
outo: make([]*client, 0, 4),
in: make(map[uint64]*client),
remotes: make(map[string]*gatewayCfg),
URLs: make(refCountedUrlSet),
resolver: opts.Gateway.resolver,
runknown: opts.Gateway.RejectUnknown,
oldHash: getOldHash(opts.Gateway.Name),
}
gateway.Lock()
defer gateway.Unlock()
s.hash = getHash(s.info.ID)
clusterHash := getHash(opts.Gateway.Name)
prefix := make([]byte, 0, gwSubjectOffset)
prefix = append(prefix, gwReplyPrefix...)
prefix = append(prefix, clusterHash...)
prefix = append(prefix, '.')
prefix = append(prefix, s.hash...)
prefix = append(prefix, '.')
gateway.replyPfx = prefix
prefix = make([]byte, 0, oldGWReplyStart)
prefix = append(prefix, oldGWReplyPrefix...)
prefix = append(prefix, gateway.oldHash...)
prefix = append(prefix, '.')
gateway.oldReplyPfx = prefix
gateway.pasi.m = make(map[string]map[string]*sitally)
if gateway.resolver == nil {
gateway.resolver = netResolver(net.DefaultResolver)
}
// Create remote gateways
for _, rgo := range opts.Gateway.Gateways {
// Ignore if there is a remote gateway with our name.
if rgo.Name == gateway.name {
continue
}
cfg := &gatewayCfg{
RemoteGatewayOpts: rgo.clone(),
hash: getHash(rgo.Name),
oldHash: getOldHash(rgo.Name),
urls: make(map[string]*url.URL, len(rgo.URLs)),
}
if opts.Gateway.TLSConfig != nil && cfg.TLSConfig == nil {
cfg.TLSConfig = opts.Gateway.TLSConfig.Clone()
}
if cfg.TLSTimeout == 0 {
cfg.TLSTimeout = opts.Gateway.TLSTimeout
}
for _, u := range rgo.URLs {
// For TLS, look for a hostname that we can use for TLSConfig.ServerName
cfg.saveTLSHostname(u)
cfg.urls[u.Host] = u
}
gateway.remotes[cfg.Name] = cfg
}
gateway.sqbsz = opts.Gateway.sendQSubsBufSize
if gateway.sqbsz == 0 {
gateway.sqbsz = maxBufSize
}
gateway.recSubExp = defaultGatewayRecentSubExpiration
gateway.enabled = opts.Gateway.Name != "" && opts.Gateway.Port != 0
s.gateway = gateway
return nil
}
// Update remote gateways TLS configurations after a config reload.
func (g *srvGateway) updateRemotesTLSConfig(opts *Options) {
g.Lock()
defer g.Unlock()
for _, ro := range opts.Gateway.Gateways {
if ro.Name == g.name {
continue
}
if cfg, ok := g.remotes[ro.Name]; ok {
cfg.Lock()
// If TLS config is in remote, use that one, otherwise,
// use the TLS config from the main block.
if ro.TLSConfig != nil {
cfg.TLSConfig = ro.TLSConfig.Clone()
} else if opts.Gateway.TLSConfig != nil {
cfg.TLSConfig = opts.Gateway.TLSConfig.Clone()
}
cfg.Unlock()
}
}
}
// Returns the Gateway's name of this server.
func (g *srvGateway) getName() string {
g.RLock()
n := g.name
g.RUnlock()
return n
}
// Returns if this server rejects connections from gateways that are not
// explicitly configured.
func (g *srvGateway) rejectUnknown() bool {
g.RLock()
reject := g.runknown
g.RUnlock()
return reject
}
// Starts the gateways accept loop and solicit explicit gateways
// after an initial delay. This delay is meant to give a chance to
// the cluster to form and this server gathers gateway URLs for this
// cluster in order to send that as part of the connect/info process.
func (s *Server) startGateways() {
s.startGatewayAcceptLoop()
// Delay start of creation of gateways to give a chance
// to the local cluster to form.
s.startGoRoutine(func() {
defer s.grWG.Done()
dur := s.getOpts().gatewaysSolicitDelay
if dur == 0 {
dur = time.Duration(atomic.LoadInt64(&gatewaySolicitDelay))
}
select {
case <-time.After(dur):
s.solicitGateways()
case <-s.quitCh:
return
}
})
}
// This starts the gateway accept loop in a go routine, unless it
// is detected that the server has already been shutdown.
func (s *Server) startGatewayAcceptLoop() {
// Snapshot server options.
opts := s.getOpts()
port := opts.Gateway.Port
if port == -1 {
port = 0
}
s.mu.Lock()
if s.shutdown {
s.mu.Unlock()
return
}
hp := net.JoinHostPort(opts.Gateway.Host, strconv.Itoa(port))
l, e := natsListen("tcp", hp)
if e != nil {
s.mu.Unlock()
s.Fatalf("Error listening on gateway port: %d - %v", opts.Gateway.Port, e)
return
}
s.Noticef("Gateway name is %s", s.getGatewayName())
s.Noticef("Listening for gateways connections on %s",
net.JoinHostPort(opts.Gateway.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
tlsReq := opts.Gateway.TLSConfig != nil
authRequired := opts.Gateway.Username != ""
info := &Info{
ID: s.info.ID,
Name: opts.ServerName,
Version: s.info.Version,
AuthRequired: authRequired,
TLSRequired: tlsReq,
TLSVerify: tlsReq,
MaxPayload: s.info.MaxPayload,
Gateway: opts.Gateway.Name,
GatewayNRP: true,
Headers: s.supportsHeaders(),
}
// If we have selected a random port...
if port == 0 {
// Write resolved port back to options.
opts.Gateway.Port = l.Addr().(*net.TCPAddr).Port
}
// Possibly override Host/Port based on Gateway.Advertise
if err := s.setGatewayInfoHostPort(info, opts); err != nil {
s.Fatalf("Error setting gateway INFO with Gateway.Advertise value of %s, err=%v", opts.Gateway.Advertise, err)
l.Close()
s.mu.Unlock()
return
}
// Setup state that can enable shutdown
s.gatewayListener = l
// Warn if insecure is configured in the main Gateway configuration
// or any of the RemoteGateway's. This means that we need to check
// remotes even if TLS would not be configured for the accept.
warn := tlsReq && opts.Gateway.TLSConfig.InsecureSkipVerify
if !warn {
for _, g := range opts.Gateway.Gateways {
if g.TLSConfig != nil && g.TLSConfig.InsecureSkipVerify {
warn = true
break
}
}
}
if warn {
s.Warnf(gatewayTLSInsecureWarning)
}
go s.acceptConnections(l, "Gateway", func(conn net.Conn) { s.createGateway(nil, nil, conn) }, nil)
s.mu.Unlock()
}
// Similar to setInfoHostPortAndGenerateJSON, but for gatewayInfo.
func (s *Server) setGatewayInfoHostPort(info *Info, o *Options) error {
gw := s.gateway
gw.Lock()
defer gw.Unlock()
gw.URLs.removeUrl(gw.URL)
if o.Gateway.Advertise != "" {
advHost, advPort, err := parseHostPort(o.Gateway.Advertise, o.Gateway.Port)
if err != nil {
return err
}
info.Host = advHost
info.Port = advPort
} else {
info.Host = o.Gateway.Host
info.Port = o.Gateway.Port
// If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
// This will return at most 1 IP.
hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(info.Host, false)
if err != nil {
return err
}
if hostIsIPAny {
if len(ips) == 0 {
// TODO(ik): Should we fail here (prevent starting)? If not, we
// are going to "advertise" the 0.0.0.0:<port> url, which means
// that remote are going to try to connect to 0.0.0.0:<port>,
// which means a connect to loopback address, which is going
// to fail with either TLS error, conn refused if the remote
// is using different gateway port than this one, or error
// saying that it tried to connect to itself.
s.Errorf("Could not find any non-local IP for gateway %q with listen specification %q",
gw.name, info.Host)
} else {
// Take the first from the list...
info.Host = ips[0]
}
}
}
gw.URL = net.JoinHostPort(info.Host, strconv.Itoa(info.Port))
if o.Gateway.Advertise != "" {
s.Noticef("Advertise address for gateway %q is set to %s", gw.name, gw.URL)
} else {
s.Noticef("Address for gateway %q is %s", gw.name, gw.URL)
}
gw.URLs[gw.URL]++
gw.info = info
info.GatewayURL = gw.URL
// (re)generate the gatewayInfoJSON byte array
gw.generateInfoJSON()
return nil
}
// Generates the Gateway INFO protocol.
// The gateway lock is held on entry
func (g *srvGateway) generateInfoJSON() {
// We could be here when processing a route INFO that has a gateway URL,
// but this server is not configured for gateways, so simply ignore here.
// The configuration mismatch is reported somewhere else.
if !g.enabled {
return
}
g.info.GatewayURLs = g.URLs.getAsStringSlice()
b, err := json.Marshal(g.info)
if err != nil {
panic(err)
}
g.infoJSON = []byte(fmt.Sprintf(InfoProto, b))
}
// Goes through the list of registered gateways and try to connect to those.
// The list (remotes) is initially containing the explicit remote gateways,
// but the list is augmented with any implicit (discovered) gateway. Therefore,
// this function only solicit explicit ones.
func (s *Server) solicitGateways() {
gw := s.gateway
gw.RLock()
defer gw.RUnlock()
for _, cfg := range gw.remotes {
// Since we delay the creation of gateways, it is
// possible that server starts to receive inbound from
// other clusters and in turn create outbounds. So here
// we create only the ones that are configured.
if !cfg.isImplicit() {
cfg := cfg // Create new instance for the goroutine.
s.startGoRoutine(func() {
s.solicitGateway(cfg, true)
s.grWG.Done()
})
}
}
}
// Reconnect to the gateway after a little wait period. For explicit
// gateways, we also wait for the default reconnect time.
func (s *Server) reconnectGateway(cfg *gatewayCfg) {
defer s.grWG.Done()
delay := time.Duration(rand.Intn(100)) * time.Millisecond
if !cfg.isImplicit() {
delay += gatewayReconnectDelay
}
select {
case <-time.After(delay):
case <-s.quitCh:
return
}
s.solicitGateway(cfg, false)
}
// This function will loop trying to connect to any URL attached
// to the given Gateway. It will return once a connection has been created.
func (s *Server) solicitGateway(cfg *gatewayCfg, firstConnect bool) {
var (
opts = s.getOpts()
isImplicit = cfg.isImplicit()
attempts int
typeStr string
)
if isImplicit {
typeStr = "implicit"
} else {
typeStr = "explicit"
}
const connFmt = "Connecting to %s gateway %q (%s) at %s (attempt %v)"
const connErrFmt = "Error connecting to %s gateway %q (%s) at %s (attempt %v): %v"
for s.isRunning() {
urls := cfg.getURLs()
if len(urls) == 0 {
break
}
attempts++
report := s.shouldReportConnectErr(firstConnect, attempts)
// Iteration is random
for _, u := range urls {
address, err := s.getRandomIP(s.gateway.resolver, u.Host, nil)
if err != nil {
s.Errorf("Error getting IP for %s gateway %q (%s): %v", typeStr, cfg.Name, u.Host, err)
continue
}
if report {
s.Noticef(connFmt, typeStr, cfg.Name, u.Host, address, attempts)
} else {
s.Debugf(connFmt, typeStr, cfg.Name, u.Host, address, attempts)
}
conn, err := natsDialTimeout("tcp", address, DEFAULT_ROUTE_DIAL)
if err == nil {
// We could connect, create the gateway connection and return.
s.createGateway(cfg, u, conn)
return
}
if report {
s.Errorf(connErrFmt, typeStr, cfg.Name, u.Host, address, attempts, err)
} else {
s.Debugf(connErrFmt, typeStr, cfg.Name, u.Host, address, attempts, err)
}
// Break this loop if server is being shutdown...
if !s.isRunning() {
break
}
}
if isImplicit {
if opts.Gateway.ConnectRetries == 0 || attempts > opts.Gateway.ConnectRetries {
s.gateway.Lock()
// We could have just accepted an inbound for this remote gateway.
// So if there is an inbound, let's try again to connect.
if s.gateway.hasInbound(cfg.Name) {
s.gateway.Unlock()
continue
}
delete(s.gateway.remotes, cfg.Name)
s.gateway.Unlock()
return
}
}
select {
case <-s.quitCh:
return
case <-time.After(gatewayConnectDelay):
continue
}
}
}
// Returns true if there is an inbound for the given `name`.
// Lock held on entry.
func (g *srvGateway) hasInbound(name string) bool {
for _, ig := range g.in {
ig.mu.Lock()
igname := ig.gw.name
ig.mu.Unlock()
if igname == name {
return true
}
}
return false
}
// Called when a gateway connection is either accepted or solicited.
// If accepted, the gateway is marked as inbound.
// If solicited, the gateway is marked as outbound.
func (s *Server) createGateway(cfg *gatewayCfg, url *url.URL, conn net.Conn) {
// Snapshot server options.
opts := s.getOpts()
now := time.Now()
c := &client{srv: s, nc: conn, start: now, last: now, kind: GATEWAY}
// Are we creating the gateway based on the configuration
solicit := cfg != nil
var tlsRequired bool
if solicit {
tlsRequired = cfg.TLSConfig != nil
} else {
tlsRequired = opts.Gateway.TLSConfig != nil
}
s.gateway.RLock()
infoJSON := s.gateway.infoJSON
s.gateway.RUnlock()
// Perform some initialization under the client lock
c.mu.Lock()
c.initClient()
c.gw = &gateway{}
if solicit {
// This is an outbound gateway connection
c.gw.outbound = true
c.gw.name = cfg.Name
c.gw.cfg = cfg
cfg.bumpConnAttempts()
// Since we are delaying the connect until after receiving
// the remote's INFO protocol, save the URL we need to connect to.
c.gw.connectURL = url
c.Noticef("Creating outbound gateway connection to %q", cfg.Name)
} else {
c.flags.set(expectConnect)
// Inbound gateway connection
c.Noticef("Processing inbound gateway connection")
}
// Check for TLS
if tlsRequired {
var host string
var timeout float64
// If we solicited, we will act like the client, otherwise the server.
if solicit {
c.Debugf("Starting TLS gateway client handshake")
cfg.RLock()
tlsName := cfg.tlsName
tlsConfig := cfg.TLSConfig.Clone()
timeout = cfg.TLSTimeout
cfg.RUnlock()
if tlsConfig.ServerName == "" {
// If the given url is a hostname, use this hostname for the
// ServerName. If it is an IP, use the cfg's tlsName. If none
// is available, resort to current IP.
host = url.Hostname()
if tlsName != "" && net.ParseIP(host) != nil {
host = tlsName
}
tlsConfig.ServerName = host
}
c.nc = tls.Client(c.nc, tlsConfig)
} else {
c.Debugf("Starting TLS gateway server handshake")
c.nc = tls.Server(c.nc, opts.Gateway.TLSConfig)
timeout = opts.Gateway.TLSTimeout
}
conn := c.nc.(*tls.Conn)
// Setup the timeout
ttl := secondsToDuration(timeout)
time.AfterFunc(ttl, func() { tlsTimeout(c, conn) })
conn.SetReadDeadline(time.Now().Add(ttl))
c.mu.Unlock()
if err := conn.Handshake(); err != nil {
if solicit {
// Based on type of error, possibly clear the saved tlsName
// See: https://github.com/nats-io/nats-server/issues/1256
if _, ok := err.(x509.HostnameError); ok {
cfg.Lock()
if host == cfg.tlsName {
cfg.tlsName = ""
}
cfg.Unlock()
}
}
c.Errorf("TLS gateway handshake error: %v", err)
c.sendErr("Secure Connection - TLS Required")
c.closeConnection(TLSHandshakeError)
return
}
// Reset the read deadline
conn.SetReadDeadline(time.Time{})
// Re-Grab lock
c.mu.Lock()
// To be consistent with client, set this flag to indicate that handshake is done
c.flags.set(handshakeComplete)
// Verify that the connection did not go away while we released the lock.
if c.isClosed() {
c.mu.Unlock()
return
}
}
// Do final client initialization
c.in.pacache = make(map[string]*perAccountCache)
if solicit {
// This is an outbound gateway connection
c.gw.outsim = &sync.Map{}
} else {
// Inbound gateway connection
c.gw.insim = make(map[string]*insie)
}
// Register in temp map for now until gateway properly registered
// in out or in gateways.
if !s.addToTempClients(c.cid, c) {
c.mu.Unlock()
c.closeConnection(ServerShutdown)
return
}
// Only send if we accept a connection. Will send CONNECT+INFO as an
// outbound only after processing peer's INFO protocol.
if !solicit {
c.enqueueProto(infoJSON)
}
// Spin up the read loop.
s.startGoRoutine(func() { c.readLoop(nil) })
// Spin up the write loop.
s.startGoRoutine(func() { c.writeLoop() })
if tlsRequired {
c.Debugf("TLS handshake complete")
cs := c.nc.(*tls.Conn).ConnectionState()
c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tlsCipher(cs.CipherSuite))
}
// Set the Ping timer after sending connect and info.
s.setFirstPingTimer(c)
c.mu.Unlock()
}
// Builds and sends the CONNECT protocol for a gateway.
func (c *client) sendGatewayConnect() {
tlsRequired := c.gw.cfg.TLSConfig != nil
url := c.gw.connectURL
c.gw.connectURL = nil
var user, pass string
if userInfo := url.User; userInfo != nil {
user = userInfo.Username()
pass, _ = userInfo.Password()
}
cinfo := connectInfo{
Verbose: false,
Pedantic: false,
User: user,
Pass: pass,
TLS: tlsRequired,
Name: c.srv.info.ID,
Gateway: c.srv.getGatewayName(),
}
b, err := json.Marshal(cinfo)
if err != nil {
panic(err)
}
c.enqueueProto([]byte(fmt.Sprintf(ConProto, b)))
}
// Process the CONNECT protocol from a gateway connection.
// Returns an error to the connection if the CONNECT is not from a gateway
// (for instance a client or route connecting to the gateway port), or
// if the destination does not match the gateway name of this server.
//
// <Invoked from inbound connection's readLoop>
func (c *client) processGatewayConnect(arg []byte) error {
connect := &connectInfo{}
if err := json.Unmarshal(arg, connect); err != nil {
return err
}
// Coming from a client or a route, reject
if connect.Gateway == "" {
c.sendErrAndErr(ErrClientOrRouteConnectedToGatewayPort.Error())
c.closeConnection(WrongPort)
return ErrClientOrRouteConnectedToGatewayPort
}
c.mu.Lock()
s := c.srv
c.mu.Unlock()
// If we reject unknown gateways, make sure we have it configured,
// otherwise return an error.
if s.gateway.rejectUnknown() && s.getRemoteGateway(connect.Gateway) == nil {
c.Errorf("Rejecting connection from gateway %q", connect.Gateway)
c.sendErr(fmt.Sprintf("Connection to gateway %q rejected", s.getGatewayName()))
c.closeConnection(WrongGateway)
return ErrWrongGateway
}
// For a gateway connection, c.gw is guaranteed not to be nil here
// (created in createGateway() and never set to nil).
// For inbound connections, it is important to know in the parser
// if the CONNECT was received first, so we use this boolean (as
// opposed to client.flags that require locking) to indicate that
// CONNECT was processed. Again, this boolean is set/read in the
// readLoop without locking.
c.gw.connected = true
return nil
}
// Process the INFO protocol from a gateway connection.
//
// If the gateway connection is an outbound (this server initiated the connection),
// this function checks that the incoming INFO contains the Gateway field. If empty,
// it means that this is a response from an older server or that this server connected
// to the wrong port.
// The outbound gateway may also receive a gossip INFO protocol from the remote gateway,
// indicating other gateways that the remote knows about. This server will try to connect
// to those gateways (if not explicitly configured or already implicitly connected).
// In both cases (explicit or implicit), the local cluster is notified about the existence
// of this new gateway. This allows servers in the cluster to ensure that they have an
// outbound connection to this gateway.
//
// For an inbound gateway, the gateway is simply registered and the info protocol
// is saved to be used after processing the CONNECT.
//
// <Invoked from both inbound/outbound readLoop's connection>
func (c *client) processGatewayInfo(info *Info) {
var (
gwName string
cfg *gatewayCfg
)
c.mu.Lock()
s := c.srv
cid := c.cid
// Check if this is the first INFO. (this call sets the flag if not already set).
isFirstINFO := c.flags.setIfNotSet(infoReceived)
isOutbound := c.gw.outbound
if isOutbound {
gwName = c.gw.name
cfg = c.gw.cfg
} else if isFirstINFO {
c.gw.name = info.Gateway
}
if isFirstINFO {
c.opts.Name = info.ID
}
c.mu.Unlock()
// For an outbound connection...
if isOutbound {
// Check content of INFO for fields indicating that it comes from a gateway.
// If we incorrectly connect to the wrong port (client or route), we won't
// have the Gateway field set.
if info.Gateway == "" {
c.sendErrAndErr(fmt.Sprintf("Attempt to connect to gateway %q using wrong port", gwName))
c.closeConnection(WrongPort)
return
}
// Check that the gateway name we got is what we expect
if info.Gateway != gwName {
// Unless this is the very first INFO, it may be ok if this is
// a gossip request to connect to other gateways.
if !isFirstINFO && info.GatewayCmd == gatewayCmdGossip {
// If we are configured to reject unknown, do not attempt to
// connect to one that we don't have configured.
if s.gateway.rejectUnknown() && s.getRemoteGateway(info.Gateway) == nil {
return
}
s.processImplicitGateway(info)
return
}
// Otherwise, this is a failure...
// We are reporting this error in the log...
c.Errorf("Failing connection to gateway %q, remote gateway name is %q",
gwName, info.Gateway)
// ...and sending this back to the remote so that the error
// makes more sense in the remote server's log.
c.sendErr(fmt.Sprintf("Connection from %q rejected, wanted to connect to %q, this is %q",
s.getGatewayName(), gwName, info.Gateway))
c.closeConnection(WrongGateway)
return
}
// Possibly add URLs that we get from the INFO protocol.
if len(info.GatewayURLs) > 0 {
cfg.updateURLs(info.GatewayURLs)
}
// If this is the first INFO, send our connect
if isFirstINFO {
s.gateway.RLock()
infoJSON := s.gateway.infoJSON
s.gateway.RUnlock()
supportsHeaders := s.supportsHeaders()
// Note, if we want to support NKeys, then we would get the nonce
// from this INFO protocol and can sign it in the CONNECT we are
// going to send now.
c.mu.Lock()
c.sendGatewayConnect()
c.Debugf("Gateway connect protocol sent to %q", gwName)
// Send INFO too
c.enqueueProto(infoJSON)
c.gw.useOldPrefix = !info.GatewayNRP
c.headers = supportsHeaders && info.Headers
c.mu.Unlock()
// Register as an outbound gateway.. if we had a protocol to ack our connect,
// then we should do that when process that ack.
if s.registerOutboundGatewayConnection(gwName, c) {
c.Noticef("Outbound gateway connection to %q (%s) registered", gwName, info.ID)
// Now that the outbound gateway is registered, we can remove from temp map.
s.removeFromTempClients(cid)
} else {
// There was a bug that would cause a connection to possibly
// be called twice resulting in reconnection of twice the
// same outbound connection. The issue is fixed, but adding
// defensive code above that if we did not register this connection
// because we already have an outbound for this name, then
// close this connection (and make sure it does not try to reconnect)
c.mu.Lock()
c.flags.set(noReconnect)
c.mu.Unlock()
c.closeConnection(WrongGateway)
return
}
} else if info.GatewayCmd > 0 {
switch info.GatewayCmd {
case gatewayCmdAllSubsStart:
c.gatewayAllSubsReceiveStart(info)
return
case gatewayCmdAllSubsComplete:
c.gatewayAllSubsReceiveComplete(info)
return
default:
s.Warnf("Received unknown command %v from gateway %q", info.GatewayCmd, gwName)
return
}
}
// Flood local cluster with information about this gateway.
// Servers in this cluster will ensure that they have (or otherwise create)
// an outbound connection to this gateway.
s.forwardNewGatewayToLocalCluster(info)
} else if isFirstINFO {
// This is the first INFO of an inbound connection...
s.registerInboundGatewayConnection(cid, c)
c.Noticef("Inbound gateway connection from %q (%s) registered", info.Gateway, info.ID)
// Now that it is registered, we can remove from temp map.
s.removeFromTempClients(cid)
// Send our QSubs.
s.sendQueueSubsToGateway(c)
// Initiate outbound connection. This function will behave correctly if
// we have already one.
s.processImplicitGateway(info)
// Send back to the server that initiated this gateway connection the
// list of all remote gateways known on this server.
s.gossipGatewaysToInboundGateway(info.Gateway, c)
// Now make sure if we have any knowledge of connected leafnodes that we resend the
// connect events to switch those accounts into interest only mode.
s.mu.Lock()
s.ensureGWsInterestOnlyForLeafNodes()
s.mu.Unlock()
}
}
// Sends to the given inbound gateway connection a gossip INFO protocol
// for each gateway known by this server. This allows for a "full mesh"
// of gateways.
func (s *Server) gossipGatewaysToInboundGateway(gwName string, c *client) {
gw := s.gateway
gw.RLock()
defer gw.RUnlock()
for gwCfgName, cfg := range gw.remotes {
// Skip the gateway that we just created
if gwCfgName == gwName {
continue
}
info := Info{
ID: s.info.ID,
GatewayCmd: gatewayCmdGossip,
}
urls := cfg.getURLsAsStrings()
if len(urls) > 0 {
info.Gateway = gwCfgName
info.GatewayURLs = urls
b, _ := json.Marshal(&info)
c.mu.Lock()
c.enqueueProto([]byte(fmt.Sprintf(InfoProto, b)))
c.mu.Unlock()
}
}
}
// Sends the INFO protocol of a gateway to all routes known by this server.
func (s *Server) forwardNewGatewayToLocalCluster(oinfo *Info) {
// Need to protect s.routes here, so use server's lock
s.mu.Lock()
defer s.mu.Unlock()
// We don't really need the ID to be set, but, we need to make sure
// that it is not set to the server ID so that if we were to connect
// to an older server that does not expect a "gateway" INFO, it
// would think that it needs to create an implicit route (since info.ID
// would not match the route's remoteID), but will fail to do so because
// the sent protocol will not have host/port defined.
info := &Info{
ID: "GW" + s.info.ID,
Name: s.getOpts().ServerName,
Gateway: oinfo.Gateway,
GatewayURLs: oinfo.GatewayURLs,
GatewayCmd: gatewayCmdGossip,
}
b, _ := json.Marshal(info)
infoJSON := []byte(fmt.Sprintf(InfoProto, b))
for _, r := range s.routes {
r.mu.Lock()
r.enqueueProto(infoJSON)
r.mu.Unlock()
}
}
// Sends queue subscriptions interest to remote gateway.
// This is sent from the inbound side, that is, the side that receives
// messages from the remote's outbound connection. This side is
// the one sending the subscription interest.
func (s *Server) sendQueueSubsToGateway(c *client) {
s.sendSubsToGateway(c, nil)
}
// Sends all subscriptions for the given account to the remove gateway
// This is sent from the inbound side, that is, the side that receives
// messages from the remote's outbound connection. This side is
// the one sending the subscription interest.
func (s *Server) sendAccountSubsToGateway(c *client, accName []byte) {
s.sendSubsToGateway(c, accName)
}
func gwBuildSubProto(buf *bytes.Buffer, accName []byte, acc map[string]*sitally, doQueues bool) {
for saq, si := range acc {
if doQueues && si.q || !doQueues && !si.q {
buf.Write(rSubBytes)
buf.Write(accName)
buf.WriteByte(' ')
// For queue subs (si.q is true), saq will be
// subject + ' ' + queue, for plain subs, this is
// just the subject.
buf.WriteString(saq)
if doQueues {
buf.WriteString(" 1")
}
buf.WriteString(CR_LF)
}
}
}
// Sends subscriptions to remote gateway.
func (s *Server) sendSubsToGateway(c *client, accountName []byte) {
var (
bufa = [32 * 1024]byte{}
bbuf = bytes.NewBuffer(bufa[:0])
)
gw := s.gateway
// This needs to run under this lock for the whole duration
gw.pasi.Lock()
defer gw.pasi.Unlock()
// If account is specified...
if accountName != nil {
// Simply send all plain subs (no queues) for this specific account
gwBuildSubProto(bbuf, accountName, gw.pasi.m[string(accountName)], false)
// Instruct to send all subs (RS+/-) for this account from now on.
c.mu.Lock()
e := c.gw.insim[string(accountName)]
if e == nil {
e = &insie{}
c.gw.insim[string(accountName)] = e
}
e.mode = InterestOnly
c.mu.Unlock()
} else {
// Send queues for all accounts
for accName, acc := range gw.pasi.m {
gwBuildSubProto(bbuf, []byte(accName), acc, true)
}
}
buf := bbuf.Bytes()
// Nothing to send.
if len(buf) == 0 {
return
}
if len(buf) > cap(bufa) {
s.Debugf("Sending subscriptions to %q, buffer size: %v", c.gw.name, len(buf))
}
// Send
c.mu.Lock()
c.enqueueProto(buf)
c.Debugf("Sent queue subscriptions to gateway")
c.mu.Unlock()
}
// This is invoked when getting an INFO protocol for gateway on the ROUTER port.
// This function will then execute appropriate function based on the command
// contained in the protocol.
// <Invoked from a route connection's readLoop>
func (s *Server) processGatewayInfoFromRoute(info *Info, routeSrvID string, route *client) {
switch info.GatewayCmd {
case gatewayCmdGossip:
s.processImplicitGateway(info)
default:
s.Errorf("Unknown command %d from server %v", info.GatewayCmd, routeSrvID)
}
}
// Sends INFO protocols to the given route connection for each known Gateway.
// These will be processed by the route and delegated to the gateway code to
// imvoke processImplicitGateway.
func (s *Server) sendGatewayConfigsToRoute(route *client) {
gw := s.gateway
gw.RLock()
// Send only to gateways for which we have actual outbound connection to.
if len(gw.out) == 0 {
gw.RUnlock()
return
}
// Collect gateway configs for which we have an outbound connection.
gwCfgsa := [16]*gatewayCfg{}
gwCfgs := gwCfgsa[:0]
for _, c := range gw.out {
c.mu.Lock()
if c.gw.cfg != nil {
gwCfgs = append(gwCfgs, c.gw.cfg)
}
c.mu.Unlock()
}
gw.RUnlock()
if len(gwCfgs) == 0 {
return
}
// Check forwardNewGatewayToLocalCluster() as to why we set ID this way.
info := Info{
ID: "GW" + s.info.ID,
GatewayCmd: gatewayCmdGossip,
}
for _, cfg := range gwCfgs {
urls := cfg.getURLsAsStrings()
if len(urls) > 0 {
info.Gateway = cfg.Name
info.GatewayURLs = urls
b, _ := json.Marshal(&info)
route.mu.Lock()
route.enqueueProto([]byte(fmt.Sprintf(InfoProto, b)))
route.mu.Unlock()
}
}
}
// Initiates a gateway connection using the info contained in the INFO protocol.
// If a gateway with the same name is already registered (either because explicitly
// configured, or already implicitly connected), this function will augmment the
// remote URLs with URLs present in the info protocol and return.
// Otherwise, this function will register this remote (to prevent multiple connections
// to the same remote) and call solicitGateway (which will run in a different go-routine).
func (s *Server) processImplicitGateway(info *Info) {
s.gateway.Lock()
defer s.gateway.Unlock()
// Name of the gateway to connect to is the Info.Gateway field.
gwName := info.Gateway
// If this is our name, bail.
if gwName == s.gateway.name {
return
}
// Check if we already have this config, and if so, we are done
cfg := s.gateway.remotes[gwName]
if cfg != nil {
// However, possibly augment the list of URLs with the given
// info.GatewayURLs content.
cfg.Lock()
cfg.addURLs(info.GatewayURLs)
cfg.Unlock()
return
}
opts := s.getOpts()
cfg = &gatewayCfg{
RemoteGatewayOpts: &RemoteGatewayOpts{Name: gwName},
hash: getHash(gwName),
oldHash: getOldHash(gwName),
urls: make(map[string]*url.URL, len(info.GatewayURLs)),
implicit: true,
}
if opts.Gateway.TLSConfig != nil {
cfg.TLSConfig = opts.Gateway.TLSConfig.Clone()
cfg.TLSTimeout = opts.Gateway.TLSTimeout
}
// Since we know we don't have URLs (no config, so just based on what we
// get from INFO), directly call addURLs(). We don't need locking since
// we just created that structure and no one else has access to it yet.
cfg.addURLs(info.GatewayURLs)
// If there is no URL, we can't proceed.
if len(cfg.urls) == 0 {
return
}
s.gateway.remotes[gwName] = cfg
s.startGoRoutine(func() {
s.solicitGateway(cfg, true)
s.grWG.Done()
})
}
// NumOutboundGateways is public here mostly for testing.
func (s *Server) NumOutboundGateways() int {
return s.numOutboundGateways()
}
// Returns the number of outbound gateway connections
func (s *Server) numOutboundGateways() int {
s.gateway.RLock()
n := len(s.gateway.out)
s.gateway.RUnlock()
return n
}
// Returns the number of inbound gateway connections
func (s *Server) numInboundGateways() int {
s.gateway.RLock()
n := len(s.gateway.in)
s.gateway.RUnlock()
return n
}
// Returns the remoteGateway (if any) that has the given `name`
func (s *Server) getRemoteGateway(name string) *gatewayCfg {
s.gateway.RLock()
cfg := s.gateway.remotes[name]
s.gateway.RUnlock()
return cfg
}
// Used in tests
func (g *gatewayCfg) bumpConnAttempts() {
g.Lock()
g.connAttempts++
g.Unlock()
}
// Used in tests
func (g *gatewayCfg) getConnAttempts() int {
g.Lock()
ca := g.connAttempts
g.Unlock()
return ca
}
// Used in tests
func (g *gatewayCfg) resetConnAttempts() {
g.Lock()
g.connAttempts = 0
g.Unlock()
}
// Returns if this remote gateway is implicit or not.
func (g *gatewayCfg) isImplicit() bool {
g.RLock()
ii := g.implicit
g.RUnlock()
return ii
}
// getURLs returns an array of URLs in random order suitable for
// an iteration to try to connect.
func (g *gatewayCfg) getURLs() []*url.URL {
g.RLock()
a := make([]*url.URL, 0, len(g.urls))
for _, u := range g.urls {
a = append(a, u)
}
g.RUnlock()
// Map iteration is random, but not that good with small maps.
rand.Shuffle(len(a), func(i, j int) {
a[i], a[j] = a[j], a[i]
})
return a
}
// Similar to getURLs but returns the urls as an array of strings.
func (g *gatewayCfg) getURLsAsStrings() []string {
g.RLock()
a := make([]string, 0, len(g.urls))
for _, u := range g.urls {
a = append(a, u.Host)
}
g.RUnlock()
return a
}
// updateURLs creates the urls map with the content of the config's URLs array
// and the given array that we get from the INFO protocol.
func (g *gatewayCfg) updateURLs(infoURLs []string) {
g.Lock()
// Clear the map...
g.urls = make(map[string]*url.URL, len(g.URLs)+len(infoURLs))
// Add the urls from the config URLs array.
for _, u := range g.URLs {
g.urls[u.Host] = u
}
// Then add the ones from the infoURLs array we got.
g.addURLs(infoURLs)
g.Unlock()
}
// Saves the hostname of the given URL (if not already done).
// This may be used as the ServerName of the TLSConfig when initiating a
// TLS connection.
// Write lock held on entry.
func (g *gatewayCfg) saveTLSHostname(u *url.URL) {
if g.TLSConfig != nil && g.tlsName == "" && net.ParseIP(u.Hostname()) == nil {
g.tlsName = u.Hostname()
}
}
// add URLs from the given array to the urls map only if not already present.
// remoteGateway write lock is assumed to be held on entry.
// Write lock is held on entry.
func (g *gatewayCfg) addURLs(infoURLs []string) {
var scheme string
if g.TLSConfig != nil {
scheme = "tls"
} else {
scheme = "nats"
}
for _, iu := range infoURLs {
if _, present := g.urls[iu]; !present {
// Urls in Info.GatewayURLs come without scheme. Add it to parse
// the url (otherwise it fails).
if u, err := url.Parse(fmt.Sprintf("%s://%s", scheme, iu)); err == nil {
// Also, if a tlsName has not been set yet and we are dealing
// with a hostname and not a bare IP, save the hostname.
g.saveTLSHostname(u)
// Use u.Host for the key.
g.urls[u.Host] = u
// Signal that we have updated the list. Used by monitoring code.
g.varzUpdateURLs = true
}
}
}
}
// Adds this URL to the set of Gateway URLs.
// Returns true if the URL has been added, false otherwise.
// Server lock held on entry
func (s *Server) addGatewayURL(urlStr string) bool {
s.gateway.Lock()
added := s.gateway.URLs.addUrl(urlStr)
if added {
s.gateway.generateInfoJSON()
}
s.gateway.Unlock()
return added
}
// Removes this URL from the set of gateway URLs.
// Returns true if the URL has been removed, false otherwise.
// Server lock held on entry
func (s *Server) removeGatewayURL(urlStr string) bool {
if s.shutdown {
return false
}
s.gateway.Lock()
removed := s.gateway.URLs.removeUrl(urlStr)
if removed {
s.gateway.generateInfoJSON()
}
s.gateway.Unlock()
return removed
}
// Sends a Gateway's INFO to all inbound GW connections.
// Server lock is held on entry
func (s *Server) sendAsyncGatewayInfo() {
s.gateway.RLock()
for _, ig := range s.gateway.in {
ig.mu.Lock()
ig.enqueueProto(s.gateway.infoJSON)
ig.mu.Unlock()
}
s.gateway.RUnlock()
}
// This returns the URL of the Gateway listen spec, or empty string
// if the server has no gateway configured.
func (s *Server) getGatewayURL() string {
s.gateway.RLock()
url := s.gateway.URL
s.gateway.RUnlock()
return url
}
// Returns this server gateway name.
// Same than calling s.gateway.getName()
func (s *Server) getGatewayName() string {
return s.gateway.getName()
}
// All gateway connections (outbound and inbound) are put in the given map.
func (s *Server) getAllGatewayConnections(conns map[uint64]*client) {
gw := s.gateway
gw.RLock()
for _, c := range gw.out {
c.mu.Lock()
cid := c.cid
c.mu.Unlock()
conns[cid] = c
}
for cid, c := range gw.in {
conns[cid] = c
}
gw.RUnlock()
}
// Register the given gateway connection (*client) in the inbound gateways
// map. The key is the connection ID (like for clients and routes).
func (s *Server) registerInboundGatewayConnection(cid uint64, gwc *client) {
s.gateway.Lock()
s.gateway.in[cid] = gwc
s.gateway.Unlock()
}
// Register the given gateway connection (*client) in the outbound gateways
// map with the given name as the key.
func (s *Server) registerOutboundGatewayConnection(name string, gwc *client) bool {
s.gateway.Lock()
if _, exist := s.gateway.out[name]; exist {
s.gateway.Unlock()
return false
}
s.gateway.out[name] = gwc
s.gateway.outo = append(s.gateway.outo, gwc)
s.gateway.orderOutboundConnectionsLocked()
s.gateway.Unlock()
return true
}
// Returns the outbound gateway connection (*client) with the given name,
// or nil if not found
func (s *Server) getOutboundGatewayConnection(name string) *client {
s.gateway.RLock()
gwc := s.gateway.out[name]
s.gateway.RUnlock()
return gwc
}
// Returns all outbound gateway connections in the provided array.
// The order of the gateways is suited for the sending of a message.
// Current ordering is based on individual gateway's RTT value.
func (s *Server) getOutboundGatewayConnections(a *[]*client) {
s.gateway.RLock()
for i := 0; i < len(s.gateway.outo); i++ {
*a = append(*a, s.gateway.outo[i])
}
s.gateway.RUnlock()
}
// Orders the array of outbound connections.
// Current ordering is by lowest RTT.
// Gateway write lock is held on entry
func (g *srvGateway) orderOutboundConnectionsLocked() {
// Order the gateways by lowest RTT
sort.Slice(g.outo, func(i, j int) bool {
return g.outo[i].getRTTValue() < g.outo[j].getRTTValue()
})
}
// Orders the array of outbound connections.
// Current ordering is by lowest RTT.
func (g *srvGateway) orderOutboundConnections() {
g.Lock()
g.orderOutboundConnectionsLocked()
g.Unlock()
}
// Returns all inbound gateway connections in the provided array
func (s *Server) getInboundGatewayConnections(a *[]*client) {
s.gateway.RLock()
for _, gwc := range s.gateway.in {
*a = append(*a, gwc)
}
s.gateway.RUnlock()
}
// This is invoked when a gateway connection is closed and the server
// is removing this connection from its state.
func (s *Server) removeRemoteGatewayConnection(c *client) {
c.mu.Lock()
cid := c.cid
isOutbound := c.gw.outbound
gwName := c.gw.name
c.mu.Unlock()
gw := s.gateway
gw.Lock()
if isOutbound {
delete(gw.out, gwName)
louto := len(gw.outo)
reorder := false
for i := 0; i < len(gw.outo); i++ {
if gw.outo[i] == c {
// If last, simply remove and no need to reorder
if i != louto-1 {
gw.outo[i] = gw.outo[louto-1]
reorder = true
}
gw.outo = gw.outo[:louto-1]
}
}
if reorder {
gw.orderOutboundConnectionsLocked()
}
} else {
delete(gw.in, cid)
}
gw.Unlock()
s.removeFromTempClients(cid)
if isOutbound {
// Update number of totalQSubs for this gateway
qSubsRemoved := int64(0)
c.mu.Lock()
for _, sub := range c.subs {
if sub.queue != nil {
qSubsRemoved++
}
}
c.mu.Unlock()
// Update total count of qsubs in remote gateways.
atomic.AddInt64(&c.srv.gateway.totalQSubs, -qSubsRemoved)
} else {
var subsa [1024]*subscription
var subs = subsa[:0]
// For inbound GW connection, if we have subs, those are
// local subs on "_R_." subjects.
c.mu.Lock()
for _, sub := range c.subs {
subs = append(subs, sub)
}
c.mu.Unlock()
for _, sub := range subs {
c.removeReplySub(sub)
}
}
}
// GatewayAddr returns the net.Addr object for the gateway listener.
func (s *Server) GatewayAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.gatewayListener == nil {
return nil
}
return s.gatewayListener.Addr().(*net.TCPAddr)
}
// A- protocol received from the remote after sending messages
// on an account that it has no interest in. Mark this account
// with a "no interest" marker to prevent further messages send.
// <Invoked from outbound connection's readLoop>
func (c *client) processGatewayAccountUnsub(accName string) {
// Just to indicate activity around "subscriptions" events.
c.in.subs++
// This account may have an entry because of queue subs.
// If that's the case, we can reset the no-interest map,
// but not set the entry to nil.
setToNil := true
if ei, ok := c.gw.outsim.Load(accName); ei != nil {
e := ei.(*outsie)
e.Lock()
// Reset the no-interest map if we have queue subs
// and don't set the entry to nil.
if e.qsubs > 0 {
e.ni = make(map[string]struct{})
setToNil = false
}
e.Unlock()
} else if ok {
// Already set to nil, so skip
setToNil = false
}
if setToNil {
c.gw.outsim.Store(accName, nil)
}
}
// A+ protocol received from remote gateway if it had previously
// sent an A-. Clear the "no interest" marker for this account.
// <Invoked from outbound connection's readLoop>
func (c *client) processGatewayAccountSub(accName string) error {
// Just to indicate activity around "subscriptions" events.
c.in.subs++
// If this account has an entry because of queue subs, we
// can't delete the entry.
remove := true
if ei, ok := c.gw.outsim.Load(accName); ei != nil {
e := ei.(*outsie)
e.Lock()
if e.qsubs > 0 {
remove = false
}
e.Unlock()
} else if !ok {
// There is no entry, so skip
remove = false
}
if remove {
c.gw.outsim.Delete(accName)
}
return nil
}
// RS- protocol received from the remote after sending messages
// on a subject that it has no interest in (but knows about the
// account). Mark this subject with a "no interest" marker to
// prevent further messages being sent.
// If in modeInterestOnly or for a queue sub, remove from
// the sublist if present.
// <Invoked from outbound connection's readLoop>
func (c *client) processGatewayRUnsub(arg []byte) error {
accName, subject, queue, err := c.parseUnsubProto(arg)
if err != nil {
return fmt.Errorf("processGatewaySubjectUnsub %s", err.Error())
}
var (
e *outsie
useSl bool
newe bool
callUpdate bool
srv *Server
sub *subscription
)
// Possibly execute this on exit after all locks have been released.
// If callUpdate is true, srv and sub will be not nil.
defer func() {
if callUpdate {
srv.updateInterestForAccountOnGateway(accName, sub, -1)
}
}()
c.mu.Lock()
if c.gw.outsim == nil {
c.Errorf("Received RS- from gateway on inbound connection")
c.mu.Unlock()
c.closeConnection(ProtocolViolation)
return nil
}
defer c.mu.Unlock()
ei, _ := c.gw.outsim.Load(accName)
if ei != nil {
e = ei.(*outsie)
e.Lock()
defer e.Unlock()
// If there is an entry, for plain sub we need
// to know if we should store the sub
useSl = queue != nil || e.mode != Optimistic
} else if queue != nil {
// should not even happen...
c.Debugf("Received RS- without prior RS+ for subject %q, queue %q", subject, queue)
return nil
} else {
// Plain sub, assume optimistic sends, create entry.
e = &outsie{ni: make(map[string]struct{}), sl: NewSublistWithCache()}
newe = true
}
// This is when a sub or queue sub is supposed to be in
// the sublist. Look for it and remove.
if useSl {
var ok bool
key := arg
// m[string()] does not cause mem allocation
sub, ok = c.subs[string(key)]
// if RS- for a sub that we don't have, just ignore.
if !ok {
return nil
}
if e.sl.Remove(sub) == nil {
delete(c.subs, string(key))
if queue != nil {
e.qsubs--
atomic.AddInt64(&c.srv.gateway.totalQSubs, -1)
}
// If last, we can remove the whole entry only
// when in optimistic mode and there is no element
// in the `ni` map.
if e.sl.Count() == 0 && e.mode == Optimistic && len(e.ni) == 0 {
c.gw.outsim.Delete(accName)
}
}
// We are going to call updateInterestForAccountOnGateway on exit.
srv = c.srv
callUpdate = true
} else {
e.ni[string(subject)] = struct{}{}
if newe {
c.gw.outsim.Store(accName, e)
}
}
return nil
}
// For plain subs, RS+ protocol received from remote gateway if it
// had previously sent a RS-. Clear the "no interest" marker for
// this subject (under this account).
// For queue subs, or if in modeInterestOnly, register interest
// from remote gateway.
// <Invoked from outbound connection's readLoop>
func (c *client) processGatewayRSub(arg []byte) error {
// Indicate activity.
c.in.subs++
var (
queue []byte
qw int32
)
args := splitArg(arg)
switch len(args) {
case 2:
case 4:
queue = args[2]
qw = int32(parseSize(args[3]))
default:
return fmt.Errorf("processGatewaySubjectSub Parse Error: '%s'", arg)
}
accName := args[0]
subject := args[1]
var (
e *outsie
useSl bool
newe bool
callUpdate bool
srv *Server
sub *subscription
)
// Possibly execute this on exit after all locks have been released.
// If callUpdate is true, srv and sub will be not nil.
defer func() {
if callUpdate {
srv.updateInterestForAccountOnGateway(string(accName), sub, 1)
}
}()
c.mu.Lock()
if c.gw.outsim == nil {
c.Errorf("Received RS+ from gateway on inbound connection")
c.mu.Unlock()
c.closeConnection(ProtocolViolation)
return nil
}
defer c.mu.Unlock()
ei, _ := c.gw.outsim.Load(string(accName))
// We should always have an existing entry for plain subs because
// in optimistic mode we would have received RS- first, and
// in full knowledge, we are receiving RS+ for an account after
// getting many RS- from the remote..
if ei != nil {
e = ei.(*outsie)
e.Lock()
defer e.Unlock()
useSl = queue != nil || e.mode != Optimistic
} else if queue == nil {
return nil
} else {
e = &outsie{ni: make(map[string]struct{}), sl: NewSublistWithCache()}
newe = true
useSl = true
}
if useSl {
var key []byte
// We store remote subs by account/subject[/queue].
// For queue, remove the trailing weight
if queue != nil {
key = arg[:len(arg)-len(args[3])-1]
} else {
key = arg
}
// If RS+ for a sub that we already have, ignore.
// (m[string()] does not allocate memory)
if _, ok := c.subs[string(key)]; ok {
return nil
}
// new subscription. copy subject (and queue) to
// not reference the underlying possibly big buffer.
var csubject []byte
var cqueue []byte
if queue != nil {
// make single allocation and use different slices
// to point to subject and queue name.
cbuf := make([]byte, len(subject)+1+len(queue))
copy(cbuf, key[len(accName)+1:])
csubject = cbuf[:len(subject)]
cqueue = cbuf[len(subject)+1:]
} else {
csubject = make([]byte, len(subject))
copy(csubject, subject)
}
sub = &subscription{client: c, subject: csubject, queue: cqueue, qw: qw}
// If no error inserting in sublist...
if e.sl.Insert(sub) == nil {
c.subs[string(key)] = sub
if queue != nil {
e.qsubs++
atomic.AddInt64(&c.srv.gateway.totalQSubs, 1)
}
if newe {
c.gw.outsim.Store(string(accName), e)
}
}
// We are going to call updateInterestForAccountOnGateway on exit.
srv = c.srv
callUpdate = true
} else {
subj := string(subject)
// If this is an RS+ for a wc subject, then
// remove from the no interest map all subjects
// that are a subset of this wc subject.
if subjectHasWildcard(subj) {
for k := range e.ni {
if subjectIsSubsetMatch(k, subj) {
delete(e.ni, k)
}
}
} else {
delete(e.ni, subj)
}
}
return nil
}
// Returns true if this gateway has possible interest in the
// given account/subject (which means, it does not have a registered
// no-interest on the account and/or subject) and the sublist result
// for queue subscriptions.
// <Outbound connection: invoked when client message is published,
// so from any client connection's readLoop>
func (c *client) gatewayInterest(acc, subj string) (bool, *SublistResult) {
ei, accountInMap := c.gw.outsim.Load(acc)
// If there is an entry for this account and ei is nil,
// it means that the remote is not interested at all in
// this account and we could not possibly have queue subs.
if accountInMap && ei == nil {
return false, nil
}
// Assume interest if account not in map.
psi := !accountInMap
var r *SublistResult
if accountInMap {
// If in map, check for subs interest with sublist.
e := ei.(*outsie)
e.RLock()
// We may be in transition to modeInterestOnly
// but until e.ni is nil, use it to know if we
// should suppress interest or not.
if e.ni != nil {
if _, inMap := e.ni[subj]; !inMap {
psi = true
}
}
// If we are in modeInterestOnly (e.ni will be nil)
// or if we have queue subs, we also need to check sl.Match.
if e.ni == nil || e.qsubs > 0 {
r = e.sl.Match(subj)
if len(r.psubs) > 0 {
psi = true
}
}
e.RUnlock()
}
return psi, r
}
// switchAccountToInterestMode will switch an account over to interestMode.
// Lock should NOT be held.
func (s *Server) switchAccountToInterestMode(accName string) {
gwsa := [16]*client{}
gws := gwsa[:0]
s.getInboundGatewayConnections(&gws)
for _, gin := range gws {
var e *insie
var ok bool
gin.mu.Lock()
if e, ok = gin.gw.insim[accName]; !ok || e == nil {
e = &insie{}
gin.gw.insim[accName] = e
}
// Do it only if we are in Optimistic mode
if e.mode == Optimistic {
gin.gatewaySwitchAccountToSendAllSubs(e, accName)
}
gin.mu.Unlock()
}
}
// This is invoked when registering (or unregistering) the first
// (or last) subscription on a given account/subject. For each
// GWs inbound connections, we will check if we need to send an RS+ or A+
// protocol.
func (s *Server) maybeSendSubOrUnsubToGateways(accName string, sub *subscription, added bool) {
if sub.queue != nil {
return
}
gwsa := [16]*client{}
gws := gwsa[:0]
s.getInboundGatewayConnections(&gws)
if len(gws) == 0 {
return
}
var (
rsProtoa [512]byte
rsProto []byte
accProtoa [256]byte
accProto []byte
proto []byte
subject = string(sub.subject)
hasWc = subjectHasWildcard(subject)
)
for _, c := range gws {
proto = nil
c.mu.Lock()
e, inMap := c.gw.insim[accName]
// If there is a inbound subject interest entry...
if e != nil {
sendProto := false
// In optimistic mode, we care only about possibly sending RS+ (or A+)
// so if e.ni is not nil we do things only when adding a new subscription.
if e.ni != nil && added {
// For wildcard subjects, we will remove from our no-interest
// map, all subjects that are a subset of this wc subject, but we
// still send the wc subject and let the remote do its own cleanup.
if hasWc {
for enis := range e.ni {
if subjectIsSubsetMatch(enis, subject) {
delete(e.ni, enis)
sendProto = true
}
}
} else if _, noInterest := e.ni[subject]; noInterest {
delete(e.ni, subject)
sendProto = true
}
} else if e.mode == InterestOnly {
// We are in the mode where we always send RS+/- protocols.
sendProto = true
}
if sendProto {
if rsProto == nil {
// Construct the RS+/- only once
proto = rsProtoa[:0]
if added {
proto = append(proto, rSubBytes...)
} else {
proto = append(proto, rUnsubBytes...)
}
proto = append(proto, accName...)
proto = append(proto, ' ')
proto = append(proto, sub.subject...)
proto = append(proto, CR_LF...)
rsProto = proto
} else {
// Point to the already constructed RS+/-
proto = rsProto
}
}
} else if added && inMap {
// Here, we have a `nil` entry for this account in
// the map, which means that we have previously sent
// an A-. We have a new subscription, so we need to
// send an A+ and delete the entry from the map so
// that we do this only once.
delete(c.gw.insim, accName)
if accProto == nil {
// Construct the A+ only once
proto = accProtoa[:0]
proto = append(proto, aSubBytes...)
proto = append(proto, accName...)
proto = append(proto, CR_LF...)
accProto = proto
} else {
// Point to the already constructed A+
proto = accProto
}
}
if proto != nil {
c.enqueueProto(proto)
if c.trace {
c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
}
}
c.mu.Unlock()
}
}
// This is invoked when the first (or last) queue subscription on a
// given subject/group is registered (or unregistered). Sent to all
// inbound gateways.
func (s *Server) sendQueueSubOrUnsubToGateways(accName string, qsub *subscription, added bool) {
if qsub.queue == nil {
return
}
gwsa := [16]*client{}
gws := gwsa[:0]
s.getInboundGatewayConnections(&gws)
if len(gws) == 0 {
return
}
var protoa [512]byte
var proto []byte
for _, c := range gws {
if proto == nil {
proto = protoa[:0]
if added {
proto = append(proto, rSubBytes...)
} else {
proto = append(proto, rUnsubBytes...)
}
proto = append(proto, accName...)
proto = append(proto, ' ')
proto = append(proto, qsub.subject...)
proto = append(proto, ' ')
proto = append(proto, qsub.queue...)
if added {
// For now, just use 1 for the weight
proto = append(proto, ' ', '1')
}
proto = append(proto, CR_LF...)
}
c.mu.Lock()
// If we add a queue sub, and we had previously sent an A-,
// we don't need to send an A+ here, but we need to clear
// the fact that we did sent the A- so that we don't send
// an A+ when we will get the first non-queue sub registered.
if added {
if ei, ok := c.gw.insim[accName]; ok && ei == nil {
delete(c.gw.insim, accName)
}
}
c.enqueueProto(proto)
if c.trace {
c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
}
c.mu.Unlock()
}
}
// This is invoked when a subscription (plain or queue) is
// added/removed locally or in our cluster. We use ref counting
// to know when to update the inbound gateways.
// <Invoked from client or route connection's readLoop or when such
// connection is closed>
func (s *Server) gatewayUpdateSubInterest(accName string, sub *subscription, change int32) {
var (
keya [1024]byte
key = keya[:0]
entry *sitally
isNew bool
)
s.gateway.pasi.Lock()
defer s.gateway.pasi.Unlock()
accMap := s.gateway.pasi.m
// First see if we have the account
st := accMap[accName]
if st == nil {
// Ignore remove of something we don't have
if change < 0 {
return
}
st = make(map[string]*sitally)
accMap[accName] = st
isNew = true
}
// Lookup: build the key as subject[+' '+queue]
key = append(key, sub.subject...)
if sub.queue != nil {
key = append(key, ' ')
key = append(key, sub.queue...)
}
if !isNew {
entry = st[string(key)]
}
first := false
last := false
if entry == nil {
// Ignore remove of something we don't have
if change < 0 {
return
}
entry = &sitally{n: 1, q: sub.queue != nil}
st[string(key)] = entry
first = true
} else {
entry.n += change
if entry.n <= 0 {
delete(st, string(key))
last = true
if len(st) == 0 {
delete(accMap, accName)
}
}
}
if sub.client != nil {
rsubs := &s.gateway.rsubs
c := sub.client
sli, _ := rsubs.Load(c)
if change > 0 {
var sl *Sublist
if sli == nil {
sl = NewSublistNoCache()
rsubs.Store(c, sl)
} else {
sl = sli.(*Sublist)
}
sl.Insert(sub)
time.AfterFunc(s.gateway.recSubExp, func() {
sl.Remove(sub)
})
} else if sli != nil {
sl := sli.(*Sublist)
sl.Remove(sub)
if sl.Count() == 0 {
rsubs.Delete(c)
}
}
}
if first || last {
if entry.q {
s.sendQueueSubOrUnsubToGateways(accName, sub, first)
} else {
s.maybeSendSubOrUnsubToGateways(accName, sub, first)
}
}
}
// Returns true if the given subject is a GW routed reply subject,
// that is, starts with $GNR and is long enough to contain cluster/server hash
// and subject.
func isGWRoutedReply(subj []byte) bool {
return len(subj) > gwSubjectOffset && string(subj[:gwReplyPrefixLen]) == gwReplyPrefix
}
// Same than isGWRoutedReply but accepts the old prefix $GR and returns
// a boolean indicating if this is the old prefix
func isGWRoutedSubjectAndIsOldPrefix(subj []byte) (bool, bool) {
if isGWRoutedReply(subj) {
return true, false
}
if len(subj) > oldGWReplyStart && string(subj[:oldGWReplyPrefixLen]) == oldGWReplyPrefix {
return true, true
}
return false, false
}
// Returns true if subject starts with "$GNR.". This is to check that
// clients can't publish on this subject.
func hasGWRoutedReplyPrefix(subj []byte) bool {
return len(subj) > gwReplyPrefixLen && string(subj[:gwReplyPrefixLen]) == gwReplyPrefix
}
// Evaluates if the given reply should be mapped or not.
func (g *srvGateway) shouldMapReplyForGatewaySend(c *client, acc *Account, reply []byte) bool {
// If the reply is a service reply (_R_), we will use the account's internal
// clientinstead of the client handed to us. This client holds the wildcard
// for all service replies.
if isServiceReply(reply) {
c = acc.internalClient()
}
// If for this client there is a recent matching subscription interest
// then we will map.
sli, _ := g.rsubs.Load(c)
if sli == nil {
return false
}
sl := sli.(*Sublist)
if sl.Count() > 0 {
if r := sl.Match(string(reply)); len(r.psubs)+len(r.qsubs) > 0 {
return true
}
}
return false
}
var subPool = &sync.Pool{
New: func() interface{} {
return &subscription{}
},
}
// May send a message to all outbound gateways. It is possible
// that the message is not sent to a given gateway if for instance
// it is known that this gateway has no interest in the account or
// subject, etc..
// <Invoked from any client connection's readLoop>
func (c *client) sendMsgToGateways(acc *Account, msg, subject, reply []byte, qgroups [][]byte) bool {
gwsa := [16]*client{}
gws := gwsa[:0]
// This is in fast path, so avoid calling functions when possible.
// Get the outbound connections in place instead of calling
// getOutboundGatewayConnections().
gw := c.srv.gateway
gw.RLock()
for i := 0; i < len(gw.outo); i++ {
gws = append(gws, gw.outo[i])
}
thisClusterReplyPrefix := gw.replyPfx
thisClusterOldReplyPrefix := gw.oldReplyPfx
gw.RUnlock()
if len(gws) == 0 {
return false
}
var (
subj = string(subject)
queuesa = [512]byte{}
queues = queuesa[:0]
accName = acc.Name
mreplya [256]byte
mreply []byte
dstHash []byte
checkReply = len(reply) > 0
didDeliver bool
)
// Get a subscription from the pool
sub := subPool.Get().(*subscription)
// Check if the subject is on the reply prefix, if so, we
// need to send that message directly to the origin cluster.
directSend, old := isGWRoutedSubjectAndIsOldPrefix(subject)
if directSend {
if old {
dstHash = subject[oldGWReplyPrefixLen : oldGWReplyStart-1]
} else {
dstHash = subject[gwClusterOffset : gwClusterOffset+gwHashLen]
}
}
for i := 0; i < len(gws); i++ {
gwc := gws[i]
if directSend {
gwc.mu.Lock()
var ok bool
if gwc.gw.cfg != nil {
if old {
ok = bytes.Equal(dstHash, gwc.gw.cfg.oldHash)
} else {
ok = bytes.Equal(dstHash, gwc.gw.cfg.hash)
}
}
gwc.mu.Unlock()
if !ok {
continue
}
} else {
// Plain sub interest and queue sub results for this account/subject
psi, qr := gwc.gatewayInterest(accName, subj)
if !psi && qr == nil {
continue
}
queues = queuesa[:0]
if qr != nil {
for i := 0; i < len(qr.qsubs); i++ {
qsubs := qr.qsubs[i]
if len(qsubs) > 0 {
queue := qsubs[0].queue
add := true
for _, qn := range qgroups {
if bytes.Equal(queue, qn) {
add = false
break
}
}
if add {
qgroups = append(qgroups, queue)
queues = append(queues, queue...)
queues = append(queues, ' ')
}
}
}
}
if !psi && len(queues) == 0 {
continue
}
}
if checkReply {
// Check/map only once
checkReply = false
// Assume we will use original
mreply = reply
// Decide if we should map.
if gw.shouldMapReplyForGatewaySend(c, acc, reply) {
mreply = mreplya[:0]
gwc.mu.Lock()
useOldPrefix := gwc.gw.useOldPrefix
gwc.mu.Unlock()
if useOldPrefix {
mreply = append(mreply, thisClusterOldReplyPrefix...)
} else {
mreply = append(mreply, thisClusterReplyPrefix...)
}
mreply = append(mreply, reply...)
}
}
// Setup the message header.
// Make sure we are an 'R' proto by default
c.msgb[0] = 'R'
mh := c.msgb[:msgHeadProtoLen]
mh = append(mh, accName...)
mh = append(mh, ' ')
mh = append(mh, subject...)
mh = append(mh, ' ')
if len(queues) > 0 {
if reply != nil {
mh = append(mh, "+ "...) // Signal that there is a reply.
mh = append(mh, mreply...)
mh = append(mh, ' ')
} else {
mh = append(mh, "| "...) // Only queues
}
mh = append(mh, queues...)
} else if reply != nil {
mh = append(mh, mreply...)
mh = append(mh, ' ')
}
// Headers
hasHeader := c.pa.hdr > 0
canReceiveHeader := gwc.headers
if hasHeader {
if canReceiveHeader {
mh[0] = 'H'
mh = append(mh, c.pa.hdb...)
mh = append(mh, ' ')
mh = append(mh, c.pa.szb...)
} else {
// If we are here we need to truncate the payload size
nsz := strconv.Itoa(c.pa.size - c.pa.hdr)
mh = append(mh, nsz...)
}
} else {
mh = append(mh, c.pa.szb...)
}
mh = append(mh, CR_LF...)
// We reuse the subscription object that we pass to deliverMsg.
// So set/reset important fields.
sub.nm, sub.max = 0, 0
sub.client = gwc
sub.subject = subject
didDeliver = c.deliverMsg(sub, subject, mreply, mh, msg, false) || didDeliver
}
// Done with subscription, put back to pool. We don't need
// to reset content since we explicitly set when using it.
subPool.Put(sub)
return didDeliver
}
// Possibly sends an A- to the remote gateway `c`.
// Invoked when processing an inbound message and the account is not found.
// A check under a lock that protects processing of SUBs and UNSUBs is
// done to make sure that we don't send the A- if a subscription has just
// been created at the same time, which would otherwise results in the
// remote never sending messages on this account until a new subscription
// is created.
func (s *Server) gatewayHandleAccountNoInterest(c *client, accName []byte) {
// Check and possibly send the A- under this lock.
s.gateway.pasi.Lock()
defer s.gateway.pasi.Unlock()
si, inMap := s.gateway.pasi.m[string(accName)]
if inMap && si != nil && len(si) > 0 {
return
}
c.sendAccountUnsubToGateway(accName)
}
// Helper that sends an A- to this remote gateway if not already done.
// This function should not be invoked directly but instead be invoked
// by functions holding the gateway.pasi's Lock.
func (c *client) sendAccountUnsubToGateway(accName []byte) {
// Check if we have sent the A- or not.
c.mu.Lock()
e, sent := c.gw.insim[string(accName)]
if e != nil || !sent {
// Add a nil value to indicate that we have sent an A-
// so that we know to send A+ when needed.
c.gw.insim[string(accName)] = nil
var protoa [256]byte
proto := protoa[:0]
proto = append(proto, aUnsubBytes...)
proto = append(proto, accName...)
proto = append(proto, CR_LF...)
c.enqueueProto(proto)
if c.trace {
c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
}
}
c.mu.Unlock()
}
// Possibly sends an A- for this account or RS- for this subject.
// Invoked when processing an inbound message and the account is found
// but there is no interest on this subject.
// A test is done under a lock that protects processing of SUBs and UNSUBs
// and if there is no subscription at this time, we send an A-. If there
// is at least a subscription, but no interest on this subject, we send
// an RS- for this subject (if not already done).
func (s *Server) gatewayHandleSubjectNoInterest(c *client, acc *Account, accName, subject []byte) {
s.gateway.pasi.Lock()
defer s.gateway.pasi.Unlock()
// If there is no subscription for this account, we would normally
// send an A-, however, if this account has the internal subscription
// for service reply, send a specific RS- for the subject instead.
hasSubs := acc.sl.Count() > 0
if !hasSubs {
acc.mu.RLock()
hasSubs = acc.siReply != nil
acc.mu.RUnlock()
}
// If there is at least a subscription, possibly send RS-
if hasSubs {
sendProto := false
c.mu.Lock()
// Send an RS- protocol if not already done and only if
// not in the modeInterestOnly.
e := c.gw.insim[string(accName)]
if e == nil {
e = &insie{ni: make(map[string]struct{})}
e.ni[string(subject)] = struct{}{}
c.gw.insim[string(accName)] = e
sendProto = true
} else if e.ni != nil {
// If we are not in modeInterestOnly, check if we
// have already sent an RS-
if _, alreadySent := e.ni[string(subject)]; !alreadySent {
// TODO(ik): pick some threshold as to when
// we need to switch mode
if len(e.ni) >= gatewayMaxRUnsubBeforeSwitch {
// If too many RS-, switch to all-subs-mode.
c.gatewaySwitchAccountToSendAllSubs(e, string(accName))
} else {
e.ni[string(subject)] = struct{}{}
sendProto = true
}
}
}
if sendProto {
var (
protoa = [512]byte{}
proto = protoa[:0]
)
proto = append(proto, rUnsubBytes...)
proto = append(proto, accName...)
proto = append(proto, ' ')
proto = append(proto, subject...)
proto = append(proto, CR_LF...)
c.enqueueProto(proto)
if c.trace {
c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
}
}
c.mu.Unlock()
} else {
// There is not a single subscription, send an A- (if not already done).
c.sendAccountUnsubToGateway([]byte(acc.Name))
}
}
// Returns the cluster hash from the gateway reply prefix
func (g *srvGateway) getClusterHash() []byte {
g.RLock()
clusterHash := g.replyPfx[gwClusterOffset : gwClusterOffset+gwHashLen]
g.RUnlock()
return clusterHash
}
// Returns the route with given hash or nil if not found.
func (s *Server) getRouteByHash(srvHash []byte) *client {
var route *client
if v, ok := s.routesByHash.Load(string(srvHash)); ok {
route = v.(*client)
}
return route
}
// Returns the subject from the routed reply
func getSubjectFromGWRoutedReply(reply []byte, isOldPrefix bool) []byte {
if isOldPrefix {
return reply[oldGWReplyStart:]
}
return reply[gwSubjectOffset:]
}
// This should be invoked only from processInboundGatewayMsg() or
// processInboundRoutedMsg() and is checking if the subject
// (c.pa.subject) has the $GNR prefix. If so, this is processed
// as a GW reply and `true` is returned to indicate to the caller
// that it should stop processing.
// If gateway is not enabled on this server or if the subject
// does not start with $GR, `false` is returned and caller should
// process message as usual.
func (c *client) handleGatewayReply(msg []byte) (processed bool) {
// Do not handle GW prefixed messages if this server does not have
// gateway enabled or if the subject does not start with the previx.
if !c.srv.gateway.enabled {
return false
}
isGWPrefix, oldPrefix := isGWRoutedSubjectAndIsOldPrefix(c.pa.subject)
if !isGWPrefix {
return false
}
// Save original subject (in case we have to forward)
orgSubject := c.pa.subject
var clusterHash []byte
var srvHash []byte
var subject []byte
if oldPrefix {
clusterHash = c.pa.subject[oldGWReplyPrefixLen : oldGWReplyStart-1]
// Check if this reply is intended for our cluster.
if !bytes.Equal(clusterHash, c.srv.gateway.oldHash) {
// We could report, for now, just drop.
return true
}
subject = c.pa.subject[oldGWReplyStart:]
} else {
clusterHash = c.pa.subject[gwClusterOffset : gwClusterOffset+gwHashLen]
// Check if this reply is intended for our cluster.
if !bytes.Equal(clusterHash, c.srv.gateway.getClusterHash()) {
// We could report, for now, just drop.
return true
}
srvHash = c.pa.subject[gwServerOffset : gwServerOffset+gwHashLen]
subject = c.pa.subject[gwSubjectOffset:]
}
var route *client
// If the origin is not this server, get the route this should be sent to.
if c.kind == GATEWAY && srvHash != nil && !bytes.Equal(srvHash, c.srv.hash) {
route = c.srv.getRouteByHash(srvHash)
// This will be possibly nil, and in this case we will try to process
// the interest from this server.
}
// Adjust the subject
c.pa.subject = subject
// Use a stack buffer to rewrite c.pa.cache since we only need it for
// getAccAndResultFromCache()
var _pacache [256]byte
pacache := _pacache[:0]
pacache = append(pacache, c.pa.account...)
pacache = append(pacache, ' ')
pacache = append(pacache, c.pa.subject...)
c.pa.pacache = pacache
acc, r := c.getAccAndResultFromCache()
if acc == nil {
typeConn := "routed"
if c.kind == GATEWAY {
typeConn = "gateway"
}
c.Debugf("Unknown account %q for %s message on subject: %q", c.pa.account, typeConn, c.pa.subject)
if c.kind == GATEWAY {
c.srv.gatewayHandleAccountNoInterest(c, c.pa.account)
}
return true
}
// If route is nil, we will process the incoming message locally.
if route == nil {
// Check if this is a service reply subject (_R_)
isServiceReply := len(acc.imports.services) > 0 && isServiceReply(c.pa.subject)
var queues [][]byte
if len(r.psubs)+len(r.qsubs) > 0 {
flags := pmrCollectQueueNames | pmrIgnoreEmptyQueueFilter
// If this message came from a ROUTE, allow to pick queue subs
// only if the message was directly sent by the "gateway" server
// in our cluster that received it.
if c.kind == ROUTER {
flags |= pmrAllowSendFromRouteToRoute
}
_, queues = c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, flags)
}
// Since this was a reply that made it to the origin cluster,
// we now need to send the message with the real subject to
// gateways in case they have interest on that reply subject.
if !isServiceReply {
c.sendMsgToGateways(acc, msg, c.pa.subject, c.pa.reply, queues)
}
} else if c.kind == GATEWAY {
// Only if we are a gateway connection should we try to route
// to the server where the request originated.
var bufa [256]byte
var buf = bufa[:0]
buf = append(buf, msgHeadProto...)
buf = append(buf, acc.Name...)
buf = append(buf, ' ')
buf = append(buf, orgSubject...)
buf = append(buf, ' ')
if len(c.pa.reply) > 0 {
buf = append(buf, c.pa.reply...)
buf = append(buf, ' ')
}
buf = append(buf, c.pa.szb...)
mhEnd := len(buf)
buf = append(buf, _CRLF_...)
buf = append(buf, msg...)
route.mu.Lock()
route.enqueueProto(buf)
if route.trace {
route.traceOutOp("", buf[:mhEnd])
}
route.mu.Unlock()
}
return true
}
// Process a message coming from a remote gateway. Send to any sub/qsub
// in our cluster that is matching. When receiving a message for an
// account or subject for which there is no interest in this cluster
// an A-/RS- protocol may be send back.
// <Invoked from inbound connection's readLoop>
func (c *client) processInboundGatewayMsg(msg []byte) {
// Update statistics
c.in.msgs++
// The msg includes the CR_LF, so pull back out for accounting.
c.in.bytes += int32(len(msg) - LEN_CR_LF)
if c.opts.Verbose {
c.sendOK()
}
// Mostly under testing scenarios.
if c.srv == nil {
return
}
// If the subject (c.pa.subject) has the gateway prefix, this function will
// handle it.
if c.handleGatewayReply(msg) {
// We are done here.
return
}
acc, r := c.getAccAndResultFromCache()
if acc == nil {
c.Debugf("Unknown account %q for gateway message on subject: %q", c.pa.account, c.pa.subject)
c.srv.gatewayHandleAccountNoInterest(c, c.pa.account)
return
}
// Check if this is a service reply subject (_R_)
noInterest := len(r.psubs) == 0
checkNoInterest := true
if acc.imports.services != nil {
if isServiceReply(c.pa.subject) {
checkNoInterest = false
} else {
// We need to eliminate the subject interest from the service imports here to
// make sure we send the proper no interest if the service import is the only interest.
noInterest = true
for _, sub := range r.psubs {
if sub.client.kind != ACCOUNT {
noInterest = false
break
}
}
}
}
if checkNoInterest && noInterest {
// If there is no interest on plain subs, possibly send an RS-,
// even if there is qsubs interest.
c.srv.gatewayHandleSubjectNoInterest(c, acc, c.pa.account, c.pa.subject)
// If there is also no queue filter, then no point in continuing
// (even if r.qsubs i > 0).
if len(c.pa.queues) == 0 {
return
}
}
c.processMsgResults(acc, r, msg, nil, c.pa.subject, c.pa.reply, pmrNoFlag)
}
// Indicates that the remote which we are sending messages to
// has decided to send us all its subs interest so that we
// stop doing optimistic sends.
// <Invoked from outbound connection's readLoop>
func (c *client) gatewayAllSubsReceiveStart(info *Info) {
account := getAccountFromGatewayCommand(c, info, "start")
if account == "" {
return
}
c.Noticef("Gateway %q: switching account %q to %s mode",
info.Gateway, account, InterestOnly)
// Since the remote would send us this start command
// only after sending us too many RS- for this account,
// we should always have an entry here.
// TODO(ik): Should we close connection with protocol violation
// error if that happens?
ei, _ := c.gw.outsim.Load(account)
if ei != nil {
e := ei.(*outsie)
e.Lock()
e.mode = Transitioning
e.Unlock()
} else {
e := &outsie{sl: NewSublistWithCache()}
e.mode = Transitioning
c.mu.Lock()
c.gw.outsim.Store(account, e)
c.mu.Unlock()
}
}
// Indicates that the remote has finished sending all its
// subscriptions and we should now not send unless we know
// there is explicit interest.
// <Invoked from outbound connection's readLoop>
func (c *client) gatewayAllSubsReceiveComplete(info *Info) {
account := getAccountFromGatewayCommand(c, info, "complete")
if account == "" {
return
}
// Done receiving all subs from remote. Set the `ni`
// map to nil so that gatewayInterest() no longer
// uses it.
ei, _ := c.gw.outsim.Load(string(account))
if ei != nil {
e := ei.(*outsie)
// Needs locking here since `ni` is checked by
// many go-routines calling gatewayInterest()
e.Lock()
e.ni = nil
e.mode = InterestOnly
e.Unlock()
c.Noticef("Gateway %q: switching account %q to %s mode complete",
info.Gateway, account, InterestOnly)
}
}
// small helper to get the account name from the INFO command.
func getAccountFromGatewayCommand(c *client, info *Info, cmd string) string {
if info.GatewayCmdPayload == nil {
c.sendErrAndErr(fmt.Sprintf("Account absent from receive-all-subscriptions-%s command", cmd))
c.closeConnection(ProtocolViolation)
return ""
}
return string(info.GatewayCmdPayload)
}
// Switch to send-all-subs mode for the given gateway and account.
// This is invoked when processing an inbound message and we
// reach a point where we had to send a lot of RS- for this
// account. We will send an INFO protocol to indicate that we
// start sending all our subs (for this account), followed by
// all subs (RS+) and finally an INFO to indicate the end of it.
// The remote will then send messages only if it finds explicit
// interest in the sublist created based on all RS+ that we just
// sent.
// The client's lock is held on entry.
// <Invoked from inbound connection's readLoop>
func (c *client) gatewaySwitchAccountToSendAllSubs(e *insie, accName string) {
// Set this map to nil so that the no-interest is no longer checked.
e.ni = nil
// Switch mode to transitioning to prevent switchAccountToInterestMode
// to possibly call this function multiple times.
e.mode = Transitioning
s := c.srv
remoteGWName := c.gw.name
c.Noticef("Gateway %q: switching account %q to %s mode",
remoteGWName, accName, InterestOnly)
// Function that will create an INFO protocol
// and set proper command.
sendCmd := func(cmd byte, useLock bool) {
// Use bare server info and simply set the
// gateway name and command
info := Info{
Gateway: s.getGatewayName(),
GatewayCmd: cmd,
GatewayCmdPayload: []byte(accName),
}
b, _ := json.Marshal(&info)
infoJSON := []byte(fmt.Sprintf(InfoProto, b))
if useLock {
c.mu.Lock()
}
c.enqueueProto(infoJSON)
if useLock {
c.mu.Unlock()
}
}
// Send the start command. When remote receives this,
// it may continue to send optimistic messages, but
// it will start to register RS+/RS- in sublist instead
// of noInterest map.
sendCmd(gatewayCmdAllSubsStart, false)
// Execute this in separate go-routine as to not block
// the readLoop (which may cause the otherside to close
// the connection due to slow consumer)
s.startGoRoutine(func() {
defer s.grWG.Done()
s.sendAccountSubsToGateway(c, []byte(accName))
// Send the complete command. When the remote receives
// this, it will not send a message unless it has a
// matching sub from us.
sendCmd(gatewayCmdAllSubsComplete, true)
c.Noticef("Gateway %q: switching account %q to %s mode complete",
remoteGWName, accName, InterestOnly)
})
}
// Keeps track of the routed reply to be used when/if application
// sends back a message on the reply without the prefix.
// Client lock held on entry. This is a server receiver because
// we use a timer interval that is avail in Server.gateway object.
func (s *Server) trackGWReply(c *client, reply []byte) {
ttl := s.gateway.recSubExp
rm := c.gwrm
var we bool // will be true if map was empty on entry
if rm == nil {
rm = make(map[string]*gwReplyMap)
c.gwrm = rm
we = true
} else {
we = len(rm) == 0
}
// We need to make a copy so that we don't reference the underlying
// read buffer.
ms := string(reply)
grm := &gwReplyMap{ms: ms, exp: time.Now().Add(ttl).UnixNano()}
// If we are here with the same key but different mapped replies
// (say $GNR._.A.srv1.bar and then $GNR._.B.srv2.bar), we need to
// store it otherwise we would take the risk of the reply not
// making it back.
rm[ms[gwSubjectOffset:]] = grm
if we {
atomic.StoreInt32(&c.cgwrt, 1)
s.gwrm.m.Store(c, nil)
if atomic.CompareAndSwapInt32(&s.gwrm.w, 0, 1) {
select {
case s.gwrm.ch <- ttl:
default:
}
}
}
}
// Starts a long lived go routine that is responsible to
// remove GW reply mapping that have expired.
func (s *Server) startGWReplyMapExpiration() {
s.mu.Lock()
s.gwrm.ch = make(chan time.Duration, 1)
s.mu.Unlock()
s.startGoRoutine(func() {
defer s.grWG.Done()
t := time.NewTimer(time.Hour)
var ttl time.Duration
for {
select {
case <-t.C:
if ttl == 0 {
t.Reset(time.Hour)
continue
}
now := time.Now().UnixNano()
mapEmpty := true
s.gwrm.m.Range(func(k, _ interface{}) bool {
c := k.(*client)
c.mu.Lock()
for k, grm := range c.gwrm {
if grm.exp <= now {
delete(c.gwrm, k)
if len(c.gwrm) == 0 {
atomic.StoreInt32(&c.cgwrt, 0)
s.gwrm.m.Delete(c)
}
}
}
c.mu.Unlock()
mapEmpty = false
return true
})
if mapEmpty && atomic.CompareAndSwapInt32(&s.gwrm.w, 1, 0) {
ttl = 0
t.Reset(time.Hour)
} else {
t.Reset(ttl)
}
case cttl := <-s.gwrm.ch:
ttl = cttl
t.Reset(ttl)
case <-s.quitCh:
return
}
}
})
}
| 1 | 12,249 | Just making a note here that this may break pre GWs between pre 2.2.0 and 2.2.0 servers. Not sure, will have to experiment/dig a bit more. | nats-io-nats-server | go |
@@ -93,6 +93,8 @@ public class WebUtils {
return "Killing";
case DISPATCHING:
return "Dispatching";
+ case POD_FAILED:
+ return "Pod Failure";
default:
}
return "Unknown"; | 1 | /*
* Copyright 2012 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.webapp.servlet;
import static azkaban.Constants.ConfigurationKeys.AZKABAN_SERVER_HOST_NAME;
import azkaban.ServiceProvider;
import azkaban.executor.Status;
import azkaban.spi.AzkabanEventReporter;
import azkaban.spi.EventType;
import azkaban.webapp.AzkabanWebServer;
import com.google.common.base.Strings;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.LoggerFactory;
public class WebUtils {
public static final String X_FORWARDED_FOR_HEADER = "X-Forwarded-For";
private static final long ONE_KB = 1024;
private static final long ONE_MB = 1024 * ONE_KB;
private static final long ONE_GB = 1024 * ONE_MB;
private static final long ONE_TB = 1024 * ONE_GB;
private static AzkabanEventReporter azkabanEventReporter;
static {
try {
azkabanEventReporter = ServiceProvider.SERVICE_PROVIDER
.getInstance(AzkabanEventReporter.class);
} catch (Exception e) {
LoggerFactory.getLogger(WebUtils.class).warn("AzkabanEventReporter not configured", e);
}
}
public static String displayBytes(final long sizeBytes) {
final NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
if (sizeBytes >= ONE_TB) {
return nf.format(sizeBytes / (double) ONE_TB) + " tb";
} else if (sizeBytes >= ONE_GB) {
return nf.format(sizeBytes / (double) ONE_GB) + " gb";
} else if (sizeBytes >= ONE_MB) {
return nf.format(sizeBytes / (double) ONE_MB) + " mb";
} else if (sizeBytes >= ONE_KB) {
return nf.format(sizeBytes / (double) ONE_KB) + " kb";
} else {
return sizeBytes + " B";
}
}
public static String formatStatus(final Status status) {
switch (status) {
case SUCCEEDED:
return "Success";
case FAILED:
return "Failed";
case RUNNING:
return "Running";
case DISABLED:
return "Disabled";
case KILLED:
return "Killed";
case FAILED_FINISHING:
return "Running w/Failure";
case PREPARING:
return "Preparing";
case READY:
return "Ready";
case PAUSED:
return "Paused";
case SKIPPED:
return "Skipped";
case KILLING:
return "Killing";
case DISPATCHING:
return "Dispatching";
default:
}
return "Unknown";
}
/**
* Gets the actual client IP address on a best effort basis as user could be sitting
* behind a VPN. Get the IP by inspecting the X-Forwarded-For HTTP header or using the
* provided 'remote IP address' from the low level TCP connection from the client.
*
* If multiple IP addresses are provided in the X-Forwarded-For header then the first one (first
* hop) is used
*
* @param httpHeaders List of HTTP headers for the current request
* @param remoteAddr The client IP address and port from the current request's TCP connection
* @return The actual client IP address
*/
// TODO djaiswal83: Refactor this code and merge into single API
public static String getRealClientIpAddr(final Map<String, String> httpHeaders,
final String remoteAddr) {
// If some upstream device added an X-Forwarded-For header
// use it for the client ip
// This will support scenarios where load balancers or gateways
// front the Azkaban web server and a changing Ip address invalidates the session
String clientIp = httpHeaders.getOrDefault(X_FORWARDED_FOR_HEADER, null);
if (clientIp == null) {
clientIp = remoteAddr;
} else {
// header can contain comma separated list of upstream servers - get the first one
final String[] ips = clientIp.split(",");
clientIp = ips[0];
}
// Strip off port and only get IP address
// todo: this is broken for IPv6, where e.g. a "loopback" address looks like "0:0:0:0:0:0:0:1"
final String[] parts = clientIp.split(":");
clientIp = parts[0];
return clientIp;
}
/**
* Gets the actual client IP address on a best effort basis as user could be sitting
* behind a VPN. Get the IP by inspecting the X-Forwarded-For HTTP header or using the
* provided 'remote IP address' from the low level TCP connection from the client.
*
* If multiple IP addresses are provided in the X-Forwarded-For header then the first one (first
* hop) is used
*
* @param req HttpServletRequest
* @return The actual client IP address
*/
public static String getRealClientIpAddr(final HttpServletRequest req) {
// If some upstream device added an X-Forwarded-For header
// use it for the client ip
// This will support scenarios where load balancers or gateways
// front the Azkaban web server and a changing Ip address invalidates
// the session
final HashMap<String, String> headers = new HashMap<>();
headers.put(WebUtils.X_FORWARDED_FOR_HEADER,
req.getHeader(WebUtils.X_FORWARDED_FOR_HEADER.toLowerCase()));
return WebUtils.getRealClientIpAddr(headers, req.getRemoteAddr());
}
private static String hostName;
static {
try {
hostName = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
hostName = "unknown";
}
}
/**
* Report login/logout events via {@link AzkabanEventReporter}, if configured.
* @param eventType login or logout
* @param username if known
* @param ip address of originating host
* @param isSuccess AKA outcome
* @param message AKA reason
*/
public static void reportLoginEvent(final EventType eventType, final String username,
final String ip, final boolean isSuccess, final String message) {
if (azkabanEventReporter != null) {
final Map<String, String> metadata = new HashMap<>();
metadata.put("azkabanHost",
AzkabanWebServer.getAzkabanProperties().getString(AZKABAN_SERVER_HOST_NAME, hostName));
metadata.put("sessionUser", Strings.isNullOrEmpty(username) ? "unknown" : username);
metadata.put("sessionIP", ip);
metadata.put("reason", message);
metadata.put("appOutcome", isSuccess ? "SUCCESS" : "FAILURE");
azkabanEventReporter.report(eventType, metadata);
}
}
public static void reportLoginEvent(final EventType eventType, final String username, final String ip) {
reportLoginEvent(eventType, username, ip, true, null);
}
}
| 1 | 22,146 | Shall we rename this status to CONTAINER_FAILED? ^^ cc: @sshardool | azkaban-azkaban | java |
@@ -30,6 +30,14 @@ const (
requestTimeout = 60 * time.Second
)
+// Fetcher defines an interface that may be used to fetch data from the network.
+type Fetcher interface {
+ // FetchTipSets will only fetch TipSets that evaluate to `false` when passed to `done`,
+ // this includes the provided `ts`. The TipSet that evaluates to true when
+ // passed to `done` will be in the returned slice. The returns slice of TipSets is in Traversal order.
+ FetchTipSets(context.Context, types.TipSetKey, peer.ID, func(types.TipSet) (bool, error)) ([]types.TipSet, error)
+}
+
// interface conformance check
var _ Fetcher = (*GraphSyncFetcher)(nil)
| 1 | package net
import (
"context"
"fmt"
"time"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-graphsync"
bstore "github.com/ipfs/go-ipfs-blockstore"
logging "github.com/ipfs/go-log"
"github.com/ipld/go-ipld-prime"
ipldfree "github.com/ipld/go-ipld-prime/impl/free"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
selectorbuilder "github.com/ipld/go-ipld-prime/traversal/selector/builder"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/pkg/errors"
"github.com/filecoin-project/go-filecoin/consensus"
"github.com/filecoin-project/go-filecoin/types"
)
var logGraphsyncFetcher = logging.Logger("net.graphsync_fetcher")
const (
// Timeout for a single graphsync request (which may be for many blocks).
// We might prefer this timeout to scale with the number of blocks expected in the fetch,
// when that number is large.
requestTimeout = 60 * time.Second
)
// interface conformance check
var _ Fetcher = (*GraphSyncFetcher)(nil)
// GraphExchange is an interface wrapper to Graphsync so it can be stubbed in
// unit testing
type GraphExchange interface {
Request(ctx context.Context, p peer.ID, root ipld.Link, selector ipld.Node) (<-chan graphsync.ResponseProgress, <-chan error)
}
type graphsyncFallbackPeerTracker interface {
List() []*types.ChainInfo
}
// GraphSyncFetcher is used to fetch data over the network. It is implemented
// using a Graphsync exchange to fetch tipsets recursively
type GraphSyncFetcher struct {
exchange GraphExchange
validator consensus.BlockSyntaxValidator
store bstore.Blockstore
ssb selectorbuilder.SelectorSpecBuilder
peerTracker graphsyncFallbackPeerTracker
}
// NewGraphSyncFetcher returns a GraphsyncFetcher wired up to the input Graphsync exchange and
// attached local blockservice for reloading blocks in memory once they are returned
func NewGraphSyncFetcher(ctx context.Context, exchange GraphExchange, blockstore bstore.Blockstore,
bv consensus.BlockSyntaxValidator, pt graphsyncFallbackPeerTracker) *GraphSyncFetcher {
gsf := &GraphSyncFetcher{
store: blockstore,
validator: bv,
exchange: exchange,
ssb: selectorbuilder.NewSelectorSpecBuilder(ipldfree.NodeBuilder()),
peerTracker: pt,
}
return gsf
}
// Graphsync can fetch a fixed number of tipsets from a remote peer recursively
// with a single request. We don't know until we get all of the response whether
// our final tipset was included in the response
//
// When fetching tipsets we try to balance performance for two competing cases:
// - an initial chain sync that is likely to fetch lots and lots of tipsets
// - a future update sync that is likely to fetch only a few
//
// To do this, the Graphsync fetcher starts fetching a single tipset at a time,
// then gradually ramps up to fetch lots of tipsets at once, up to a fixed limit
//
// The constants below determine the maximum number of tipsets fetched at once
// (maxRecursionDepth) and how fast the ramp up is (recursionMultipler)
const maxRecursionDepth = 64
const recursionMultiplier = 4
// FetchTipSets gets Tipsets starting from the given tipset key and continuing until
// the done function returns true or errors
//
// For now FetchTipSets operates in two parts:
// 1. It fetches relevant blocks through Graphsync, which writes them to the block store
// 2. It reads them from the block store and validates their syntax as blocks
// and constructs a tipset
// This does have a potentially unwanted side effect of writing blocks to the block store
// that later don't validate (bitswap actually does this as well)
//
// TODO: In the future, the blocks will be validated directly through graphsync as
// go-filecoin migrates to the same IPLD library used by go-graphsync (go-ipld-prime)
//
// See: https://github.com/filecoin-project/go-filecoin/issues/3175
func (gsf *GraphSyncFetcher) FetchTipSets(ctx context.Context, tsKey types.TipSetKey, initialPeer peer.ID, done func(types.TipSet) (bool, error)) ([]types.TipSet, error) {
rpf := newRequestPeerFinder(gsf.peerTracker, initialPeer)
// fetch initial tipset
startingTipset, err := gsf.fetchFirstTipset(ctx, tsKey, rpf)
if err != nil {
return nil, err
}
// fetch remaining tipsets recursively
return gsf.fetchRemainingTipsets(ctx, startingTipset, rpf, done)
}
func (gsf *GraphSyncFetcher) fetchFirstTipset(ctx context.Context, key types.TipSetKey, rpf *requestPeerFinder) (types.TipSet, error) {
blocksToFetch := key.ToSlice()
for {
peer := rpf.CurrentPeer()
logGraphsyncFetcher.Infof("fetching initial tipset %s from peer %s", key, peer)
err := gsf.fetchBlocks(ctx, blocksToFetch, peer)
if err != nil {
logGraphsyncFetcher.Infof("request failed: %s", err)
}
var verifiedTip types.TipSet
verifiedTip, blocksToFetch, err = gsf.loadAndVerify(ctx, key)
if err != nil {
return types.UndefTipSet, err
}
if len(blocksToFetch) == 0 {
return verifiedTip, nil
}
logGraphsyncFetcher.Warningf("incomplete fetch for first tipset %s, trying new peer", key)
// Some of the blocks may have been fetched, but avoid tricksy optimization here and just
// request the whole bunch again. Graphsync internally will avoid redundant network requests.
err = rpf.FindNextPeer()
if err != nil {
return types.UndefTipSet, errors.Wrapf(err, "fetching tipset: %s", key)
}
}
}
func (gsf *GraphSyncFetcher) fetchRemainingTipsets(ctx context.Context, startingTipset types.TipSet, rpf *requestPeerFinder, done func(types.TipSet) (bool, error)) ([]types.TipSet, error) {
out := []types.TipSet{startingTipset}
isDone, err := done(startingTipset)
if err != nil {
return nil, err
}
// fetch remaining tipsets recursively
recursionDepth := 1
anchor := startingTipset // The tipset above the one we actually want to fetch.
for !isDone {
// Because a graphsync query always starts from a single CID,
// we fetch tipsets anchored from any block in the last (i.e. highest) tipset and
// recursively fetching sets of parents.
childBlock := anchor.At(0)
peer := rpf.CurrentPeer()
logGraphsyncFetcher.Infof("fetching chain from height %d, block %s, peer %s, %d levels", childBlock.Height, childBlock.Cid(), peer, recursionDepth)
err := gsf.fetchBlocksRecursively(ctx, childBlock.Cid(), peer, recursionDepth)
if err != nil {
// something went wrong in a graphsync request, but we want to keep trying other peers, so
// just log error
logGraphsyncFetcher.Infof("request failed, trying another peer: %s", err)
}
var incomplete []cid.Cid
for i := 0; !isDone && i < recursionDepth; i++ {
tsKey, err := anchor.Parents()
if err != nil {
return nil, err
}
var verifiedTip types.TipSet
verifiedTip, incomplete, err = gsf.loadAndVerify(ctx, tsKey)
if err != nil {
return nil, err
}
if len(incomplete) == 0 {
out = append(out, verifiedTip)
isDone, err = done(verifiedTip)
if err != nil {
return nil, err
}
anchor = verifiedTip
} else {
logGraphsyncFetcher.Warningf("incomplete fetch for tipset %s, trying new peer", tsKey)
err := rpf.FindNextPeer()
if err != nil {
return nil, errors.Wrapf(err, "fetching tipset: %s", tsKey)
}
break // Stop verifying, make another fetch
}
}
if len(incomplete) == 0 && recursionDepth < maxRecursionDepth {
recursionDepth *= recursionMultiplier
}
}
return out, nil
}
// fetchBlocks requests a single set of cids as individual blocks, fetching
// non-recursively
func (gsf *GraphSyncFetcher) fetchBlocks(ctx context.Context, cids []cid.Cid, targetPeer peer.ID) error {
selector := gsf.ssb.ExploreFields(func(efsb selectorbuilder.ExploreFieldsSpecBuilder) {
efsb.Insert("messages", gsf.ssb.Matcher())
efsb.Insert("messageReceipts", gsf.ssb.Matcher())
}).Node()
errChans := make([]<-chan error, 0, len(cids))
requestCtx, requestCancel := context.WithTimeout(ctx, requestTimeout)
defer requestCancel()
for _, c := range cids {
_, errChan := gsf.exchange.Request(requestCtx, targetPeer, cidlink.Link{Cid: c}, selector)
errChans = append(errChans, errChan)
}
// Any of the multiple parallel requests might fail. Wait for all of them to complete, then
// return any error (in this case, the last one to be received).
var anyError error
for _, errChan := range errChans {
for err := range errChan {
anyError = err
}
}
return anyError
}
// fetchBlocksRecursively gets the blocks from recursionDepth ancestor tipsets
// starting from baseCid.
func (gsf *GraphSyncFetcher) fetchBlocksRecursively(ctx context.Context, baseCid cid.Cid, targetPeer peer.ID, recursionDepth int) error {
requestCtx, requestCancel := context.WithTimeout(ctx, requestTimeout)
defer requestCancel()
// recursive selector to fetch n sets of parent blocks
// starting from block matching base cid:
// - fetch all parent blocks, with messages/receipts
// - with exactly the first parent block, repeat again for its parents
// - continue up to recursion depth
selector := gsf.ssb.ExploreRecursive(recursionDepth, gsf.ssb.ExploreFields(func(efsb selectorbuilder.ExploreFieldsSpecBuilder) {
efsb.Insert("parents", gsf.ssb.ExploreUnion(
gsf.ssb.ExploreAll(
gsf.ssb.ExploreFields(func(efsb selectorbuilder.ExploreFieldsSpecBuilder) {
efsb.Insert("messages", gsf.ssb.Matcher())
efsb.Insert("messageReceipts", gsf.ssb.Matcher())
}),
),
gsf.ssb.ExploreIndex(0, gsf.ssb.ExploreRecursiveEdge()),
))
})).Node()
_, errChan := gsf.exchange.Request(requestCtx, targetPeer, cidlink.Link{Cid: baseCid}, selector)
for err := range errChan {
return err
}
return nil
}
// Loads the IPLD blocks for all blocks in a tipset, and checks for the presence of the
// message and receipt list structures in the store.
// Returns the tipset if complete. Otherwise it returns UndefTipSet and the CIDs of
// all blocks missing either their header, messages or receipts.
func (gsf *GraphSyncFetcher) loadAndVerify(ctx context.Context, key types.TipSetKey) (types.TipSet, []cid.Cid, error) {
// Load the block headers that exist.
tip, incomplete, err := gsf.loadTipHeaders(ctx, key)
if err != nil {
return types.UndefTipSet, nil, err
}
// Check that nested structures are also stored, recording any that are missing as incomplete.
for i := 0; i < tip.Len(); i++ {
blk := tip.At(i)
for _, link := range []cid.Cid{blk.Messages, blk.MessageReceipts} {
// TODO: validate the structures, don't just check for their presence #3232
ok, err := gsf.store.Has(link)
if err != nil {
return types.UndefTipSet, nil, err
}
if !ok {
incomplete = append(incomplete, blk.Cid())
}
}
}
if len(incomplete) > 0 {
tip = types.UndefTipSet
}
return tip, incomplete, nil
}
// Loads and validates the block headers for a tipset. Returns the tipset if complete,
// else the cids of blocks which are not yet stored.
func (gsf *GraphSyncFetcher) loadTipHeaders(ctx context.Context, key types.TipSetKey) (types.TipSet, []cid.Cid, error) {
rawBlocks := make([]blocks.Block, 0, key.Len())
var incomplete []cid.Cid
for it := key.Iter(); !it.Complete(); it.Next() {
hasBlock, err := gsf.store.Has(it.Value())
if err != nil {
return types.UndefTipSet, nil, err
}
if !hasBlock {
incomplete = append(incomplete, it.Value())
continue
}
rawBlock, err := gsf.store.Get(it.Value())
if err != nil {
return types.UndefTipSet, nil, err
}
rawBlocks = append(rawBlocks, rawBlock)
}
// Validate the headers.
validatedBlocks, err := sanitizeBlocks(ctx, rawBlocks, gsf.validator)
if err != nil || len(validatedBlocks) == 0 {
return types.UndefTipSet, incomplete, err
}
tip, err := types.NewTipSet(validatedBlocks...)
return tip, incomplete, err
}
type requestPeerFinder struct {
peerTracker graphsyncFallbackPeerTracker
currentPeer peer.ID
triedPeers map[peer.ID]struct{}
}
func newRequestPeerFinder(peerTracker graphsyncFallbackPeerTracker, initialPeer peer.ID) *requestPeerFinder {
pri := &requestPeerFinder{peerTracker, initialPeer, make(map[peer.ID]struct{})}
pri.triedPeers[initialPeer] = struct{}{}
return pri
}
func (pri *requestPeerFinder) CurrentPeer() peer.ID {
return pri.currentPeer
}
func (pri *requestPeerFinder) FindNextPeer() error {
chains := pri.peerTracker.List()
for _, chain := range chains {
if _, tried := pri.triedPeers[chain.Peer]; !tried {
pri.triedPeers[chain.Peer] = struct{}{}
pri.currentPeer = chain.Peer
return nil
}
}
return fmt.Errorf("Unable to find any untried peers")
}
| 1 | 21,226 | Thinking out loud here: I believe the only reason we need `peer.ID` as a parameter to this method is because we are not persisting blocks from pubsub (instead we are refetching them). If nodes persist the blocks they received over pubsub then I think we can guarantee peers we share a connection with (i.e. that are in the peer tracker) will always have the blocks we are fetching (else how would have we gotten the pubsub message). I imagine the concept of an `initialPeer` can go away once #2962 lands since the peers in the tracker will have the block. Although I don't think that covers the case of fetching blocks our peers have deemed semantically invalid and thus not stored... | filecoin-project-venus | go |
@@ -42,7 +42,7 @@ func init() {
// MatchExpression matches requests by evaluating a
// [CEL](https://github.com/google/cel-spec) expression.
// This enables complex logic to be expressed using a comfortable,
-// familiar syntax.
+// familiar syntax. The standard definitions of CEL functions and operators can be found [here](https://github.com/google/cel-spec/blob/master/doc/langdef.md#standard-definitions).
//
// This matcher's JSON interface is actually a string, not a struct.
// The generated docs are not correct because this type has custom | 1 | // Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"regexp"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/gogo/protobuf/proto"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/common/types/traits"
"github.com/google/cel-go/ext"
"github.com/google/cel-go/interpreter/functions"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
func init() {
caddy.RegisterModule(MatchExpression{})
}
// MatchExpression matches requests by evaluating a
// [CEL](https://github.com/google/cel-spec) expression.
// This enables complex logic to be expressed using a comfortable,
// familiar syntax.
//
// This matcher's JSON interface is actually a string, not a struct.
// The generated docs are not correct because this type has custom
// marshaling logic.
//
// COMPATIBILITY NOTE: This module is still experimental and is not
// subject to Caddy's compatibility guarantee.
type MatchExpression struct {
// The CEL expression to evaluate. Any Caddy placeholders
// will be expanded and situated into proper CEL function
// calls before evaluating.
Expr string
expandedExpr string
prg cel.Program
ta ref.TypeAdapter
}
// CaddyModule returns the Caddy module information.
func (MatchExpression) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.matchers.expression",
New: func() caddy.Module { return new(MatchExpression) },
}
}
// MarshalJSON marshals m's expression.
func (m MatchExpression) MarshalJSON() ([]byte, error) {
return json.Marshal(m.Expr)
}
// UnmarshalJSON unmarshals m's expression.
func (m *MatchExpression) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &m.Expr)
}
// Provision sets ups m.
func (m *MatchExpression) Provision(_ caddy.Context) error {
// replace placeholders with a function call - this is just some
// light (and possibly naïve) syntactic sugar
m.expandedExpr = placeholderRegexp.ReplaceAllString(m.Expr, placeholderExpansion)
// our type adapter expands CEL's standard type support
m.ta = celTypeAdapter{}
// create the CEL environment
env, err := cel.NewEnv(
cel.Declarations(
decls.NewIdent("request", httpRequestObjectType, nil),
decls.NewFunction(placeholderFuncName,
decls.NewOverload(placeholderFuncName+"_httpRequest_string",
[]*exprpb.Type{httpRequestObjectType, decls.String},
decls.Any)),
),
cel.CustomTypeAdapter(m.ta),
ext.Strings(),
)
if err != nil {
return fmt.Errorf("setting up CEL environment: %v", err)
}
// parse and type-check the expression
checked, issues := env.Compile(m.expandedExpr)
if issues != nil && issues.Err() != nil {
return fmt.Errorf("compiling CEL program: %s", issues.Err())
}
// request matching is a boolean operation, so we don't really know
// what to do if the expression returns a non-boolean type
if !proto.Equal(checked.ResultType(), decls.Bool) {
return fmt.Errorf("CEL request matcher expects return type of bool, not %s", checked.ResultType())
}
// compile the "program"
m.prg, err = env.Program(checked,
cel.Functions(
&functions.Overload{
Operator: placeholderFuncName,
Binary: m.caddyPlaceholderFunc,
},
),
)
if err != nil {
return fmt.Errorf("compiling CEL program: %s", err)
}
return nil
}
// Match returns true if r matches m.
func (m MatchExpression) Match(r *http.Request) bool {
out, _, _ := m.prg.Eval(map[string]interface{}{
"request": celHTTPRequest{r},
})
if outBool, ok := out.Value().(bool); ok {
return outBool
}
return false
}
// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (m *MatchExpression) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
m.Expr = strings.Join(d.RemainingArgs(), " ")
}
return nil
}
// caddyPlaceholderFunc implements the custom CEL function that accesses the
// Replacer on a request and gets values from it.
func (m MatchExpression) caddyPlaceholderFunc(lhs, rhs ref.Val) ref.Val {
celReq, ok := lhs.(celHTTPRequest)
if !ok {
return types.NewErr(
"invalid request of type '%v' to "+placeholderFuncName+"(request, placeholderVarName)",
lhs.Type())
}
phStr, ok := rhs.(types.String)
if !ok {
return types.NewErr(
"invalid placeholder variable name of type '%v' to "+placeholderFuncName+"(request, placeholderVarName)",
rhs.Type())
}
repl := celReq.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
val, _ := repl.Get(string(phStr))
return m.ta.NativeToValue(val)
}
// httpRequestCELType is the type representation of a native HTTP request.
var httpRequestCELType = types.NewTypeValue("http.Request", traits.ReceiverType)
// cellHTTPRequest wraps an http.Request with
// methods to satisfy the ref.Val interface.
type celHTTPRequest struct{ *http.Request }
func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {
return cr.Request, nil
}
func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val {
panic("not implemented")
}
func (cr celHTTPRequest) Equal(other ref.Val) ref.Val {
if o, ok := other.Value().(celHTTPRequest); ok {
return types.Bool(o.Request == cr.Request)
}
return types.ValOrErr(other, "%v is not comparable type", other)
}
func (celHTTPRequest) Type() ref.Type { return httpRequestCELType }
func (cr celHTTPRequest) Value() interface{} { return cr }
// celTypeAdapter can adapt our custom types to a CEL value.
type celTypeAdapter struct{}
func (celTypeAdapter) NativeToValue(value interface{}) ref.Val {
switch v := value.(type) {
case celHTTPRequest:
return v
case error:
types.NewErr(v.Error())
}
return types.DefaultTypeAdapter.NativeToValue(value)
}
// Variables used for replacing Caddy placeholders in CEL
// expressions with a proper CEL function call; this is
// just for syntactic sugar.
var (
placeholderRegexp = regexp.MustCompile(`{([\w.-]+)}`)
placeholderExpansion = `caddyPlaceholder(request, "${1}")`
)
var httpRequestObjectType = decls.NewObjectType("http.Request")
// The name of the CEL function which accesses Replacer values.
const placeholderFuncName = "caddyPlaceholder"
// Interface guards
var (
_ caddy.Provisioner = (*MatchExpression)(nil)
_ RequestMatcher = (*MatchExpression)(nil)
_ caddyfile.Unmarshaler = (*MatchExpression)(nil)
_ json.Marshaler = (*MatchExpression)(nil)
_ json.Unmarshaler = (*MatchExpression)(nil)
)
| 1 | 15,045 | I know it has no effect but my eyes can't help. Is that line not too long? | caddyserver-caddy | go |
@@ -645,13 +645,6 @@ func (r *DefaultRuleRenderer) filterOutputChain(ipVersion uint8) *Chain {
},
)
- // Jump to chain for blocking service CIDR loops.
- rules = append(rules,
- Rule{
- Action: JumpAction{Target: ChainCIDRBlock},
- },
- )
-
return &Chain{
Name: ChainFilterOutput,
Rules: rules, | 1 | // Copyright (c) 2020 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rules
import (
log "github.com/sirupsen/logrus"
. "github.com/projectcalico/felix/iptables"
"github.com/projectcalico/felix/proto"
)
func (r *DefaultRuleRenderer) StaticFilterTableChains(ipVersion uint8) (chains []*Chain) {
chains = append(chains, r.StaticFilterForwardChains()...)
chains = append(chains, r.StaticFilterInputChains(ipVersion)...)
chains = append(chains, r.StaticFilterOutputChains(ipVersion)...)
return
}
const (
ProtoIPIP = 4
ProtoTCP = 6
ProtoUDP = 17
ProtoICMPv6 = 58
)
func (r *DefaultRuleRenderer) StaticFilterInputChains(ipVersion uint8) []*Chain {
result := []*Chain{}
result = append(result,
r.filterInputChain(ipVersion),
r.filterWorkloadToHostChain(ipVersion),
r.failsafeInChain("filter"),
)
if r.KubeIPVSSupportEnabled {
result = append(result, r.StaticFilterInputForwardCheckChain(ipVersion))
}
return result
}
func (r *DefaultRuleRenderer) acceptAlreadyAccepted() []Rule {
return []Rule{
{
Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: r.filterAllowAction,
},
}
}
// Forward check chain is to check if a packet belongs to a forwarded traffic or not.
// With kube-proxy running in ipvs mode, both local or forwarded traffic goes through INPUT filter chain.
func (r *DefaultRuleRenderer) StaticFilterInputForwardCheckChain(ipVersion uint8) *Chain {
var fwRules []Rule
var portRanges []*proto.PortRange
// Assembly port ranges for kubernetes node ports.
for _, portRange := range r.KubeNodePortRanges {
pr := &proto.PortRange{
First: int32(portRange.MinPort),
Last: int32(portRange.MaxPort),
}
portRanges = append(portRanges, pr)
}
// Get ipsets name for local host ips.
nameForIPSet := func(ipsetID string) string {
if ipVersion == 4 {
return r.IPSetConfigV4.NameForMainIPSet(ipsetID)
} else {
return r.IPSetConfigV6.NameForMainIPSet(ipsetID)
}
}
hostIPSet := nameForIPSet(IPSetIDThisHostIPs)
fwRules = append(fwRules,
// If packet belongs to an existing conntrack connection, it does not belong to a forwarded traffic even destination ip is a
// service ip. This could happen when pod send back response to a local host process accessing a service ip.
Rule{
Match: Match().ConntrackState("RELATED,ESTABLISHED"),
Action: ReturnAction{},
},
)
// If packet is accessing local host within kubernetes NodePort range, it belongs to a forwarded traffic.
for _, portSplit := range SplitPortList(portRanges) {
fwRules = append(fwRules,
Rule{
Match: Match().Protocol("tcp").
DestPortRanges(portSplit).
DestIPSet(hostIPSet),
Action: GotoAction{Target: ChainDispatchSetEndPointMark},
Comment: []string{"To kubernetes NodePort service"},
},
Rule{
Match: Match().Protocol("udp").
DestPortRanges(portSplit).
DestIPSet(hostIPSet),
Action: GotoAction{Target: ChainDispatchSetEndPointMark},
Comment: []string{"To kubernetes NodePort service"},
},
)
}
fwRules = append(fwRules,
// If packet is accessing non local host ip, it belongs to a forwarded traffic.
Rule{
Match: Match().NotDestIPSet(hostIPSet),
Action: JumpAction{Target: ChainDispatchSetEndPointMark},
Comment: []string{"To kubernetes service"},
},
)
return &Chain{
Name: ChainForwardCheck,
Rules: fwRules,
}
}
// With kube-proxy running in ipvs mode, we categorise traffic going through OUTPUT chain into three classes.
// Class 1. forwarded packet originated from a calico workload or host endpoint --> INPUT filter --> OUTPUT filter
// Class 2. forwarded packet originated from a non calico endpoint --> INPUT filter --> OUTPUT filter
// Class 3. local process originated packet --> OUTPUT filter
// This function handles traffic in Class 1 and Class 2.
func (r *DefaultRuleRenderer) StaticFilterOutputForwardEndpointMarkChain() *Chain {
var fwRules []Rule
fwRules = append(fwRules,
// Only packets that we know are really being forwarded reach this chain. However, since
// we're called from the OUTPUT chain, we're forbidden from using the input interface match.
// Instead, we rely on the INPUT chain to mark the packet with a per-endpoint mark value
// and do our dispatch on that mark value. So that we don't touch "Class 2" packets, we
// mark them with mark pattern IptablesMarkNonCaliEndpoint and exclude them here. This
// prevents the default drop at the end of the dispatch chain from dropping non-Calico
// traffic.
Rule{
Match: Match().NotMarkMatchesWithMask(r.IptablesMarkNonCaliEndpoint, r.IptablesMarkEndpoint),
Action: JumpAction{Target: ChainDispatchFromEndPointMark},
},
)
// The packet may be going to a workload interface. Send any such packets to the normal,
// interface-name-based dispatch chains.
for _, prefix := range r.WorkloadIfacePrefixes {
log.WithField("ifacePrefix", prefix).Debug("Adding workload match rules")
ifaceMatch := prefix + "+"
fwRules = append(fwRules,
Rule{
Match: Match().OutInterface(ifaceMatch),
Action: JumpAction{Target: ChainToWorkloadDispatch},
},
)
}
fwRules = append(fwRules,
// The packet may be going to a host endpoint, send it to the host endpoint
// apply-on-forward dispatch chain. That chain returns any packets that are not going to a
// known host endpoint for further processing.
Rule{
Action: JumpAction{Target: ChainDispatchToHostEndpointForward},
},
// Before we ACCEPT the packet, clear the per-interface mark bit. This is required because
// the packet may get encapsulated and pass through iptables again. Since the new encapped
// packet would inherit the mark bits, it would be (incorrectly) treated as a forwarded
// packet.
Rule{
Action: ClearMarkAction{Mark: r.IptablesMarkEndpoint},
},
// If a packet reaches here, one of the following must be true:
//
// - it is going to a workload endpoint and it has passed that endpoint's policy
// - it is going to a host interface with a Calico host endpoint and it has passed that
// endpoint's policy
// - it is going to a host interface with no Calico host endpoint.
//
// In the first two cases, the policy will have set the accept bit in the mark and we "own"
// the packet so it's right for us to ACCEPT it here (unless configured otherwise). In
// the other case, we don't own the packet so we always return it to the OUTPUT chain
// for further processing.
Rule{
Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: r.filterAllowAction,
Comment: []string{"Policy explicitly accepted packet."},
},
)
return &Chain{
Name: ChainForwardEndpointMark,
Rules: fwRules,
}
}
func (r *DefaultRuleRenderer) filterInputChain(ipVersion uint8) *Chain {
var inputRules []Rule
if ipVersion == 4 && r.IPIPEnabled {
// IPIP is enabled, filter incoming IPIP packets to ensure they come from a
// recognised host and are going to a local address on the host. We use the protocol
// number rather than its name because the name is not guaranteed to be known by the kernel.
inputRules = append(inputRules,
Rule{
Match: Match().ProtocolNum(ProtoIPIP).
SourceIPSet(r.IPSetConfigV4.NameForMainIPSet(IPSetIDAllHostNets)).
DestAddrType(AddrTypeLocal),
Action: r.filterAllowAction,
Comment: []string{"Allow IPIP packets from Calico hosts"},
},
Rule{
Match: Match().ProtocolNum(ProtoIPIP),
Action: DropAction{},
Comment: []string{"Drop IPIP packets from non-Calico hosts"},
},
)
}
if ipVersion == 4 && r.VXLANEnabled {
// VXLAN is enabled, filter incoming VXLAN packets that match our VXLAN port to ensure they
// come from a recognised host and are going to a local address on the host.
inputRules = append(inputRules,
Rule{
Match: Match().ProtocolNum(ProtoUDP).
DestPorts(uint16(r.Config.VXLANPort)).
SourceIPSet(r.IPSetConfigV4.NameForMainIPSet(IPSetIDAllVXLANSourceNets)).
DestAddrType(AddrTypeLocal),
Action: r.filterAllowAction,
Comment: []string{"Allow VXLAN packets from whitelisted hosts"},
},
Rule{
Match: Match().ProtocolNum(ProtoUDP).
DestPorts(uint16(r.Config.VXLANPort)).
DestAddrType(AddrTypeLocal),
Action: DropAction{},
Comment: []string{"Drop VXLAN packets from non-whitelisted hosts"},
},
)
}
// Note that we do not need to do this filtering for wireguard because it already has the peering and allowed IPs
// baked into the crypto routing table.
if r.KubeIPVSSupportEnabled {
// Check if packet belongs to forwarded traffic. (e.g. part of an ipvs connection).
// If it is, set endpoint mark and skip "to local host" rules below.
inputRules = append(inputRules,
Rule{
Action: ClearMarkAction{Mark: r.IptablesMarkEndpoint},
},
Rule{
Action: JumpAction{Target: ChainForwardCheck},
},
Rule{
Match: Match().MarkNotClear(r.IptablesMarkEndpoint),
Action: ReturnAction{},
},
)
}
// Apply our policy to packets coming from workload endpoints.
for _, prefix := range r.WorkloadIfacePrefixes {
log.WithField("ifacePrefix", prefix).Debug("Adding workload match rules")
ifaceMatch := prefix + "+"
inputRules = append(inputRules, Rule{
Match: Match().InInterface(ifaceMatch),
Action: GotoAction{Target: ChainWorkloadToHost},
})
}
// Now we only have ingress host endpoint processing to do. The ingress host endpoint may
// have already accepted this packet in the raw or mangle table. In that case, accept the
// packet immediately here too.
inputRules = append(inputRules, r.acceptAlreadyAccepted()...)
// Apply host endpoint policy.
inputRules = append(inputRules,
Rule{
Action: ClearMarkAction{Mark: r.allCalicoMarkBits()},
},
Rule{
Action: JumpAction{Target: ChainDispatchFromHostEndpoint},
},
Rule{
Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: r.filterAllowAction,
Comment: []string{"Host endpoint policy accepted packet."},
},
)
return &Chain{
Name: ChainFilterInput,
Rules: inputRules,
}
}
func (r *DefaultRuleRenderer) filterWorkloadToHostChain(ipVersion uint8) *Chain {
var rules []Rule
// For IPv6, we need to white-list certain ICMP traffic from workloads in order to to act
// as a router. Note: we do this before the policy chains, so we're bypassing the egress
// rules for this traffic. While that might be unexpected, it makes sure that the user
// doesn't cut off their own connectivity in subtle ways that they shouldn't have to worry
// about.
//
// - 130: multicast listener query.
// - 131: multicast listener report.
// - 132: multicast listener done.
// - 133: router solicitation, which an endpoint uses to request
// configuration information rather than waiting for an
// unsolicited router advertisement.
// - 135: neighbor solicitation.
// - 136: neighbor advertisement.
if ipVersion == 6 {
for _, icmpType := range []uint8{130, 131, 132, 133, 135, 136} {
rules = append(rules, Rule{
Match: Match().
ProtocolNum(ProtoICMPv6).
ICMPV6Type(icmpType),
Action: r.filterAllowAction,
})
}
}
if r.OpenStackSpecialCasesEnabled {
log.Info("Adding OpenStack special-case rules.")
if ipVersion == 4 && r.OpenStackMetadataIP != nil {
// For OpenStack compatibility, we support a special-case to allow incoming traffic
// to the OpenStack metadata IP/port.
// TODO(smc) Long-term, it'd be nice if the OpenStack plugin programmed a policy to
// do this instead.
log.WithField("ip", r.OpenStackMetadataIP).Info(
"OpenStack metadata IP specified, installing whitelist rule.")
rules = append(rules, Rule{
Match: Match().
Protocol("tcp").
DestNet(r.OpenStackMetadataIP.String()).
DestPorts(r.OpenStackMetadataPort),
Action: r.filterAllowAction,
})
}
// Again, for OpenStack compatibility, white-list certain protocols.
// TODO(smc) Long-term, it'd be nice if the OpenStack plugin programmed a policy to
// do this instead.
dhcpSrcPort := uint16(68)
dhcpDestPort := uint16(67)
if ipVersion == 6 {
dhcpSrcPort = uint16(546)
dhcpDestPort = uint16(547)
}
dnsDestPort := uint16(53)
rules = append(rules,
Rule{
Match: Match().
Protocol("udp").
SourcePorts(dhcpSrcPort).
DestPorts(dhcpDestPort),
Action: r.filterAllowAction,
},
Rule{
Match: Match().
Protocol("udp").
DestPorts(dnsDestPort),
Action: r.filterAllowAction,
},
)
}
// Now send traffic to the policy chains to apply the egress policy.
rules = append(rules, Rule{
Action: JumpAction{Target: ChainFromWorkloadDispatch},
})
// If the dispatch chain accepts the packet, it returns to us here. Apply the configured
// action. Note: we may have done work above to allow the packet and then end up dropping
// it here. We can't optimize that away because there may be other rules (such as log
// rules in the policy).
for _, action := range r.inputAcceptActions {
rules = append(rules, Rule{
Action: action,
Comment: []string{"Configured DefaultEndpointToHostAction"},
})
}
return &Chain{
Name: ChainWorkloadToHost,
Rules: rules,
}
}
func (r *DefaultRuleRenderer) failsafeInChain(table string) *Chain {
rules := []Rule{}
for _, protoPort := range r.Config.FailsafeInboundHostPorts {
rules = append(rules, Rule{
Match: Match().
Protocol(protoPort.Protocol).
DestPorts(protoPort.Port),
Action: AcceptAction{},
})
}
if table == "raw" {
// We're in the raw table, before conntrack, so we need to whitelist response traffic.
// Otherwise, it could fall through to some doNotTrack policy and half of the connection
// would get untracked. If we ACCEPT here then the traffic falls through to the filter
// table, where it'll only be accepted if there's a conntrack entry.
for _, protoPort := range r.Config.FailsafeOutboundHostPorts {
rules = append(rules, Rule{
Match: Match().
Protocol(protoPort.Protocol).
SourcePorts(protoPort.Port),
Action: AcceptAction{},
})
}
}
return &Chain{
Name: ChainFailsafeIn,
Rules: rules,
}
}
func (r *DefaultRuleRenderer) failsafeOutChain(table string) *Chain {
rules := []Rule{}
for _, protoPort := range r.Config.FailsafeOutboundHostPorts {
rules = append(rules, Rule{
Match: Match().
Protocol(protoPort.Protocol).
DestPorts(protoPort.Port),
Action: AcceptAction{},
})
}
if table == "raw" {
// We're in the raw table, before conntrack, so we need to whitelist response traffic.
// Otherwise, it could fall through to some doNotTrack policy and half of the connection
// would get untracked. If we ACCEPT here then the traffic falls through to the filter
// table, where it'll only be accepted if there's a conntrack entry.
for _, protoPort := range r.Config.FailsafeInboundHostPorts {
rules = append(rules, Rule{
Match: Match().
Protocol(protoPort.Protocol).
SourcePorts(protoPort.Port),
Action: AcceptAction{},
})
}
}
return &Chain{
Name: ChainFailsafeOut,
Rules: rules,
}
}
func (r *DefaultRuleRenderer) StaticFilterForwardChains() []*Chain {
rules := []Rule{}
// Rules for filter forward chains dispatches the packet to our dispatch chains if it is going
// to/from an interface that we're responsible for. Note: the dispatch chains represent "allow"
// by returning to this chain for further processing; this is required to handle traffic that
// is going between endpoints on the same host. In that case we need to apply the egress policy
// for one endpoint and the ingress policy for the other.
//
// Packets will be accepted if they passed through both workload and host endpoint policy
// and were returned.
// Jump to from-host-endpoint dispatch chains.
rules = append(rules,
Rule{
// we're clearing all our mark bits to minimise non-determinism caused by rules in other chains.
// We exclude the accept bit because we use that to communicate from the raw/pre-dnat chains.
Action: ClearMarkAction{Mark: r.allCalicoMarkBits() &^ r.IptablesMarkAccept},
},
Rule{
// Apply forward policy for the incoming Host endpoint if accept bit is clear which means the packet
// was not accepted in a previous raw or pre-DNAT chain.
Match: Match().MarkClear(r.IptablesMarkAccept),
Action: JumpAction{Target: ChainDispatchFromHostEndPointForward},
},
)
// Jump to workload dispatch chains.
for _, prefix := range r.WorkloadIfacePrefixes {
log.WithField("ifacePrefix", prefix).Debug("Adding workload match rules")
ifaceMatch := prefix + "+"
rules = append(rules,
Rule{
Match: Match().InInterface(ifaceMatch),
Action: JumpAction{Target: ChainFromWorkloadDispatch},
},
Rule{
Match: Match().OutInterface(ifaceMatch),
Action: JumpAction{Target: ChainToWorkloadDispatch},
},
)
}
// Jump to to-host-endpoint dispatch chains.
rules = append(rules,
Rule{
// Apply forward policy for the outgoing host endpoint.
Action: JumpAction{Target: ChainDispatchToHostEndpointForward},
},
)
// Jump to chain for blocking service CIDR loops.
rules = append(rules,
Rule{
Action: JumpAction{Target: ChainCIDRBlock},
},
)
return []*Chain{{
Name: ChainFilterForward,
Rules: rules,
}}
}
// StaticFilterForwardAppendRules returns rules which should be statically appended to the end of the filter
// table's forward chain.
func (r *DefaultRuleRenderer) StaticFilterForwardAppendRules() []Rule {
return []Rule{{
Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: r.filterAllowAction,
Comment: []string{"Policy explicitly accepted packet."},
}}
}
func (r *DefaultRuleRenderer) StaticFilterOutputChains(ipVersion uint8) []*Chain {
result := []*Chain{}
result = append(result,
r.filterOutputChain(ipVersion),
r.failsafeOutChain("filter"),
)
if r.KubeIPVSSupportEnabled {
result = append(result, r.StaticFilterOutputForwardEndpointMarkChain())
}
return result
}
func (r *DefaultRuleRenderer) filterOutputChain(ipVersion uint8) *Chain {
var rules []Rule
// Accept immediately if we've already accepted this packet in the raw or mangle table.
rules = append(rules, r.acceptAlreadyAccepted()...)
if r.KubeIPVSSupportEnabled {
// Special case: packets that are forwarded through IPVS hit the INPUT and OUTPUT chains
// instead of FORWARD. In the INPUT chain, we mark such packets with a per-interface ID.
// Divert those packets to a chain that handles them as we would if they had hit the FORWARD
// chain.
//
// We use a goto so that a RETURN from that chain will continue execution in the OUTPUT
// chain.
rules = append(rules,
Rule{
Match: Match().MarkNotClear(r.IptablesMarkEndpoint),
Action: GotoAction{Target: ChainForwardEndpointMark},
},
)
}
// We don't currently police host -> endpoint according to the endpoint's ingress policy.
// That decision is based on pragmatism; it's generally very useful to be able to contact
// any local workload from the host and policing the traffic doesn't really protect
// against host compromise. If a host is compromised, then the rules could be removed!
// However, we do apply policy to workload ingress traffic if it belongs to an IPVS connection.
for _, prefix := range r.WorkloadIfacePrefixes {
// If the packet is going to a workload endpoint, apply workload ingress policy if traffic
// belongs to an IPVS connection and return at the end.
log.WithField("ifacePrefix", prefix).Debug("Adding workload match rules")
ifaceMatch := prefix + "+"
rules = append(rules,
Rule{
// if packet goes to a workload endpoint. set return action properly.
Match: Match().OutInterface(ifaceMatch),
Action: ReturnAction{},
},
)
}
// If we reach here, the packet is not going to a workload so it must be going to a
// host endpoint. It also has no endpoint mark so it must be going from a process.
if ipVersion == 4 && r.IPIPEnabled {
// When IPIP is enabled, auto-allow IPIP traffic to other Calico nodes. Without this,
// it's too easy to make a host policy that blocks IPIP traffic, resulting in very confusing
// connectivity problems.
rules = append(rules,
Rule{
Match: Match().ProtocolNum(ProtoIPIP).
DestIPSet(r.IPSetConfigV4.NameForMainIPSet(IPSetIDAllHostNets)).
SrcAddrType(AddrTypeLocal, false),
Action: r.filterAllowAction,
Comment: []string{"Allow IPIP packets to other Calico hosts"},
},
)
}
if ipVersion == 4 && r.VXLANEnabled {
// When VXLAN is enabled, auto-allow VXLAN traffic to other Calico nodes. Without this,
// it's too easy to make a host policy that blocks VXLAN traffic, resulting in very confusing
// connectivity problems.
rules = append(rules,
Rule{
Match: Match().ProtocolNum(ProtoUDP).
DestPorts(uint16(r.Config.VXLANPort)).
SrcAddrType(AddrTypeLocal, false).
DestIPSet(r.IPSetConfigV4.NameForMainIPSet(IPSetIDAllVXLANSourceNets)),
Action: r.filterAllowAction,
Comment: []string{"Allow VXLAN packets to other whitelisted hosts"},
},
)
}
// TODO(rlb): For wireguard, we add the destination port to the failsafes. We may want to revisit this so that we
// only include nodes that support wireguard. This will tie in with whether or not we want to include external
// wireguard destinations.
// Apply host endpoint policy.
rules = append(rules,
Rule{
Action: ClearMarkAction{Mark: r.allCalicoMarkBits()},
},
Rule{
Action: JumpAction{Target: ChainDispatchToHostEndpoint},
},
Rule{
Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: r.filterAllowAction,
Comment: []string{"Host endpoint policy accepted packet."},
},
)
// Jump to chain for blocking service CIDR loops.
rules = append(rules,
Rule{
Action: JumpAction{Target: ChainCIDRBlock},
},
)
return &Chain{
Name: ChainFilterOutput,
Rules: rules,
}
}
func (r *DefaultRuleRenderer) StaticNATTableChains(ipVersion uint8) (chains []*Chain) {
chains = append(chains, r.StaticNATPreroutingChains(ipVersion)...)
chains = append(chains, r.StaticNATPostroutingChains(ipVersion)...)
chains = append(chains, r.StaticNATOutputChains(ipVersion)...)
return
}
func (r *DefaultRuleRenderer) StaticNATPreroutingChains(ipVersion uint8) []*Chain {
rules := []Rule{
{
Action: JumpAction{Target: ChainFIPDnat},
},
}
if ipVersion == 4 && r.OpenStackSpecialCasesEnabled && r.OpenStackMetadataIP != nil {
rules = append(rules, Rule{
Match: Match().
Protocol("tcp").
DestPorts(80).
DestNet("169.254.169.254/32"),
Action: DNATAction{
DestAddr: r.OpenStackMetadataIP.String(),
DestPort: r.OpenStackMetadataPort,
},
})
}
chains := []*Chain{{
Name: ChainNATPrerouting,
Rules: rules,
}}
return chains
}
func (r *DefaultRuleRenderer) StaticNATPostroutingChains(ipVersion uint8) []*Chain {
rules := []Rule{
{
Action: JumpAction{Target: ChainFIPSnat},
},
{
Action: JumpAction{Target: ChainNATOutgoing},
},
}
var tunnelIfaces []string
if ipVersion == 4 && r.IPIPEnabled && len(r.IPIPTunnelAddress) > 0 {
tunnelIfaces = append(tunnelIfaces, "tunl0")
}
if ipVersion == 4 && r.VXLANEnabled && len(r.VXLANTunnelAddress) > 0 {
tunnelIfaces = append(tunnelIfaces, "vxlan.calico")
}
if ipVersion == 4 && r.WireguardEnabled && len(r.WireguardInterfaceName) > 0 {
// Wireguard is assigned an IP dynamically and without restarting Felix. Just add the interface if we have
// wireguard enabled.
tunnelIfaces = append(tunnelIfaces, r.WireguardInterfaceName)
}
for _, tunnel := range tunnelIfaces {
// Add a rule to catch packets that are being sent down a tunnel from an
// incorrect local IP address of the host and NAT them to use the tunnel IP as its
// source. This happens if:
//
// - the user explicitly binds their socket to the wrong source IP accidentally
// - the user sends traffic to, for example, a Kubernetes service IP, which is
// implemented via NAT instead of routing, leading the kernel to choose the
// wrong source IP.
//
// We NAT the source of the packet to use the tunnel IP. We assume that
// non-local IPs have been correctly routed. Since Calico-assigned IPs are
// non-local (because they're down a veth), they won't get caught by the rule.
// Other remote sources will only reach the tunnel if they're being NATted
// already (for example, a Kubernetes "NodePort"). The kernel will then
// choose the correct source on its own.
rules = append(rules, Rule{
Match: Match().
// Only match packets going out the tunnel.
OutInterface(tunnel).
// Match packets that don't have the correct source address. This
// matches local addresses (i.e. ones assigned to this host)
// limiting the match to the output interface (which we matched
// above as the tunnel). Avoiding embedding the IP address lets
// us use a static rule, which is easier to manage.
NotSrcAddrType(AddrTypeLocal, true).
// Only match if the IP is also some local IP on the box. This
// prevents us from matching packets from workloads, which are
// remote as far as the routing table is concerned.
SrcAddrType(AddrTypeLocal, false),
Action: MasqAction{},
})
}
return []*Chain{{
Name: ChainNATPostrouting,
Rules: rules,
}}
}
func (r *DefaultRuleRenderer) StaticNATOutputChains(ipVersion uint8) []*Chain {
rules := []Rule{
{
Action: JumpAction{Target: ChainFIPDnat},
},
}
return []*Chain{{
Name: ChainNATOutput,
Rules: rules,
}}
}
func (r *DefaultRuleRenderer) StaticMangleTableChains(ipVersion uint8) []*Chain {
var chains []*Chain
chains = append(chains,
r.failsafeInChain("mangle"),
r.StaticManglePreroutingChain(ipVersion),
)
return chains
}
func (r *DefaultRuleRenderer) StaticManglePreroutingChain(ipVersion uint8) *Chain {
rules := []Rule{}
// ACCEPT or RETURN immediately if packet matches an existing connection. Note that we also
// have a rule like this at the start of each pre-endpoint chain; the functional difference
// with placing this rule here is that it will also apply to packets that may be unrelated
// to Calico (i.e. not to or from Calico workloads, and not via Calico host endpoints). We
// think this is appropriate in the mangle table here - whereas we don't have a rule like
// this in the filter table - because the mangle table is generally not used (except by us)
// for dropping packets, so it is very unlikely that we would be circumventing someone
// else's rule to drop a packet. (And in that case, the user can configure
// IptablesMangleAllowAction to be RETURN.)
rules = append(rules,
Rule{
Match: Match().ConntrackState("RELATED,ESTABLISHED"),
Action: r.mangleAllowAction,
},
)
// Or if we've already accepted this packet in the raw table.
rules = append(rules,
Rule{
Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: r.mangleAllowAction,
},
)
// Now (=> not from a workload) dispatch to host endpoint chain for the incoming interface.
rules = append(rules,
Rule{
Action: JumpAction{Target: ChainDispatchFromHostEndpoint},
},
// Following that... If the packet was explicitly allowed by a pre-DNAT policy, it
// will have MarkAccept set. If the packet was denied, it will have been dropped
// already. If the incoming interface isn't one that we're policing, or the packet
// isn't governed by any pre-DNAT policy on that interface, it will fall through to
// here without any Calico bits set.
// In the MarkAccept case, we ACCEPT or RETURN according to
// IptablesMangleAllowAction.
Rule{
Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: r.mangleAllowAction,
Comment: []string{"Host endpoint policy accepted packet."},
},
)
return &Chain{
Name: ChainManglePrerouting,
Rules: rules,
}
}
func (r *DefaultRuleRenderer) StaticRawTableChains(ipVersion uint8) []*Chain {
return []*Chain{
r.failsafeInChain("raw"),
r.failsafeOutChain("raw"),
r.StaticRawPreroutingChain(ipVersion),
r.StaticRawOutputChain(),
}
}
func (r *DefaultRuleRenderer) StaticRawPreroutingChain(ipVersion uint8) *Chain {
rules := []Rule{}
// For safety, clear all our mark bits before we start. (We could be in append mode and
// another process' rules could have left the mark bit set.)
rules = append(rules,
Rule{Action: ClearMarkAction{Mark: r.allCalicoMarkBits()}},
)
// Set a mark on the packet if it's from a workload interface.
markFromWorkload := r.IptablesMarkScratch0
for _, ifacePrefix := range r.WorkloadIfacePrefixes {
rules = append(rules, Rule{
Match: Match().InInterface(ifacePrefix + "+"),
Action: SetMarkAction{Mark: markFromWorkload},
})
}
// Apply strict RPF check to packets from workload interfaces. This prevents
// workloads from spoofing their IPs. Note: non-privileged containers can't
// usually spoof but privileged containers and VMs can.
//
rules = append(rules,
RPFilter(ipVersion, markFromWorkload, markFromWorkload, r.OpenStackSpecialCasesEnabled, false)...)
rules = append(rules,
// Send non-workload traffic to the untracked policy chains.
Rule{Match: Match().MarkClear(markFromWorkload),
Action: JumpAction{Target: ChainDispatchFromHostEndpoint}},
// Then, if the packet was marked as allowed, accept it. Packets also return here
// without the mark bit set if the interface wasn't one that we're policing. We
// let those packets fall through to the user's policy.
Rule{Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: AcceptAction{}},
)
return &Chain{
Name: ChainRawPrerouting,
Rules: rules,
}
}
// RPFilter returns rules that implement RPF
func RPFilter(ipVersion uint8, mark, mask uint32, openStackSpecialCasesEnabled, acceptLocal bool) []Rule {
rules := make([]Rule, 0, 2)
// For OpenStack, allow DHCP v4 packets with source 0.0.0.0. These must be allowed before
// checking against the iptables rp_filter module, because the rp_filter module in some
// kernel versions does not allow for DHCP with source 0.0.0.0 (whereas the rp_filter sysctl
// setting _did_).
//
// Initial DHCP requests (DHCPDISCOVER) have source 0.0.0.0, and so will be allowed through
// by the specific rule just following. Later DHCP requests (DHCPREQUEST) may have source
// 0.0.0.0, or the client's actual IP (as discovered through the DHCP process). The 0.0.0.0
// case will again be allowed by the following specific rule; the actual IP case should be
// allowed by the general RPF check. (Ref: https://www.ietf.org/rfc/rfc2131.txt page 37)
//
// Note: in DHCPv6, the initial request is sent with a link-local IPv6 address, which should
// pass RPF, hence no special case is needed for DHCPv6.
//
// Here we are only focussing on anti-spoofing, and note that we ACCEPT a correct packet for
// the current raw table, but don't mark it (with our Accept bit) as automatically accepted
// for later tables. Hence - for the policy level - we still have an OpenStack DHCP special
// case again in filterWorkloadToHostChain.
if openStackSpecialCasesEnabled && ipVersion == 4 {
log.Info("Add OpenStack special-case rule for DHCP with source 0.0.0.0")
rules = append(rules,
Rule{
Match: Match().
Protocol("udp").
SourceNet("0.0.0.0").
SourcePorts(68).
DestPorts(67),
Action: AcceptAction{},
},
)
}
rules = append(rules, Rule{
Match: Match().MarkMatchesWithMask(mark, mask).RPFCheckFailed(acceptLocal),
Action: DropAction{},
})
return rules
}
func (r *DefaultRuleRenderer) allCalicoMarkBits() uint32 {
return r.IptablesMarkAccept |
r.IptablesMarkPass |
r.IptablesMarkScratch0 |
r.IptablesMarkScratch1
}
func (r *DefaultRuleRenderer) StaticRawOutputChain() *Chain {
return &Chain{
Name: ChainRawOutput,
Rules: []Rule{
// For safety, clear all our mark bits before we start. (We could be in
// append mode and another process' rules could have left the mark bit set.)
{Action: ClearMarkAction{Mark: r.allCalicoMarkBits()}},
// Then, jump to the untracked policy chains.
{Action: JumpAction{Target: ChainDispatchToHostEndpoint}},
// Then, if the packet was marked as allowed, accept it. Packets also
// return here without the mark bit set if the interface wasn't one that
// we're policing.
{Match: Match().MarkSingleBitSet(r.IptablesMarkAccept),
Action: AcceptAction{}},
},
}
}
| 1 | 18,427 | Does that mean we disable service loop prevention for packet generated by local host? | projectcalico-felix | go |
@@ -107,6 +107,7 @@ module Beaker
when host['platform'] =~ /cumulus/
check_and_install_packages_if_needed(host, CUMULUS_PACKAGES)
when (host['platform'] =~ /windows/ and host.is_cygwin?)
+ raise RuntimeError, "cygwin is not installed on #{host}" if !host.cygwin_installed?
check_and_install_packages_if_needed(host, WINDOWS_PACKAGES)
when (host['platform'] =~ /windows/ and not host.is_cygwin?)
check_and_install_packages_if_needed(host, PSWINDOWS_PACKAGES) | 1 | require 'pathname'
[ 'command', "dsl" ].each do |lib|
require "beaker/#{lib}"
end
module Beaker
#Provides convienience methods for commonly run actions on hosts
module HostPrebuiltSteps
include Beaker::DSL::Patterns
NTPSERVER = 'pool.ntp.org'
SLEEPWAIT = 5
TRIES = 5
UNIX_PACKAGES = ['curl', 'ntpdate']
FREEBSD_PACKAGES = ['curl', 'perl5|perl']
OPENBSD_PACKAGES = ['curl']
ARCHLINUX_PACKAGES = ['curl', 'ntp']
WINDOWS_PACKAGES = ['curl']
PSWINDOWS_PACKAGES = []
SLES10_PACKAGES = ['curl']
SLES_PACKAGES = ['curl', 'ntp']
DEBIAN_PACKAGES = ['curl', 'ntpdate', 'lsb-release']
CUMULUS_PACKAGES = ['curl', 'ntpdate']
SOLARIS10_PACKAGES = ['CSWcurl', 'CSWntp']
SOLARIS11_PACKAGES = ['curl', 'ntp']
ETC_HOSTS_PATH = "/etc/hosts"
ETC_HOSTS_PATH_SOLARIS = "/etc/inet/hosts"
ROOT_KEYS_SCRIPT = "https://raw.githubusercontent.com/puppetlabs/puppetlabs-sshkeys/master/templates/scripts/manage_root_authorized_keys"
ROOT_KEYS_SYNC_CMD = "curl -k -o - -L #{ROOT_KEYS_SCRIPT} | %s"
ROOT_KEYS_SYNC_CMD_AIX = "curl --tlsv1 -o - -L #{ROOT_KEYS_SCRIPT} | %s"
APT_CFG = %q{ Acquire::http::Proxy "http://proxy.puppetlabs.net:3128/"; }
IPS_PKG_REPO="http://solaris-11-internal-repo.delivery.puppetlabs.net"
#Run timesync on the provided hosts
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def timesync host, opts
logger = opts[:logger]
ntp_server = opts[:ntp_server] ? opts[:ntp_server] : NTPSERVER
block_on host do |host|
logger.notify "Update system time sync for '#{host.name}'"
if host['platform'].include? 'windows'
# The exit code of 5 is for Windows 2008 systems where the w32tm /register command
# is not actually necessary.
host.exec(Command.new("w32tm /register"), :acceptable_exit_codes => [0,5])
host.exec(Command.new("net start w32time"), :acceptable_exit_codes => [0,2])
host.exec(Command.new("w32tm /config /manualpeerlist:#{ntp_server} /syncfromflags:manual /update"))
host.exec(Command.new("w32tm /resync"))
logger.notify "NTP date succeeded on #{host}"
else
case
when host['platform'] =~ /sles-/
ntp_command = "sntp #{ntp_server}"
when host['platform'] =~ /cisco_nexus/
ntp_server = host.exec(Command.new("getent hosts #{NTPSERVER} | head -n1 |cut -d \" \" -f1"), :acceptable_exit_codes => [0]).stdout
ntp_command = "sudo -E sh -c 'export DCOS_CONTEXT=2;/isan/bin/ntpdate -u -t 20 #{ntp_server}'"
else
ntp_command = "ntpdate -u -t 20 #{ntp_server}"
end
success=false
try = 0
until try >= TRIES do
try += 1
if host.exec(Command.new(ntp_command), :accept_all_exit_codes => true).exit_code == 0
success=true
break
end
sleep SLEEPWAIT
end
if success
logger.notify "NTP date succeeded on #{host} after #{try} tries"
else
raise "NTP date was not successful after #{try} tries"
end
end
end
nil
rescue => e
report_and_raise(logger, e, "timesync (--ntp)")
end
# Validate that hosts are prepared to be used as SUTs, if packages are missing attempt to
# install them.
#
# Verifies the presence of #{HostPrebuiltSteps::UNIX_PACKAGES} on unix platform hosts,
# {HostPrebuiltSteps::SLES_PACKAGES} on SUSE platform hosts,
# {HostPrebuiltSteps::DEBIAN_PACKAGES} on debian platform hosts,
# {HostPrebuiltSteps::CUMULUS_PACKAGES} on cumulus platform hosts,
# {HostPrebuiltSteps::WINDOWS_PACKAGES} on cygwin-installed windows platform hosts,
# and {HostPrebuiltSteps::PSWINDOWS_PACKAGES} on non-cygwin windows platform hosts.
#
# @param [Host, Array<Host>, String, Symbol] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def validate_host host, opts
logger = opts[:logger]
block_on host do |host|
case
when host['platform'] =~ /sles-10/
check_and_install_packages_if_needed(host, SLES10_PACKAGES)
when host['platform'] =~ /sles-/
check_and_install_packages_if_needed(host, SLES_PACKAGES)
when host['platform'] =~ /debian/
check_and_install_packages_if_needed(host, DEBIAN_PACKAGES)
when host['platform'] =~ /cumulus/
check_and_install_packages_if_needed(host, CUMULUS_PACKAGES)
when (host['platform'] =~ /windows/ and host.is_cygwin?)
check_and_install_packages_if_needed(host, WINDOWS_PACKAGES)
when (host['platform'] =~ /windows/ and not host.is_cygwin?)
check_and_install_packages_if_needed(host, PSWINDOWS_PACKAGES)
when host['platform'] =~ /freebsd/
check_and_install_packages_if_needed(host, FREEBSD_PACKAGES)
when host['platform'] =~ /openbsd/
check_and_install_packages_if_needed(host, OPENBSD_PACKAGES)
when host['platform'] =~ /solaris-10/
check_and_install_packages_if_needed(host, SOLARIS10_PACKAGES)
when host['platform'] =~ /solaris-1[1-9]/
check_and_install_packages_if_needed(host, SOLARIS11_PACKAGES)
when host['platform'] =~ /archlinux/
check_and_install_packages_if_needed(host, ARCHLINUX_PACKAGES)
when host['platform'] !~ /debian|aix|solaris|windows|sles-|osx-|cumulus|f5-|netscaler|cisco_/
check_and_install_packages_if_needed(host, UNIX_PACKAGES)
end
end
rescue => e
report_and_raise(logger, e, "validate")
end
# Installs the given packages if they aren't already on a host
#
# @param [Host] host Host to act on
# @param [Array<String>] package_list List of package names to install
def check_and_install_packages_if_needed host, package_list
package_list.each do |string|
alternatives = string.split('|')
next if alternatives.any? { |pkg| host.check_for_package pkg }
install_one_of_packages host, alternatives
end
end
# Installs one of alternative packages (first available)
#
# @param [Host] host Host to act on
# @param [Array<String>] packages List of package names (alternatives).
def install_one_of_packages host, packages
error = nil
packages.each do |pkg|
begin
return host.install_package pkg
rescue Beaker::Host::CommandFailure => e
error = e
end
end
raise error
end
#Install a set of authorized keys using {HostPrebuiltSteps::ROOT_KEYS_SCRIPT}. This is a
#convenience method to allow for easy login to hosts after they have been provisioned with
#Beaker.
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def sync_root_keys host, opts
# JJM This step runs on every system under test right now. We're anticipating
# issues on Windows and maybe Solaris. We will likely need to filter this step
# but we're deliberately taking the approach of "assume it will work, fix it
# when reality dictates otherwise"
logger = opts[:logger]
block_on host do |host|
logger.notify "Sync root authorized_keys from github on #{host.name}"
# Allow all exit code, as this operation is unlikely to cause problems if it fails.
if host['platform'] =~ /solaris|eos/
host.exec(Command.new(ROOT_KEYS_SYNC_CMD % "bash"), :accept_all_exit_codes => true)
elsif host['platform'] =~ /aix/
host.exec(Command.new(ROOT_KEYS_SYNC_CMD_AIX % "env PATH=/usr/gnu/bin:$PATH bash"), :accept_all_exit_codes => true)
else
host.exec(Command.new(ROOT_KEYS_SYNC_CMD % "env PATH=\"/usr/gnu/bin:$PATH\" bash"), :accept_all_exit_codes => true)
end
end
rescue => e
report_and_raise(logger, e, "sync_root_keys")
end
# Run 'apt-get update' on the provided host or hosts.
# If the platform of the provided host is not ubuntu, debian or cumulus: do nothing.
#
# @param [Host, Array<Host>] hosts One or more hosts to act upon
def apt_get_update hosts
block_on hosts do |host|
if host[:platform] =~ /ubuntu|debian|cumulus/
host.exec(Command.new("apt-get update"))
end
end
end
#Create a file on host or hosts at the provided file path with the provided file contents.
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [String] file_path The path at which the new file will be created on the host or hosts.
# @param [String] file_content The contents of the file to be created on the host or hosts.
def copy_file_to_remote(host, file_path, file_content)
block_on host do |host|
Tempfile.open 'beaker' do |tempfile|
File.open(tempfile.path, 'w') {|file| file.puts file_content }
host.do_scp_to(tempfile.path, file_path, @options)
end
end
end
# On ubuntu, debian, or cumulus host or hosts: alter apt configuration to use
# the internal Puppet Labs proxy {HostPrebuiltSteps::APT_CFG} proxy.
# On solaris-11 host or hosts: alter pkg to point to
# the internal Puppet Labs proxy {HostPrebuiltSteps::IPS_PKG_REPO}.
#
# Do nothing for other platform host or hosts.
#
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def proxy_config( host, opts )
logger = opts[:logger]
block_on host do |host|
case
when host['platform'] =~ /ubuntu|debian|cumulus/
host.exec(Command.new("if test -f /etc/apt/apt.conf; then mv /etc/apt/apt.conf /etc/apt/apt.conf.bk; fi"))
copy_file_to_remote(host, '/etc/apt/apt.conf', APT_CFG)
apt_get_update(host)
when host['platform'] =~ /solaris-11/
host.exec(Command.new("/usr/bin/pkg unset-publisher solaris || :"))
host.exec(Command.new("/usr/bin/pkg set-publisher -g %s solaris" % IPS_PKG_REPO))
else
logger.debug "#{host}: repo proxy configuration not modified"
end
end
rescue => e
report_and_raise(logger, e, "proxy_config")
end
#Install EPEL on host or hosts with platform = /el-(5|6|7)/. Do nothing on host or hosts of other platforms.
# @param [Host, Array<Host>] host One or more hosts to act upon. Will use individual host epel_url, epel_arch
# and epel_pkg before using defaults provided in opts.
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Boolean] :debug If true, print verbose rpm information when installing EPEL
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
# @option opts [String] :epel_url Link to download from
def add_el_extras( host, opts )
#add_el_extras
#only supports el-* platforms
logger = opts[:logger]
debug_opt = opts[:debug] ? 'vh' : ''
block_on host do |host|
case
when el_based?(host) && ['5','6','7'].include?(host['platform'].version)
result = host.exec(Command.new('rpm -qa | grep epel-release'), :acceptable_exit_codes => [0,1])
if result.exit_code == 1
url_base = opts[:epel_url]
url_base = opts[:epel_url_archive] if host['platform'].version == '5'
host.exec(Command.new("rpm -i#{debug_opt} #{url_base}/epel-release-latest-#{host['platform'].version}.noarch.rpm"))
#update /etc/yum.repos.d/epel.repo for new baseurl
host.exec(Command.new("sed -i -e 's;#baseurl.*$;baseurl=#{Regexp.escape("#{url_base}/#{host['platform'].version}")}/\$basearch;' /etc/yum.repos.d/epel.repo"))
#remove mirrorlist
host.exec(Command.new("sed -i -e '/mirrorlist/d' /etc/yum.repos.d/epel.repo"))
host.exec(Command.new('yum clean all && yum makecache'))
end
else
logger.debug "#{host}: package repo configuration not modified"
end
end
rescue => e
report_and_raise(logger, e, "add_repos")
end
#Determine the domain name of the provided host from its /etc/resolv.conf
# @param [Host] host the host to act upon
def get_domain_name(host)
domain = nil
search = nil
if host['platform'] =~ /windows/
if host.is_cygwin?
resolv_conf = host.exec(Command.new("cat /cygdrive/c/Windows/System32/drivers/etc/hosts")).stdout
else
resolv_conf = host.exec(Command.new('type C:\Windows\System32\drivers\etc\hosts')).stdout
end
else
resolv_conf = host.exec(Command.new("cat /etc/resolv.conf")).stdout
end
resolv_conf.each_line { |line|
if line =~ /^\s*domain\s+(\S+)/
domain = $1
elsif line =~ /^\s*search\s+(\S+)/
search = $1
end
}
return_value ||= domain
return_value ||= search
if return_value
return_value.gsub(/\.$/, '')
end
end
#Determine the ip address of the provided host
# @param [Host] host the host to act upon
# @deprecated use {Host#get_ip}
def get_ip(host)
host.get_ip
end
#Append the provided string to the /etc/hosts file of the provided host
# @param [Host] host the host to act upon
# @param [String] etc_hosts The string to append to the /etc/hosts file
def set_etc_hosts(host, etc_hosts)
if host['platform'] =~ /freebsd/
host.echo_to_file(etc_hosts, '/etc/hosts')
elsif ((host['platform'] =~ /windows/) and not host.is_cygwin?)
host.exec(Command.new("echo '#{etc_hosts}' >> C:\\Windows\\System32\\drivers\\etc\\hosts"))
else
host.exec(Command.new("echo '#{etc_hosts}' >> /etc/hosts"))
end
# AIX must be configured to prefer local DNS over external
if host['platform'] =~ /aix/
aix_netsvc = '/etc/netsvc.conf'
aix_local_resolv = 'hosts = local, bind'
unless host.exec(Command.new("grep '#{aix_local_resolv}' #{aix_netsvc}"), :accept_all_exit_codes => true).exit_code == 0
host.exec(Command.new("echo '#{aix_local_resolv}' >> #{aix_netsvc}"))
end
end
end
#Make it possible to log in as root by copying the current users ssh keys to the root account
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def copy_ssh_to_root host, opts
logger = opts[:logger]
block_on host do |host|
logger.debug "Give root a copy of current user's keys, on #{host.name}"
if host['platform'] =~ /windows/ and host.is_cygwin?
host.exec(Command.new('cp -r .ssh /cygdrive/c/Users/Administrator/.'))
host.exec(Command.new('chown -R Administrator /cygdrive/c/Users/Administrator/.ssh'))
elsif host['platform'] =~ /windows/ and not host.is_cygwin?
# from https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true:
# /i : If Source is a directory or contains wildcards and Destination
# does not exist, xcopy assumes destination specifies a directory
# name and creates a new directory. Then, xcopy copies all specified
# files into the new directory. By default, xcopy prompts you to
# specify whether Destination is a file or a directory.
#
# /y : Suppresses prompting to confirm that you want to overwrite an
# existing destination file.
host.exec(Command.new("if exist .ssh (xcopy .ssh C:\\Users\\Administrator\\.ssh /s /e /y /i)"))
elsif host['platform'] =~ /osx/
host.exec(Command.new('sudo cp -r .ssh /var/root/.'), {:pty => true})
elsif host['platform'] =~ /freebsd/
host.exec(Command.new('sudo cp -r .ssh /root/.'), {:pty => true})
elsif host['platform'] =~ /openbsd/
host.exec(Command.new('sudo cp -r .ssh /root/.'), {:pty => true})
elsif host['platform'] =~ /solaris-10/
host.exec(Command.new('sudo cp -r .ssh /.'), {:pty => true})
elsif host['platform'] =~ /solaris-11/
host.exec(Command.new('sudo cp -r .ssh /root/.'), {:pty => true})
else
host.exec(Command.new('sudo su -c "cp -r .ssh /root/."'), {:pty => true})
end
if host.selinux_enabled?
host.exec(Command.new('sudo fixfiles restore /root'))
end
end
end
# Update /etc/hosts to make it possible for each provided host to reach each other host by name.
# Assumes that each provided host has host[:ip] set; in the instance where a provider sets
# host['ip'] to an address which facilitates access to the host externally, but the actual host
# addresses differ from this, we check first for the presence of a host['vm_ip'] key first,
# and use that if present.
# @param [Host, Array<Host>] hosts An array of hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def hack_etc_hosts hosts, opts
etc_hosts = "127.0.0.1\tlocalhost localhost.localdomain\n"
hosts.each do |host|
ip = host['vm_ip'] || host['ip'].to_s
hostname = host[:vmhostname] || host.name
domain = get_domain_name(host)
etc_hosts += "#{ip}\t#{hostname}.#{domain} #{hostname}\n"
end
hosts.each do |host|
set_etc_hosts(host, etc_hosts)
end
end
# Update /etc/hosts to make updates.puppetlabs.com (aka the dujour server) resolve to 127.0.01,
# so that we don't pollute the server with test data. See SERVER-1000, BKR-182, BKR-237, DJ-10
# for additional details.
def disable_updates hosts, opts
logger = opts[:logger]
hosts.each do |host|
next if host['platform'] =~ /netscaler/
logger.notify "Disabling updates.puppetlabs.com by modifying hosts file to resolve updates to 127.0.0.1 on #{host}"
set_etc_hosts(host, "127.0.0.1\tupdates.puppetlabs.com\n")
end
end
# Update sshd_config on debian, ubuntu, centos, el, redhat, cumulus, and fedora boxes to allow for root login
#
# Does nothing on other platfoms.
#
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def enable_root_login host, opts
logger = opts[:logger]
block_on host do |host|
logger.debug "Update sshd_config to allow root login"
if host['platform'] =~ /osx/
# If osx > 10.10 use '/private/etc/ssh/sshd_config', else use '/etc/sshd_config'
ssh_config_file = '/private/etc/ssh/sshd_config'
ssh_config_file = '/etc/sshd_config' if host['platform'] =~ /^osx-10\.(9|10)/i
host.exec(Command.new("sudo sed -i '' 's/#PermitRootLogin no/PermitRootLogin Yes/g' #{ssh_config_file}"))
host.exec(Command.new("sudo sed -i '' 's/#PermitRootLogin yes/PermitRootLogin Yes/g' #{ssh_config_file}"))
elsif host['platform'] =~ /freebsd/
host.exec(Command.new("sudo sed -i -e 's/#PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config"), {:pty => true} )
elsif host['platform'] =~ /openbsd/
host.exec(Command.new("sudo perl -pi -e 's/^PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config"), {:pty => true} )
elsif host['platform'] =~ /solaris-10/
host.exec(Command.new("sudo gsed -i -e 's/#PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config"), {:pty => true} )
elsif host['platform'] =~ /solaris-11/
host.exec(Command.new("if grep \"root::::type=role\" /etc/user_attr; then sudo rolemod -K type=normal root; else echo \"root user already type=normal\"; fi"), {:pty => true} )
host.exec(Command.new("sudo gsed -i -e 's/PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config"), {:pty => true} )
elsif host.is_cygwin?
host.exec(Command.new("sed -ri 's/^#?PermitRootLogin /PermitRootLogin yes/' /etc/sshd_config"), {:pty => true})
elsif host.is_powershell?
logger.warn("Attempting to enable root login non-supported platform: #{host.name}: #{host['platform']}")
else
host.exec(Command.new("sudo su -c \"sed -ri 's/^#?PermitRootLogin no|^#?PermitRootLogin yes/PermitRootLogin yes/' /etc/ssh/sshd_config\""), {:pty => true})
end
#restart sshd
if host['platform'] =~ /debian|ubuntu|cumulus/
host.exec(Command.new("sudo su -c \"service ssh restart\""), {:pty => true})
elsif host['platform'] =~ /arch|centos-7|el-7|redhat-7|fedora-(1[4-9]|2[0-9])/
host.exec(Command.new("sudo -E systemctl restart sshd.service"), {:pty => true})
elsif host['platform'] =~ /centos|el-|redhat|fedora|eos/
host.exec(Command.new("sudo -E /sbin/service sshd reload"), {:pty => true})
elsif host['platform'] =~ /(free|open)bsd/
host.exec(Command.new("sudo /etc/rc.d/sshd restart"))
elsif host['platform'] =~ /solaris/
host.exec(Command.new("sudo -E svcadm restart network/ssh"), {:pty => true} )
else
logger.warn("Attempting to update ssh on non-supported platform: #{host.name}: #{host['platform']}")
end
end
end
#Disable SELinux on centos, does nothing on other platforms
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def disable_se_linux host, opts
logger = opts[:logger]
block_on host do |host|
if host['platform'] =~ /centos|el-|redhat|fedora|eos/
@logger.debug("Disabling se_linux on #{host.name}")
host.exec(Command.new("sudo su -c \"setenforce 0\""), {:pty => true})
else
@logger.warn("Attempting to disable SELinux on non-supported platform: #{host.name}: #{host['platform']}")
end
end
end
#Disable iptables on centos, does nothing on other platforms
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def disable_iptables host, opts
logger = opts[:logger]
block_on host do |host|
if host['platform'] =~ /centos|el-|redhat|fedora|eos/
logger.debug("Disabling iptables on #{host.name}")
host.exec(Command.new("sudo su -c \"/etc/init.d/iptables stop\""), {:pty => true})
else
logger.warn("Attempting to disable iptables on non-supported platform: #{host.name}: #{host['platform']}")
end
end
end
# Setup files for enabling requests to pass to a proxy server
# This works for the APT package manager on debian, ubuntu, and cumulus
# and YUM package manager on el, centos, fedora and redhat.
# @param [Host, Array<Host>, String, Symbol] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
# @option opts [Beaker::Logger] :logger A {Beaker::Logger} object
def package_proxy host, opts
logger = opts[:logger]
block_on host do |host|
logger.debug("enabling proxy support on #{host.name}")
case host['platform']
when /ubuntu/, /debian/, /cumulus/
host.exec(Command.new("echo 'Acquire::http::Proxy \"#{opts[:package_proxy]}/\";' >> /etc/apt/apt.conf.d/10proxy"))
when /^el-/, /centos/, /fedora/, /redhat/, /eos/
host.exec(Command.new("echo 'proxy=#{opts[:package_proxy]}/' >> /etc/yum.conf"))
else
logger.debug("Attempting to enable package manager proxy support on non-supported platform: #{host.name}: #{host['platform']}")
end
end
end
# Merge the two provided hashes so that an array of values is created from collisions
# @param [Hash] h1 The first hash
# @param [Hash] h2 The second hash
# @return [Hash] A merged hash with arrays of values where collisions between the two hashes occured.
# @example
# > h1 = {:PATH=>"/1st/path"}
# > h2 = {:PATH=>"/2nd/path"}
# > additive_hash_merge(h1, h2)
# => {:PATH=>["/1st/path", "/2nd/path"]}
def additive_hash_merge h1, h2
merged_hash = {}
normalized_h2 = h2.inject({}) { |h, (k, v)| h[k.to_s.upcase] = v; h }
h1.each_pair do |key, val|
normalized_key = key.to_s.upcase
if normalized_h2.has_key?(normalized_key)
merged_hash[key] = [h1[key], normalized_h2[normalized_key]]
merged_hash[key] = merged_hash[key].uniq #remove dupes
end
end
merged_hash
end
# Create the hash of default environment from host (:host_env), global options hash (:host_env) and default PE/Foss puppet variables
# @param [Host] host The host to construct the environment hash for, host specific environment should be in :host_env in a hash
# @param [Hash] opts Hash of options, including optional global host_env to be applied to each provided host
# @return [Hash] A hash of environment variables for provided host
def construct_env host, opts
env = additive_hash_merge(host[:host_env], opts[:host_env])
env.each_key do |key|
separator = host['pathseparator']
if key == 'PATH' && (not host.is_powershell?)
separator = ':'
end
env[key] = env[key].join(separator)
end
env
end
# Add a host specific set of env vars to each provided host's ~/.ssh/environment
# @param [Host, Array<Host>] host One or more hosts to act upon
# @param [Hash{Symbol=>String}] opts Options to alter execution.
def set_env host, opts
logger = opts[:logger]
block_on host do |host|
skip_msg = host.skip_set_env?
unless skip_msg.nil?
logger.debug( skip_msg )
next
end
env = construct_env(host, opts)
logger.debug("setting local environment on #{host.name}")
if host['platform'] =~ /windows/ and host.is_cygwin?
env['CYGWIN'] = 'nodosfilewarning'
end
host.ssh_permit_user_environment()
host.ssh_set_user_environment(env)
# REMOVE POST BEAKER 3: backwards compatability, do some setup based upon the global type
# this is the worst and i hate it
Class.new.extend(Beaker::DSL).configure_type_defaults_on(host)
#close the host to re-establish the connection with the new sshd settings
host.close
# print out the working env
if host.is_powershell?
host.exec(Command.new("SET"))
else
host.exec(Command.new("cat #{host[:ssh_env_file]}"))
end
end
end
private
# A helper to tell whether a host is el-based
# @param [Host] host the host to act upon
#
# @return [Boolean] if the host is el_based
def el_based? host
['centos','redhat','scientific','el','oracle'].include?(host['platform'].variant)
end
end
end
| 1 | 15,207 | It seems a little odd to have both `host.is_cygwin?` *and* `host.cygwin_installed?` defined (with a possibility of having `is_cygwin?` be `true`, but `cygwin_installed?` returning `false`). Do the docs clearly explain the difference? | voxpupuli-beaker | rb |
@@ -73,8 +73,8 @@ public class ManifestFiles {
* @return a manifest writer
*/
public static ManifestWriter write(PartitionSpec spec, OutputFile outputFile) {
- // always use a v1 writer for appended manifests because sequence number must be inherited
- return write(1, spec, outputFile, null);
+ // always use a v2 writer to preserve sequence numbers, but use null for sequence number so appends inherit
+ return write(2, spec, outputFile, null);
}
/** | 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.Sets;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import org.apache.iceberg.exceptions.RuntimeIOException;
import org.apache.iceberg.io.FileIO;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.io.OutputFile;
public class ManifestFiles {
private ManifestFiles() {
}
/**
* Returns a new {@link ManifestReader} for a {@link ManifestFile}.
* <p>
* <em>Note:</em> Callers should use {@link ManifestFiles#read(ManifestFile, FileIO, Map)} to ensure
* the schema used by filters is the latest table schema. This should be used only when reading
* a manifest without filters.
*
* @param manifest a ManifestFile
* @param io a FileIO
* @return a manifest reader
*/
public static ManifestReader read(ManifestFile manifest, FileIO io) {
return read(manifest, io, null);
}
/**
* Returns a new {@link ManifestReader} for a {@link ManifestFile}.
*
* @param manifest a {@link ManifestFile}
* @param io a {@link FileIO}
* @param specsById a Map from spec ID to partition spec
* @return a {@link ManifestReader}
*/
public static ManifestReader read(ManifestFile manifest, FileIO io, Map<Integer, PartitionSpec> specsById) {
InputFile file = io.newInputFile(manifest.path());
InheritableMetadata inheritableMetadata = InheritableMetadataFactory.fromManifest(manifest);
return new ManifestReader(file, specsById, inheritableMetadata);
}
/**
* Create a new {@link ManifestWriter}.
* <p>
* Manifests created by this writer have all entry snapshot IDs set to null.
* All entries will inherit the snapshot ID that will be assigned to the manifest on commit.
*
* @param spec {@link PartitionSpec} used to produce {@link DataFile} partition tuples
* @param outputFile the destination file location
* @return a manifest writer
*/
public static ManifestWriter write(PartitionSpec spec, OutputFile outputFile) {
// always use a v1 writer for appended manifests because sequence number must be inherited
return write(1, spec, outputFile, null);
}
/**
* Create a new {@link ManifestWriter} for the given format version.
*
* @param formatVersion a target format version
* @param spec a {@link PartitionSpec}
* @param outputFile an {@link OutputFile} where the manifest will be written
* @param snapshotId a snapshot ID for the manifest entries, or null for an inherited ID
* @return a manifest writer
*/
static ManifestWriter write(int formatVersion, PartitionSpec spec, OutputFile outputFile, Long snapshotId) {
switch (formatVersion) {
case 1:
return new ManifestWriter.V1Writer(spec, outputFile, snapshotId);
case 2:
return new ManifestWriter.V2Writer(spec, outputFile, snapshotId);
}
throw new UnsupportedOperationException("Cannot write manifest for table version: " + formatVersion);
}
static ManifestFile copyAppendManifest(int formatVersion, ManifestReader reader, OutputFile outputFile,
long snapshotId, SnapshotSummary.Builder summaryBuilder) {
return copyManifest(
formatVersion, reader, outputFile, snapshotId, summaryBuilder, Sets.newHashSet(ManifestEntry.Status.ADDED));
}
static ManifestFile copyManifest(int formatVersion, ManifestReader reader, OutputFile outputFile, long snapshotId,
SnapshotSummary.Builder summaryBuilder,
Set<ManifestEntry.Status> allowedEntryStatuses) {
ManifestWriter writer = write(formatVersion, reader.spec(), outputFile, snapshotId);
boolean threw = true;
try {
for (ManifestEntry entry : reader.entries()) {
Preconditions.checkArgument(
allowedEntryStatuses.contains(entry.status()),
"Invalid manifest entry status: %s (allowed statuses: %s)",
entry.status(), allowedEntryStatuses);
switch (entry.status()) {
case ADDED:
summaryBuilder.addedFile(reader.spec(), entry.file());
writer.add(entry);
break;
case EXISTING:
writer.existing(entry);
break;
case DELETED:
summaryBuilder.deletedFile(reader.spec(), entry.file());
writer.delete(entry);
break;
}
}
threw = false;
} finally {
try {
writer.close();
} catch (IOException e) {
if (!threw) {
throw new RuntimeIOException(e, "Failed to close manifest: %s", outputFile);
}
}
}
return writer.toManifestFile();
}
}
| 1 | 19,512 | Does this mean manifests will be written with the v2 schema (i.e. with sequence numbers) even though `TableMetadata` is v1 and the manifest list is written with v1? And this should work because we do a projection on read and sequence number is optional? | apache-iceberg | java |
@@ -47,4 +47,7 @@ public class SparkWriteOptions {
// Checks if input schema and table schema are same(default: true)
public static final String CHECK_ORDERING = "check-ordering";
+
+ // File scan task set ID that is being rewritten
+ public static final String REWRITTEN_FILE_SCAN_TASK_SET_ID = "rewritten-file-scan-task-set-id";
} | 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.spark;
/**
* Spark DF write options
*/
public class SparkWriteOptions {
private SparkWriteOptions() {
}
// Fileformat for write operations(default: Table write.format.default )
public static final String WRITE_FORMAT = "write-format";
// Overrides this table's write.target-file-size-bytes
public static final String TARGET_FILE_SIZE_BYTES = "target-file-size-bytes";
// Sets the nullable check on fields(default: true)
public static final String CHECK_NULLABILITY = "check-nullability";
// Adds an entry with custom-key and corresponding value in the snapshot summary
// ex: df.write().format(iceberg)
// .option(SparkWriteOptions.SNAPSHOT_PROPERTY_PREFIX."key1", "value1")
// .save(location)
public static final String SNAPSHOT_PROPERTY_PREFIX = "snapshot-property";
// Overrides table property write.spark.fanout.enabled(default: false)
public static final String FANOUT_ENABLED = "fanout-enabled";
// Checks if input schema and table schema are same(default: true)
public static final String CHECK_ORDERING = "check-ordering";
}
| 1 | 36,350 | Should we be sharing this property key with the read? Maybe it should be belong to the file-scan-task object itself? | apache-iceberg | java |
@@ -82,6 +82,15 @@ type TestFields struct {
NoOutput bool `name:"no_test_output"`
}
+type DebugFields struct {
+ // Shell command to debug targets.
+ Command string `name:"debug_cmd"`
+ // Like tools but available to the debug_cmd instead
+ tools []BuildInput `name:"debug_tools"`
+ // Named debug tools, similar to named sources.
+ namedTools map[string][]BuildInput `name:"debug_tools"`
+}
+
// A BuildTarget is a representation of a build target and all information about it;
// its name, dependencies, build commands, etc.
type BuildTarget struct { | 1 | package core
import (
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
"github.com/thought-machine/please/src/fs"
)
// OutDir is the root output directory for everything.
const OutDir string = "plz-out"
// TmpDir is the root of the temporary directory for building targets & running tests.
const TmpDir string = "plz-out/tmp"
// GenDir is the output directory for non-binary targets.
const GenDir string = "plz-out/gen"
// BinDir is the output directory for binary targets.
const BinDir string = "plz-out/bin"
// DefaultBuildingDescription is the default description for targets when they're building.
const DefaultBuildingDescription = "Building..."
// SandboxDir is the directory that sandboxed actions are run in.
const SandboxDir = "/tmp/plz_sandbox"
// Suffixes for temporary directories
const buildDirSuffix = "._build"
const testDirSuffix = "._test"
// TestResultsFile is the file that targets output their test results into.
// This is normally defined for them via an environment variable.
const TestResultsFile = "test.results"
// CoverageFile is the file that targets output coverage information into.
// This is similarly defined via an environment variable.
const CoverageFile = "test.coverage"
// TestResultsDirLabel is a known label that indicates that the test will output results
// into a directory rather than a file. Please can internally handle either but the remote
// execution API requires that we specify which is which.
const TestResultsDirLabel = "test_results_dir"
// tempOutputSuffix is the suffix we attach to temporary outputs to avoid name clashes.
const tempOutputSuffix = ".out"
// lockFileSuffix is the suffix we attach to lock files.
const lockFileSuffix = ".lock"
type TestFields struct {
// Shell command to run for test targets.
Command string `name:"test_cmd"`
// Per-configuration test commands to run.
Commands map[string]string `name:"test_cmd"`
// The results of this test target, if it is one.
Results *TestSuite `print:"false"`
// Like tools but available to the test_cmd instead
tools []BuildInput `name:"test_tools"`
// Named test tools, similar to named sources.
namedTools map[string][]BuildInput `name:"test_tools"`
// The timeout for the test
Timeout time.Duration `name:"test_timeout"`
// Extra output files from the test.
// These are in addition to the usual test.results output file.
Outputs []string `name:"test_outputs"`
// Flakiness of test, ie. number of times we will rerun it before giving up. 1 is the default.
Flakiness uint8 `name:"flaky"`
// True if the test action is sandboxed.
Sandbox bool `name:"test_sandbox"`
// True if the target is a test and has no output file.
// Default is false, meaning all tests must produce test.results as output.
NoOutput bool `name:"no_test_output"`
}
// A BuildTarget is a representation of a build target and all information about it;
// its name, dependencies, build commands, etc.
type BuildTarget struct {
// N.B. The tags on these fields are used by query print to help it print them.
// Identifier of this build target
Label BuildLabel `name:"name"`
// If this target is in a subrepo, this will be the one it's in.
Subrepo *Subrepo `print:"false"`
// Dependencies of this target.
// Maps the original declaration to whatever dependencies actually got attached,
// which may be more than one in some cases. Also contains info about exporting etc.
dependencies []depInfo `name:"deps"`
// List of build target patterns that can use this build target.
Visibility []BuildLabel
// Source files of this rule. Can refer to build rules themselves.
Sources []BuildInput `name:"srcs"`
// Named source files of this rule; as above but identified by name.
NamedSources map[string][]BuildInput `name:"srcs"`
// Data files of this rule. Similar to sources but used at runtime, typically by tests.
Data []BuildInput `name:"data"`
// Data files of this rule by name.
namedData map[string][]BuildInput `name:"data"`
// Output files of this rule. All are paths relative to this package.
outputs []string `name:"outs"`
// Named output subsets of this rule. All are paths relative to this package but can be
// captured separately; for example something producing C code might separate its outputs
// into sources and headers.
namedOutputs map[string][]string `name:"outs"`
// Optional output files of this rule. Same as outs but aren't required to be produced always.
// Can be glob patterns.
OptionalOutputs []string `name:"optional_outs"`
// Optional labels applied to this rule. Used for including/excluding rules.
Labels []string
// Shell command to run.
Command string `name:"cmd" hide:"filegroup"`
// Per-configuration shell commands to run.
Commands map[string]string `name:"cmd" hide:"filegroup"`
Test *TestFields `name:"test"`
// If ShowProgress is true, this is used to store the current progress of the target.
Progress float32 `print:"false"`
// Description displayed while the command is building.
// Default is just "Building" but it can be customised.
BuildingDescription string `name:"building_description"`
// Acceptable hashes of the outputs of this rule. If the output doesn't match any of these
// it's an error at build time. Can be used to validate third-party deps.
Hashes []string
// Licences that this target is subject to.
Licences []string
// Any secrets that this rule requires.
// Secrets are similar to sources but are always absolute system paths and affect the hash
// differently; they are not used to determine the hash for retrieving a file from cache, but
// if changed locally will still force a rebuild. They're not copied into the source directory
// (or indeed anywhere by plz).
Secrets []string
// Named secrets of this rule; as above but identified by name.
NamedSecrets map[string][]string
// BUILD language functions to call before / after target is built. Allows deferred manipulation of the build graph.
PreBuildFunction PreBuildFunction `name:"pre_build"`
PostBuildFunction PostBuildFunction `name:"post_build"`
// Languages this rule requires. These are an arbitrary set and the only meaning is that they
// correspond to entries in Provides; if rules match up then it allows choosing a specific
// dependency (consider eg. code generated from protobufs; this mechanism allows us to expose
// one rule but only compile the appropriate code for each library that consumes it).
Requires []string
// Dependent rules this rule provides for each language. Matches up to Requires as described above.
Provides map[string]BuildLabel
// Stores the hash of this build rule before any post-build function is run.
RuleHash []byte `name:"exported_deps"` // bit of a hack to call this exported_deps...
// Tools that this rule will use, ie. other rules that it may use at build time which are not
// copied into its source directory.
Tools []BuildInput
// Named tools, similar to named sources.
namedTools map[string][]BuildInput `name:"tools"`
// Target-specific environment passthroughs.
PassEnv *[]string `name:"pass_env"`
// Target-specific unsafe environment passthroughs.
PassUnsafeEnv *[]string `name:"pass_unsafe_env"`
// Timeouts for build/test actions
BuildTimeout time.Duration `name:"build_timeout"`
// OutputDirectories are the directories that outputs can be produced into which will be added to the root of the
// output for the rule. For example if an output directory "foo" contains "bar.txt" the rule will have the output
// "bar.txt"
OutputDirectories []OutputDirectory `name:"output_dirs"`
// EntryPoints represent named binaries within the rules output that can be targeted via //package:rule|entry_point_name
EntryPoints map[string]string `name:"entry_points"`
// Used to arbitrate concurrent access to dependencies, and to the test results.
mutex sync.RWMutex `print:"false"`
// Used to notify once this target has built successfully.
finishedBuilding chan struct{} `print:"false"`
// Env are any custom environment variables to set for this build target
Env map[string]string `name:"env"`
// The content of text_file() rules
FileContent string `name:"content"`
// Represents the state of this build target (see below)
state int32 `print:"false"`
// The number of completed runs
completedRuns uint16 `print:"false"`
// True if this target is a binary (ie. runnable, will appear in plz-out/bin)
IsBinary bool `name:"binary"`
// Indicates that the target can only be depended on by tests or other rules with this set.
// Used to restrict non-deployable code and also affects coverage detection.
TestOnly bool `name:"test_only"`
// True if the build action is sandboxed.
Sandbox bool
// True if this target needs access to its transitive dependencies to build.
// This would be false for most 'normal' genrules but true for eg. compiler steps
// that need to build in everything.
NeedsTransitiveDependencies bool `name:"needs_transitive_deps"`
// True if this target blocks recursive exploring for transitive dependencies.
// This is typically false for _library rules which aren't complete, and true
// for _binary rules which normally are, and genrules where you don't care about
// the inputs, only whatever they were turned into.
OutputIsComplete bool `name:"output_is_complete"`
// If true, the rule is given an env var at build time that contains the hash of its
// transitive dependencies, which can be used to identify the output in a predictable way.
Stamp bool
// If true, the target must be run locally (i.e. is not compatible with remote execution).
Local bool
// If true, the executed commands will exit whenever an error is encountered (i.e. shells
// are executed with -e).
ExitOnError bool
// If true, the target is needed for a subinclude and therefore we will have to make sure its
// outputs are available locally when built.
NeededForSubinclude bool `print:"false"`
// Marks the target as a filegroup.
IsFilegroup bool `print:"false"`
// Marks the target as a remote_file.
IsRemoteFile bool `print:"false"`
// Marks the target as a text_file.
IsTextFile bool `print:"false"`
// Marks that the target was added in a post-build function.
AddedPostBuild bool `print:"false"`
// If true, the interactive progress display will try to infer the target's progress
// via some heuristics on its output.
ShowProgress bool `name:"progress"`
}
// BuildMetadata is temporary metadata that's stored around a build target - we don't
// generally persist it indefinitely.
type BuildMetadata struct {
// Standard output & error
Stdout, Stderr []byte
// Serialised build action metadata.
RemoteAction []byte
// Time this action was written. Used for remote execution to determine if
// the action is stale and needs re-checking or not.
Timestamp time.Time
// Additional optional outputs found from wildcard
OptionalOutputs []string
// Additional outputs from output directories serialised as a csv
OutputDirOuts []string
// True if this represents a test run.
Test bool
// True if the results were retrieved from a cache, false if we ran the full build action.
Cached bool
}
// A PreBuildFunction is a type that allows hooking a pre-build callback.
type PreBuildFunction interface {
fmt.Stringer
// Call calls this pre-build function
Call(target *BuildTarget) error
}
// A PostBuildFunction is a type that allows hooking a post-build callback.
type PostBuildFunction interface {
fmt.Stringer
// Call calls this pre-build function with this target and its output.
Call(target *BuildTarget, output string) error
}
type depInfo struct {
declared *BuildLabel // the originally declared dependency
deps []*BuildTarget // list of actual deps
resolved bool // has the graph resolved it
exported bool // is it an exported dependency
internal bool // is it an internal dependency (that is not picked up implicitly by transitive searches)
source bool // is it implicit because it's a source (not true if it's a dependency too)
data bool // is it a data item for a test
}
// OutputDirectory is an output directory for the build rule. It may have a suffix of /** which means that we should
// traverse the directory tree adding each file individually rather than just adding whatever files/directories are in
// the top level.
type OutputDirectory string
// Dir returns the actual directory name for this output directory
func (o OutputDirectory) Dir() string {
return strings.TrimSuffix(string(o), "/**")
}
// ShouldAddFiles checks whether the contents of this directory should include all the files in the directory tree
// individually i.e. out_dir/net/thoughtmachine/Main.java -> net/thoughtmachine/Main.java. If this is false then these
// files would be included as out_dir/net/thoughtmachine/Main.java -> net.
func (o OutputDirectory) ShouldAddFiles() bool {
return strings.HasSuffix(string(o), "/**")
}
// A BuildTargetState tracks the current state of this target in regard to whether it's built
// or not. Targets only move forwards through this (i.e. the state of a target only ever increases).
type BuildTargetState uint8
// The available states for a target.
const (
Inactive BuildTargetState = iota // Target isn't used in current build
Semiactive // Target would be active if we needed a build
Active // Target is going to be used in current build
Pending // Target is ready to be built but not yet started.
Building // Target is currently being built
Stopped // We stopped building the target because we'd gone as far as needed.
Built // Target has been successfully built
Cached // Target has been retrieved from the cache
Unchanged // Target has been built but hasn't changed since last build
Reused // Outputs of previous build have been reused.
BuiltRemotely // Target has been built but outputs are not necessarily local.
ReusedRemotely // Outputs of previous remote action have been reused.
Failed // Target failed for some reason
)
// String implements the fmt.Stringer interface.
func (s BuildTargetState) String() string {
if s == Inactive {
return "Inactive"
} else if s == Semiactive {
return "Semiactive"
} else if s == Active {
return "Active"
} else if s == Pending {
return "Pending"
} else if s == Building {
return "Building"
} else if s == Stopped {
return "Stopped"
} else if s == Built {
return "Built"
} else if s == Cached {
return "Cached"
} else if s == Unchanged {
return "Unchanged"
} else if s == Reused {
return "Reused"
} else if s == Failed {
return "Failed"
} else if s == BuiltRemotely {
return "Built remotely"
} else if s == ReusedRemotely {
return "Reused remote outputs"
}
return "Unknown"
}
// NewBuildTarget constructs & returns a new BuildTarget.
func NewBuildTarget(label BuildLabel) *BuildTarget {
return &BuildTarget{
Label: label,
state: int32(Inactive),
BuildingDescription: DefaultBuildingDescription,
finishedBuilding: make(chan struct{}),
}
}
// String returns a stringified form of the build label of this target, which is
// a unique identity for it.
func (target *BuildTarget) String() string {
return target.Label.String()
}
// TmpDir returns the temporary working directory for this target, eg.
// //mickey/donald:goofy -> plz-out/tmp/mickey/donald/goofy._build
// Note the extra subdirectory to keep rules separate from one another, and the .build suffix
// to attempt to keep rules from duplicating the names of sub-packages; obviously that is not
// 100% reliable but we don't have a better solution right now.
func (target *BuildTarget) TmpDir() string {
return path.Join(TmpDir, target.Label.Subrepo, target.Label.PackageName, target.Label.Name+buildDirSuffix)
}
// BuildLockFile returns the lock filename for the target's build stage.
func (target *BuildTarget) BuildLockFile() string {
return target.TmpDir() + lockFileSuffix
}
// OutDir returns the output directory for this target, eg.
// //mickey/donald:goofy -> plz-out/gen/mickey/donald (or plz-out/bin if it's a binary)
func (target *BuildTarget) OutDir() string {
if target.IsBinary {
return path.Join(BinDir, target.Label.Subrepo, target.Label.PackageName)
}
return path.Join(GenDir, target.Label.Subrepo, target.Label.PackageName)
}
// TestDir returns the test directory for this target, eg.
// //mickey/donald:goofy -> plz-out/tmp/mickey/donald/goofy._test/run_1
// This is different to TmpDir so we run tests in a clean environment
// and to facilitate containerising tests.
func (target *BuildTarget) TestDir(runNumber int) string {
return path.Join(target.TestDirs(), fmt.Sprint("run_", runNumber))
}
// TestLockFile returns the lock filename for the target's test stage.
func (target *BuildTarget) TestLockFile(runNumber int) string {
return target.TestDir(runNumber) + lockFileSuffix
}
// TestDirs contains the parent directory of all the test run directories above
func (target *BuildTarget) TestDirs() string {
return path.Join(TmpDir, target.Label.Subrepo, target.Label.PackageName, target.Label.Name+testDirSuffix)
}
// IsTest returns whether or not the target is a test target i.e. has its Test field populated
func (target *BuildTarget) IsTest() bool {
return target.Test != nil
}
// CompleteRun completes a run and returns true if this was the last run
func (target *BuildTarget) CompleteRun(state *BuildState) bool {
target.mutex.Lock()
defer target.mutex.Unlock()
target.completedRuns++
return target.completedRuns == state.NumTestRuns
}
// TestResultsFile returns the output results file for tests for this target.
func (target *BuildTarget) TestResultsFile() string {
return path.Join(target.OutDir(), ".test_results_"+target.Label.Name)
}
// CoverageFile returns the output coverage file for tests for this target.
func (target *BuildTarget) CoverageFile() string {
return path.Join(target.OutDir(), ".test_coverage_"+target.Label.Name)
}
// AddTestResults adds results to the target
func (target *BuildTarget) AddTestResults(results TestSuite) {
target.mutex.Lock()
defer target.mutex.Unlock()
if len(target.Test.Results.TestCases) == 0 {
target.Test.Results.Cached = results.Cached // On the first run we take whatever this is
} else {
target.Test.Results.Cached = target.Test.Results.Cached && results.Cached
}
target.Test.Results.Collapse(results)
}
// StartTestSuite sets the initial properties on the result test suite
func (target *BuildTarget) StartTestSuite() {
target.mutex.Lock()
defer target.mutex.Unlock()
// If the results haven't been set yet, set them
if target.Test.Results == nil {
target.Test.Results = &TestSuite{
Package: strings.ReplaceAll(target.Label.PackageName, "/", "."),
Name: target.Label.Name,
Timestamp: time.Now().Format(time.RFC3339),
}
}
}
// AllSourcePaths returns all the source paths for this target
func (target *BuildTarget) AllSourcePaths(graph *BuildGraph) []string {
return target.allSourcePaths(graph, BuildInput.Paths)
}
// AllSourceFullPaths returns all the source paths for this target, with a leading
// plz-out/gen etc if appropriate.
func (target *BuildTarget) AllSourceFullPaths(graph *BuildGraph) []string {
return target.allSourcePaths(graph, BuildInput.FullPaths)
}
// AllSourceLocalPaths returns the local part of all the source paths for this target,
// i.e. without this target's package in it.
func (target *BuildTarget) AllSourceLocalPaths(graph *BuildGraph) []string {
return target.allSourcePaths(graph, BuildInput.LocalPaths)
}
type buildPathsFunc func(BuildInput, *BuildGraph) []string
func (target *BuildTarget) allSourcePaths(graph *BuildGraph, full buildPathsFunc) []string {
ret := make([]string, 0, len(target.Sources))
for _, source := range target.AllSources() {
ret = append(ret, target.sourcePaths(graph, source, full)...)
}
return ret
}
// AllURLs returns all the URLs for this target.
// This should only be called if the target is a remote file.
// The URLs will have any embedded environment variables expanded according to the given config.
func (target *BuildTarget) AllURLs(state *BuildState) []string {
env := GeneralBuildEnvironment(state)
ret := make([]string, len(target.Sources))
for i, s := range target.Sources {
ret[i] = os.Expand(string(s.(URLLabel)), env.ReplaceEnvironment)
}
return ret
}
// resolveDependencies matches up all declared dependencies to the actual build targets.
// TODO(peterebden,tatskaari): Work out if we really want to have this and how the suite of *Dependencies functions
// below should behave (preferably nicely).
func (target *BuildTarget) resolveDependencies(graph *BuildGraph, callback func(*BuildTarget) error) error {
var g errgroup.Group
target.mutex.RLock()
for i := range target.dependencies {
dep := &target.dependencies[i] // avoid using a loop variable here as it mutates each iteration
if len(dep.deps) > 0 {
continue // already done
}
g.Go(func() error {
if err := target.resolveOneDependency(graph, dep); err != nil {
return err
}
for _, d := range dep.deps {
if err := callback(d); err != nil {
return err
}
}
return nil
})
}
target.mutex.RUnlock()
return g.Wait()
}
func (target *BuildTarget) resolveOneDependency(graph *BuildGraph, dep *depInfo) error {
t := graph.WaitForTarget(*dep.declared)
if t == nil {
return fmt.Errorf("Couldn't find dependency %s", dep.declared)
}
dep.declared = &t.Label // saves memory by not storing the label twice once resolved
labels := t.provideFor(target)
if len(labels) == 0 {
target.mutex.Lock()
defer target.mutex.Unlock()
// Small optimisation to avoid re-looking-up the same target again.
dep.deps = []*BuildTarget{t}
return nil
}
deps := make([]*BuildTarget, 0, len(labels))
for _, l := range labels {
t := graph.WaitForTarget(l)
if t == nil {
return fmt.Errorf("%s depends on %s (provided by %s), however that target doesn't exist", target, l, t)
}
deps = append(deps, t)
}
target.mutex.Lock()
defer target.mutex.Unlock()
dep.deps = deps
return nil
}
// MustResolveDependencies is exposed only for testing purposes.
// TODO(peterebden, tatskaari): See if we can get rid of this.
func (target *BuildTarget) ResolveDependencies(graph *BuildGraph) error {
return target.resolveDependencies(graph, func(*BuildTarget) error { return nil })
}
// DeclaredDependencies returns all the targets this target declared any kind of dependency on (including sources and tools).
func (target *BuildTarget) DeclaredDependencies() []BuildLabel {
target.mutex.RLock()
defer target.mutex.RUnlock()
ret := make(BuildLabels, len(target.dependencies))
for i, dep := range target.dependencies {
ret[i] = *dep.declared
}
sort.Sort(ret)
return ret
}
// DeclaredDependenciesStrict returns the original declaration of this target's dependencies.
func (target *BuildTarget) DeclaredDependenciesStrict() []BuildLabel {
target.mutex.RLock()
defer target.mutex.RUnlock()
ret := make(BuildLabels, 0, len(target.dependencies))
for _, dep := range target.dependencies {
if !dep.exported && !dep.source && !target.IsTool(*dep.declared) {
ret = append(ret, *dep.declared)
}
}
sort.Sort(ret)
return ret
}
// Dependencies returns the resolved dependencies of this target.
func (target *BuildTarget) Dependencies() []*BuildTarget {
target.mutex.RLock()
defer target.mutex.RUnlock()
ret := make(BuildTargets, 0, len(target.dependencies))
for _, deps := range target.dependencies {
for _, dep := range deps.deps {
ret = append(ret, dep)
}
}
sort.Sort(ret)
return ret
}
// ExternalDependencies returns the non-internal dependencies of this target (i.e. not "_target#tag" ones).
func (target *BuildTarget) ExternalDependencies() []*BuildTarget {
target.mutex.RLock()
defer target.mutex.RUnlock()
ret := make(BuildTargets, 0, len(target.dependencies))
for _, deps := range target.dependencies {
for _, dep := range deps.deps {
if dep.Label.Parent() != target.Label {
ret = append(ret, dep)
} else {
ret = append(ret, dep.ExternalDependencies()...)
}
}
}
sort.Sort(ret)
return ret
}
// BuildDependencies returns the build-time dependencies of this target (i.e. not data and not internal).
func (target *BuildTarget) BuildDependencies() []*BuildTarget {
target.mutex.RLock()
defer target.mutex.RUnlock()
ret := make(BuildTargets, 0, len(target.dependencies))
for _, deps := range target.dependencies {
if !deps.data && !deps.internal {
for _, dep := range deps.deps {
ret = append(ret, dep)
}
}
}
sort.Sort(ret)
return ret
}
// ExportedDependencies returns any exported dependencies of this target.
func (target *BuildTarget) ExportedDependencies() []BuildLabel {
target.mutex.RLock()
defer target.mutex.RUnlock()
ret := make(BuildLabels, 0, len(target.dependencies))
for _, info := range target.dependencies {
if info.exported {
ret = append(ret, *info.declared)
}
}
return ret
}
// DependenciesFor returns the dependencies that relate to a given label.
func (target *BuildTarget) DependenciesFor(label BuildLabel) []*BuildTarget {
target.mutex.RLock()
defer target.mutex.RUnlock()
return target.dependenciesFor(label)
}
func (target *BuildTarget) dependenciesFor(label BuildLabel) []*BuildTarget {
if info := target.dependencyInfo(label); info != nil {
return info.deps
} else if target.Label.Subrepo != "" && label.Subrepo == "" {
// Can implicitly use the target's subrepo.
label.Subrepo = target.Label.Subrepo
return target.dependenciesFor(label)
}
return nil
}
// FinishBuild marks this target as having built.
func (target *BuildTarget) FinishBuild() {
close(target.finishedBuilding)
}
// WaitForBuild blocks until this target has finished building.
func (target *BuildTarget) WaitForBuild() {
<-target.finishedBuilding
}
// DeclaredOutputs returns the outputs from this target's original declaration.
// Hence it's similar to Outputs() but without the resolving of other rule names.
func (target *BuildTarget) DeclaredOutputs() []string {
return target.outputs
}
// DeclaredNamedOutputs returns the named outputs from this target's original declaration.
func (target *BuildTarget) DeclaredNamedOutputs() map[string][]string {
return target.namedOutputs
}
// DeclaredOutputNames is a convenience function to return the names of the declared
// outputs in a consistent order.
func (target *BuildTarget) DeclaredOutputNames() []string {
ret := make([]string, 0, len(target.namedOutputs))
for name := range target.namedOutputs {
ret = append(ret, name)
}
sort.Strings(ret)
return ret
}
// Outputs returns a slice of all the outputs of this rule.
func (target *BuildTarget) Outputs() []string {
var ret []string
if target.IsFilegroup {
ret = make([]string, 0, len(target.Sources))
// Filegroups just re-output their inputs.
for _, src := range target.Sources {
if namedLabel, ok := src.(AnnotatedOutputLabel); ok {
// Bit of a hack, but this needs different treatment from either of the others.
for _, dep := range target.DependenciesFor(namedLabel.BuildLabel) {
ret = append(ret, dep.NamedOutputs(namedLabel.Annotation)...)
}
} else if label, ok := src.nonOutputLabel(); !ok {
ret = append(ret, src.LocalPaths(nil)[0])
} else {
for _, dep := range target.DependenciesFor(label) {
ret = append(ret, dep.Outputs()...)
}
}
}
} else {
// Must really copy the slice before sorting it ([:] is too shallow)
ret = make([]string, len(target.outputs))
copy(ret, target.outputs)
}
if target.namedOutputs != nil {
for _, outputs := range target.namedOutputs {
ret = append(ret, outputs...)
}
}
sort.Strings(ret)
return ret
}
// FullOutputs returns a slice of all the outputs of this rule with the target's output directory prepended.
func (target *BuildTarget) FullOutputs() []string {
outs := target.Outputs()
outDir := target.OutDir()
for i, out := range outs {
outs[i] = path.Join(outDir, out)
}
return outs
}
// AllOutputs returns a slice of all the outputs of this rule, including any output directories.
// Outs are passed through GetTmpOutput as appropriate.
func (target *BuildTarget) AllOutputs() []string {
outs := target.Outputs()
for i, out := range outs {
outs[i] = target.GetTmpOutput(out)
}
for _, out := range target.OutputDirectories {
outs = append(outs, out.Dir())
}
return outs
}
// NamedOutputs returns a slice of all the outputs of this rule with a given name.
// If the name is not declared by this rule it panics.
func (target *BuildTarget) NamedOutputs(name string) []string {
if target.namedOutputs == nil {
return nil
}
if outs, present := target.namedOutputs[name]; present {
return outs
}
return nil
}
// GetTmpOutput takes the original output filename as an argument, and returns a temporary output
// filename(plz-out/tmp/) if output has the same name as the package, this avoids the name conflict issue
func (target *BuildTarget) GetTmpOutput(parseOutput string) string {
if target.IsFilegroup {
return parseOutput // Filegroups never need this.
} else if parseOutput == target.Label.PackageName {
return parseOutput + tempOutputSuffix
} else if target.Label.PackageName == "" && target.HasSource(parseOutput) {
// This also fixes the case where source and output are the same, which can happen
// when we're in the root directory.
return parseOutput + tempOutputSuffix
}
return parseOutput
}
// GetTmpOutputAll returns a slice of all the temporary outputs this is used in setting up environment for outputs,
// e.g: OUTS, OUT
func (target *BuildTarget) GetTmpOutputAll(parseOutputs []string) []string {
tmpOutputs := make([]string, len(parseOutputs))
for i, out := range parseOutputs {
tmpOutputs[i] = target.GetTmpOutput(out)
}
return tmpOutputs
}
// GetRealOutput returns the real output name for a filename that might have been a temporary output
// (i.e as returned by GetTmpOutput).
func (target *BuildTarget) GetRealOutput(output string) string {
if strings.HasSuffix(output, tempOutputSuffix) {
real := strings.TrimSuffix(output, tempOutputSuffix)
// Check this isn't a file that just happens to be named the same way
if target.GetTmpOutput(real) == output {
return real
}
}
return output
}
// SourcePaths returns the source paths for a given set of sources.
func (target *BuildTarget) SourcePaths(graph *BuildGraph, sources []BuildInput) []string {
ret := make([]string, 0, len(sources))
for _, source := range sources {
ret = append(ret, target.sourcePaths(graph, source, BuildInput.Paths)...)
}
return ret
}
// sourcePaths returns the source paths for a single source.
func (target *BuildTarget) sourcePaths(graph *BuildGraph, source BuildInput, f buildPathsFunc) []string {
if label, ok := source.nonOutputLabel(); ok {
ret := []string{}
for _, providedLabel := range graph.TargetOrDie(label).ProvideFor(target) {
ret = append(ret, f(providedLabel, graph)...)
}
return ret
}
return f(source, graph)
}
// CanSee returns true if target can see the given dependency, or false if not.
func (target *BuildTarget) CanSee(state *BuildState, dep *BuildTarget) bool {
return target.Label.CanSee(state, dep)
}
// CheckDependencyVisibility checks that all declared dependencies of this target are visible to it.
// Returns an error if not, or nil if all's well.
func (target *BuildTarget) CheckDependencyVisibility(state *BuildState) error {
for _, d := range target.dependencies {
dep := state.Graph.TargetOrDie(*d.declared)
if !target.CanSee(state, dep) {
return fmt.Errorf("Target %s isn't visible to %s", dep.Label, target.Label)
} else if dep.TestOnly && !(target.IsTest() || target.TestOnly) {
if target.Label.isExperimental(state) {
log.Warning("Test-only restrictions suppressed for %s since %s is in the experimental tree", dep.Label, target.Label)
} else {
return fmt.Errorf("Target %s can't depend on %s, it's marked test_only", target.Label, dep.Label)
}
}
}
return nil
}
// CheckDuplicateOutputs checks if any of the outputs of this target duplicate one another.
// Returns an error if so, or nil if all's well.
func (target *BuildTarget) CheckDuplicateOutputs() error {
outputs := map[string]struct{}{}
for _, output := range target.Outputs() {
if _, present := outputs[output]; present {
return fmt.Errorf("Target %s declares output file %s multiple times", target.Label, output)
}
outputs[output] = struct{}{}
}
return nil
}
// CheckTargetOwnsBuildOutputs checks that any outputs to this rule output into directories this of this package.
func (target *BuildTarget) CheckTargetOwnsBuildOutputs(state *BuildState) error {
// Skip this check for sub-repos because sub-repos are currently outputted into plz-gen so the output might also
// be a sub-repo that contains a package. This isn't the best solution but we can't fix this without reworking
// how sub-repos are done.
if target.Subrepo != nil {
return nil
}
for _, output := range target.Outputs() {
targetPackage := target.Label.PackageName
out := filepath.Join(targetPackage, output)
if fs.IsPackage(state.Config.Parse.BuildFileName, out) {
return fmt.Errorf("trying to output file %s, but that directory is another package", out)
}
// If the output is just a file in the package root, we don't need to check anything else.
if filepath.Dir(output) == "." {
continue
}
pkg := FindOwningPackage(state, out)
if targetPackage != pkg.PackageName {
return fmt.Errorf("trying to output file %s, but that directory belongs to another package (%s)", out, pkg.PackageName)
}
}
return nil
}
// CheckTargetOwnsBuildInputs checks that any file inputs to this rule belong to this package.
func (target *BuildTarget) CheckTargetOwnsBuildInputs(state *BuildState) error {
for _, input := range target.AllSources() {
if err := target.checkTargetOwnsBuildInput(state, input); err != nil {
return err
}
}
for _, input := range target.AllData() {
if err := target.checkTargetOwnsBuildInput(state, input); err != nil {
return err
}
}
return nil
}
func (target *BuildTarget) checkTargetOwnsBuildInput(state *BuildState, input BuildInput) error {
if input, ok := input.(FileLabel); ok {
for _, f := range input.Paths(state.Graph) {
if err := target.checkTargetOwnsFileAndSubDirectories(state, f); err != nil {
return err
}
}
}
return nil
}
func (target *BuildTarget) checkTargetOwnsFileAndSubDirectories(state *BuildState, file string) error {
pkg := FindOwningPackage(state, file)
if target.Label.PackageName != pkg.PackageName {
return fmt.Errorf("package %s is trying to use file %s, but that belongs to another package (%s)", target.Label.PackageName, file, pkg.PackageName)
}
if fs.IsDirectory(file) {
err := fs.Walk(file, func(name string, isDir bool) error {
if isDir && fs.IsPackage(state.Config.Parse.BuildFileName, name) {
return fmt.Errorf("cannot include %s as it contains subpackage %s", file, name)
}
return nil
})
if err != nil {
return err
}
}
return nil
}
// CheckSecrets checks that this target's secrets are available.
// We run this check before building because we don't attempt to copy them, but any rule
// requiring them will presumably fail if they aren't available.
// Returns an error if any aren't.
func (target *BuildTarget) CheckSecrets() error {
for _, secret := range target.AllSecrets() {
if path := fs.ExpandHomePath(secret); !PathExists(path) {
return fmt.Errorf("Path %s doesn't exist; it's required to build %s", secret, target.Label)
}
}
return nil
}
// AllSecrets returns all the sources of this rule.
func (target *BuildTarget) AllSecrets() []string {
ret := target.Secrets[:]
if target.NamedSecrets != nil {
keys := make([]string, 0, len(target.NamedSecrets))
for k := range target.NamedSecrets {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
ret = append(ret, target.NamedSecrets[k]...)
}
}
return ret
}
// HasDependency checks if a target already depends on this label.
func (target *BuildTarget) HasDependency(label BuildLabel) bool {
target.mutex.RLock()
defer target.mutex.RUnlock()
return target.dependencyInfo(label) != nil
}
// resolveDependency resolves a particular dependency on a target.
// TODO(jpoole): this is only used by tests: remove
func (target *BuildTarget) resolveDependency(label BuildLabel, dep *BuildTarget) {
target.mutex.Lock()
defer target.mutex.Unlock()
info := target.dependencyInfo(label)
if info == nil {
target.dependencies = append(target.dependencies, depInfo{declared: &label})
info = &target.dependencies[len(target.dependencies)-1]
}
if dep != nil {
info.deps = append(info.deps, dep)
}
info.resolved = true
}
// dependencyInfo returns the information about a declared dependency, or nil if the target doesn't have it.
func (target *BuildTarget) dependencyInfo(label BuildLabel) *depInfo {
for i, info := range target.dependencies {
if *info.declared == label {
return &target.dependencies[i]
}
}
return nil
}
// IsSourceOnlyDep returns true if the given dependency was only declared on the srcs of the target.
func (target *BuildTarget) IsSourceOnlyDep(label BuildLabel) bool {
info := target.dependencyInfo(label)
return info != nil && info.source
}
// State returns the target's current state.
func (target *BuildTarget) State() BuildTargetState {
return BuildTargetState(atomic.LoadInt32(&target.state))
}
// SetState sets a target's current state.
func (target *BuildTarget) SetState(state BuildTargetState) {
atomic.StoreInt32(&target.state, int32(state))
}
// SyncUpdateState oves the target's state from before to after via a lock.
// Returns true if successful, false if not (which implies something else changed the state first).
// The nature of our build graph ensures that most transitions are only attempted by
// one thread simultaneously, but this one can be attempted by several at once
// (eg. if a depends on b and c, which finish building simultaneously, they race to queue a).
func (target *BuildTarget) SyncUpdateState(before, after BuildTargetState) bool {
return atomic.CompareAndSwapInt32(&target.state, int32(before), int32(after))
}
// AddLabel adds the given label to this target if it doesn't already have it.
func (target *BuildTarget) AddLabel(label string) {
if !target.HasLabel(label) {
target.Labels = append(target.Labels, label)
}
}
// HasLabel returns true if target has the given label.
func (target *BuildTarget) HasLabel(label string) bool {
for _, l := range target.Labels {
if l == label {
return true
}
}
return label == "test" && target.IsTest()
}
// PrefixedLabels returns all labels of this target with the given prefix.
func (target *BuildTarget) PrefixedLabels(prefix string) []string {
ret := []string{}
for _, l := range target.Labels {
if strings.HasPrefix(l, prefix) {
ret = append(ret, strings.TrimPrefix(l, prefix))
}
}
return ret
}
// HasAnyLabel returns true if target has any of these labels.
func (target *BuildTarget) HasAnyLabel(labels []string) bool {
for _, label := range labels {
if target.HasLabel(label) {
return true
}
}
return false
}
// HasAllLabels returns true if target has all of these labels.
func (target *BuildTarget) HasAllLabels(labels []string) bool {
for _, label := range labels {
if !target.HasLabel(label) {
return false
}
}
return true
}
// ShouldInclude handles the typical include/exclude logic for a target's labels; returns true if
// target has any include label and not an exclude one.
// Each include/exclude can have multiple comma-separated labels; in this case, all of the labels
// in a given group must match.
func (target *BuildTarget) ShouldInclude(includes, excludes []string) bool {
if len(includes) == 0 && len(excludes) == 0 {
return true
}
// Include by default if no includes are specified.
shouldInclude := len(includes) == 0
for _, include := range includes {
if target.HasAllLabels(strings.Split(include, ",")) {
shouldInclude = true
break
}
}
for _, exclude := range excludes {
if target.HasAllLabels(strings.Split(exclude, ",")) {
shouldInclude = false
break
}
}
return shouldInclude
}
// AddProvide adds a new provide entry to this target.
func (target *BuildTarget) AddProvide(language string, label BuildLabel) {
if target.Provides == nil {
target.Provides = map[string]BuildLabel{language: label}
} else {
target.Provides[language] = label
}
}
// ProvideFor returns the build label that we'd provide for the given target.
func (target *BuildTarget) ProvideFor(other *BuildTarget) []BuildLabel {
if p := target.provideFor(other); len(p) > 0 {
return p
}
return []BuildLabel{target.Label}
}
// provideFor is like ProvideFor but returns an empty slice if there is a direct dependency.
// It's a small optimisation to save allocating extra slices.
func (target *BuildTarget) provideFor(other *BuildTarget) []BuildLabel {
target.mutex.RLock()
defer target.mutex.RUnlock()
if target.Provides == nil || len(other.Requires) == 0 {
return nil
}
// Never do this if the other target has a data or tool dependency on us.
for _, data := range other.Data {
if label, ok := data.Label(); ok && label == target.Label {
return nil
}
}
if other.IsTool(target.Label) {
return nil
}
var ret []BuildLabel
for _, require := range other.Requires {
if label, present := target.Provides[require]; present {
if ret == nil {
ret = make([]BuildLabel, 0, len(other.Requires))
}
ret = append(ret, label)
}
}
return ret
}
// UnprefixedHashes returns the hashes for the target without any prefixes;
// they are allowed to have optional prefixes before a colon which aren't taken
// into account for the resulting hash.
func (target *BuildTarget) UnprefixedHashes() []string {
hashes := target.Hashes[:]
for i, h := range hashes {
if index := strings.LastIndexByte(h, ':'); index != -1 {
hashes[i] = strings.TrimSpace(h[index+1:])
}
}
return hashes
}
// AddSource adds a source to the build target, deduplicating against existing entries.
func (target *BuildTarget) AddSource(source BuildInput) {
target.Sources = target.addSource(target.Sources, source)
}
func (target *BuildTarget) addSource(sources []BuildInput, source BuildInput) []BuildInput {
for _, src := range sources {
if source == src {
return sources
}
}
// Add a dependency if this is not just a file.
if label, ok := source.Label(); ok {
target.AddMaybeExportedDependency(label, false, true, false)
}
return append(sources, source)
}
// AddSecret adds a secret to the build target, deduplicating against existing entries.
func (target *BuildTarget) AddSecret(secret string) {
target.Secrets = target.addSecret(target.Secrets, secret)
}
func (target *BuildTarget) addSecret(secrets []string, secret string) []string {
for _, existing := range secrets {
if existing == secret {
return secrets
}
}
return append(secrets, secret)
}
// AddNamedSource adds a source to the target which is tagged with a particular name.
// For example, C++ rules add sources tagged as "sources" and "headers" to distinguish
// two conceptually different kinds of input.
func (target *BuildTarget) AddNamedSource(name string, source BuildInput) {
if target.NamedSources == nil {
target.NamedSources = map[string][]BuildInput{name: target.addSource(nil, source)}
} else {
target.NamedSources[name] = target.addSource(target.NamedSources[name], source)
}
}
// AddNamedSecret adds a secret to the target which is tagged with a particular name.
// These will be made available in the environment at runtime, with key-format "SECRETS_<NAME>".
func (target *BuildTarget) AddNamedSecret(name string, secret string) {
if target.NamedSecrets == nil {
target.NamedSecrets = map[string][]string{name: target.addSecret(nil, secret)}
} else {
target.NamedSecrets[name] = target.addSecret(target.NamedSecrets[name], secret)
}
}
// AddTool adds a new tool to the target.
func (target *BuildTarget) AddTool(tool BuildInput) {
target.Tools = append(target.Tools, tool)
if label, ok := tool.Label(); ok {
target.AddDependency(label)
}
}
// AddTestTool adds a new test tool to the target.
func (target *BuildTarget) AddTestTool(tool BuildInput) {
target.Test.tools = append(target.Test.tools, tool)
if label, ok := tool.Label(); ok {
target.AddDependency(label)
}
}
// AllTestTools returns all the test tool paths for this rule.
func (target *BuildTarget) AllTestTools() []BuildInput {
if target.Test.namedTools == nil {
return target.Test.tools
}
return target.allBuildInputs(target.Test.tools, target.Test.namedTools)
}
func (target *BuildTarget) NamedTestTools() map[string][]BuildInput {
return target.Test.namedTools
}
// AddDatum adds a new item of data to the target.
func (target *BuildTarget) AddDatum(datum BuildInput) {
target.Data = append(target.Data, datum)
if label, ok := datum.Label(); ok {
target.AddDependency(label)
target.dependencyInfo(label).data = true
}
}
// AddNamedDatum adds a data file to the target which is tagged with a particular name.
func (target *BuildTarget) AddNamedDatum(name string, datum BuildInput) {
if target.namedData == nil {
target.namedData = map[string][]BuildInput{name: {datum}}
} else {
target.namedData[name] = append(target.namedData[name], datum)
}
if label, ok := datum.Label(); ok {
target.AddDependency(label)
target.dependencyInfo(label).data = true
}
}
// AddNamedTool adds a new tool to the target.
func (target *BuildTarget) AddNamedTool(name string, tool BuildInput) {
if target.namedTools == nil {
target.namedTools = map[string][]BuildInput{name: {tool}}
} else {
target.namedTools[name] = append(target.namedTools[name], tool)
}
if label, ok := tool.Label(); ok {
target.AddDependency(label)
}
}
// AddNamedTestTool adds a new tool to the target.
func (target *BuildTarget) AddNamedTestTool(name string, tool BuildInput) {
if target.Test == nil {
target.Test = new(TestFields)
}
if target.Test.namedTools == nil {
target.Test.namedTools = map[string][]BuildInput{name: {tool}}
} else {
target.Test.namedTools[name] = append(target.Test.namedTools[name], tool)
}
if label, ok := tool.Label(); ok {
target.AddDependency(label)
}
}
// AddCommand adds a new config-specific command to this build target.
// Adding a general command is still done by simply setting the Command member.
func (target *BuildTarget) AddCommand(config, command string) {
if target.Command != "" {
panic(fmt.Sprintf("Adding named command %s to %s, but it already has a general command set", config, target.Label))
} else if target.Commands == nil {
target.Commands = map[string]string{config: command}
} else {
target.Commands[config] = command
}
}
// AddTestCommand adds a new config-specific test command to this build target.
// Adding a general command is still done by simply setting the Command member.
func (target *BuildTarget) AddTestCommand(config, command string) {
if target.Test.Command != "" {
panic(fmt.Sprintf("Adding named test command %s to %s, but it already has a general test command set", config, target.Label))
} else if target.Test.Commands == nil {
target.Test.Commands = map[string]string{config: command}
} else {
target.Test.Commands[config] = command
}
}
// GetCommand returns the command we should use to build this target for the current config.
func (target *BuildTarget) GetCommand(state *BuildState) string {
return target.getCommand(state, target.Commands, target.Command)
}
// GetCommandConfig returns the command we should use to build this target for the given config.
func (target *BuildTarget) GetCommandConfig(config string) string {
if config == "" {
return target.Command
}
return target.Commands[config]
}
// GetTestCommand returns the command we should use to test this target for the current config.
func (target *BuildTarget) GetTestCommand(state *BuildState) string {
return target.getCommand(state, target.Test.Commands, target.Test.Command)
}
func (target *BuildTarget) getCommand(state *BuildState, commands map[string]string, singleCommand string) string {
if commands == nil {
return singleCommand
} else if command, present := commands[state.Config.Build.Config]; present {
return command // Has command for current config, good
} else if command, present := commands[state.Config.Build.FallbackConfig]; present {
return command // Has command for default config, fall back to that
}
// Oh dear, target doesn't have any matching config. Panicking is a bit heavy here, instead
// fall back to an arbitrary (but consistent) one.
highestCommand := ""
highestConfig := ""
for config, command := range commands {
if config > highestConfig {
highestConfig = config
highestCommand = command
}
}
log.Warning("%s doesn't have a command for %s (or %s), falling back to %s",
target.Label, state.Config.Build.Config, state.Config.Build.FallbackConfig, highestConfig)
return highestCommand
}
// AllSources returns all the sources of this rule.
func (target *BuildTarget) AllSources() []BuildInput {
if target.NamedSources == nil {
return target.Sources
}
return target.allBuildInputs(target.Sources, target.NamedSources)
}
func (target *BuildTarget) allBuildInputs(unnamed []BuildInput, named map[string][]BuildInput) []BuildInput {
ret := unnamed
keys := make([]string, 0, len(named))
for k := range named {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
ret = append(ret, named[k]...)
}
return ret
}
// AllLocalSourcePaths returns all the "local" sources of this rule, i.e. all sources that are
// actually sources in the repo, not other rules or system srcs etc.
func (target *BuildTarget) AllLocalSourcePaths() []string {
return target.allLocalSourcePaths(BuildInput.Paths)
}
func (target *BuildTarget) AllLocalSourceLocalPaths() []string {
return target.allLocalSourcePaths(BuildInput.LocalPaths)
}
func (target *BuildTarget) allLocalSourcePaths(full buildPathsFunc) []string {
srcs := target.AllSources()
ret := make([]string, 0, len(srcs))
for _, src := range srcs {
if file, ok := src.(FileLabel); ok {
ret = append(ret, full(file, nil)[0])
}
}
return ret
}
// HasSource returns true if this target has the given file as a source (named or not, or data).
func (target *BuildTarget) HasSource(source string) bool {
for _, src := range append(target.AllSources(), target.AllData()...) {
// Check for both the source matching and a prefix match indicating it's a directory with the file within.
if s := src.String(); s == source || strings.HasPrefix(source, s+"/") {
return true
}
}
return false
}
// HasAbsoluteSource returns true if this target has the given file as a source (or data).
// The input source includes the target's package name.
func (target *BuildTarget) HasAbsoluteSource(source string) bool {
return target.HasSource(strings.TrimPrefix(source, target.Label.PackageName+"/"))
}
// AllData returns all the sources of this rule.
func (target *BuildTarget) AllData() []BuildInput {
if target.namedData == nil {
return target.Data
}
return target.allBuildInputs(target.Data, target.namedData)
}
func (target *BuildTarget) NamedData() map[string][]BuildInput {
return target.namedData
}
// AllDataPaths returns the paths for all the data of this target.
func (target *BuildTarget) AllDataPaths(graph *BuildGraph) []string {
ret := make([]string, 0, len(target.Data))
for _, datum := range target.AllData() {
ret = append(ret, target.sourcePaths(graph, datum, BuildInput.Paths)...)
}
return ret
}
// AllTools returns all the tools for this rule in some canonical order.
func (target *BuildTarget) AllTools() []BuildInput {
if target.namedTools == nil {
return target.Tools
}
return target.allBuildInputs(target.Tools, target.namedTools)
}
// ToolNames returns an ordered list of tool names.
func (target *BuildTarget) ToolNames() []string {
ret := make([]string, 0, len(target.namedTools))
for name := range target.namedTools {
ret = append(ret, name)
}
sort.Strings(ret)
return ret
}
// NamedTools returns the tools with the given name.
func (target *BuildTarget) NamedTools(name string) []BuildInput {
return target.namedTools[name]
}
func (target *BuildTarget) AllNamedTools() map[string][]BuildInput {
return target.namedTools
}
// AddDependency adds a dependency to this target. It deduplicates against any existing deps.
func (target *BuildTarget) AddDependency(dep BuildLabel) {
target.AddMaybeExportedDependency(dep, false, false, false)
}
// AddMaybeExportedDependency adds a dependency to this target which may be exported. It deduplicates against any existing deps.
func (target *BuildTarget) AddMaybeExportedDependency(dep BuildLabel, exported, source, internal bool) {
if dep == target.Label {
log.Fatalf("Attempted to add %s as a dependency of itself.\n", dep)
}
info := target.dependencyInfo(dep)
if info == nil {
target.dependencies = append(target.dependencies, depInfo{declared: &dep, exported: exported, source: source, internal: internal})
} else {
info.exported = info.exported || exported
info.source = info.source && source
info.internal = info.internal && internal
info.data = false // It's not *only* data any more.
}
}
// IsTool returns true if the given build label is a tool used by this target.
func (target *BuildTarget) IsTool(tool BuildLabel) bool {
for _, t := range target.Tools {
if label, ok := t.Label(); ok && label == tool {
return true
}
}
for _, tools := range target.namedTools {
for _, t := range tools {
if label, ok := t.Label(); ok && label == tool {
return true
}
}
}
return false
}
// toolPath returns a path to this target when used as a tool.
func (target *BuildTarget) toolPath(abs bool, namedOutput string) string {
outToolPath := func(outputs ...string) string {
ret := make([]string, len(outputs))
for i, o := range outputs {
if abs {
ret[i] = path.Join(RepoRoot, target.OutDir(), o)
} else {
ret[i] = path.Join(target.Label.PackageName, o)
}
}
return strings.Join(ret, " ")
}
if namedOutput != "" {
if o, ok := target.EntryPoints[namedOutput]; ok {
return outToolPath(o)
}
if outs, ok := target.namedOutputs[namedOutput]; ok {
return outToolPath(outs...)
}
panic(fmt.Sprintf("%v has no named output or entry point %v", target.Label, namedOutput))
}
return outToolPath(target.Outputs()...)
}
// AddOutput adds a new output to the target if it's not already there.
func (target *BuildTarget) AddOutput(output string) {
target.outputs = target.insert(target.outputs, output)
}
// AddOptionalOutput adds a new optional output to the target if it's not already there.
func (target *BuildTarget) AddOptionalOutput(output string) {
target.OptionalOutputs = target.insert(target.OptionalOutputs, output)
}
// AddTestOutput adds a new test output to the target if it's not already there.
func (target *BuildTarget) AddTestOutput(output string) {
target.Test.Outputs = target.insert(target.Test.Outputs, output)
}
// AddNamedOutput adds a new output to the target under a named group.
// No attempt to deduplicate against unnamed outputs is currently made.
func (target *BuildTarget) AddNamedOutput(name, output string) {
if target.namedOutputs == nil {
target.namedOutputs = map[string][]string{name: target.insert(nil, output)}
return
}
target.namedOutputs[name] = target.insert(target.namedOutputs[name], output)
}
// insert adds a string into a slice if it's not already there. Sorted order is maintained.
func (target *BuildTarget) insert(sl []string, s string) []string {
if s == "" {
panic("Cannot add an empty string as an output of a target")
}
s = strings.TrimPrefix(s, "./")
for i, x := range sl {
if s == x {
// Already present.
return sl
} else if x > s {
// Insert in this location. Make an attempt to be efficient.
sl = append(sl, "")
copy(sl[i+1:], sl[i:])
sl[i] = s
return sl
}
}
return append(sl, s)
}
// AddLicence adds a licence to the target if it's not already there.
func (target *BuildTarget) AddLicence(licence string) {
licence = strings.TrimSpace(licence)
for _, l := range target.Licences {
if l == licence {
return
}
}
target.Licences = append(target.Licences, licence)
}
// AddHash adds a new acceptable hash to the target.
func (target *BuildTarget) AddHash(hash string) {
target.Hashes = append(target.Hashes, hash)
}
// AddRequire adds a new requirement to the target.
func (target *BuildTarget) AddRequire(require string) {
target.Requires = append(target.Requires, require)
// Requirements are also implicit labels
target.AddLabel(require)
}
// OutMode returns the mode to set outputs of a target to.
func (target *BuildTarget) OutMode() os.FileMode {
if target.IsBinary {
return 0555
}
return 0444
}
// TargetBuildMetadataFileName returns the target build metadata file name for this target.
func (target *BuildTarget) TargetBuildMetadataFileName() string {
return ".target_build_metadata_" + target.Label.Name
}
// StampFileName returns the stamp filename for this target.
func (target *BuildTarget) StampFileName() string {
return ".stamp_" + target.Label.Name
}
// NeedCoverage returns true if this target should output coverage during a test
// for a particular invocation.
func (target *BuildTarget) NeedCoverage(state *BuildState) bool {
if target.Test == nil {
return false
}
return state.NeedCoverage && !target.Test.NoOutput && !target.HasAnyLabel(state.Config.Test.DisableCoverage)
}
// Parent finds the parent of a build target, or nil if the target is parentless.
// Note that this is a fairly informal relationship; we identify it by labels with the convention of
// a leading _ and trailing hashtag on child rules, rather than storing pointers between them in the graph.
// The parent returned, if any, will be the ultimate ancestor of the target.
func (target *BuildTarget) Parent(graph *BuildGraph) *BuildTarget {
parent := target.Label.Parent()
if parent == target.Label {
return nil
}
return graph.Target(parent)
}
// HasParent returns true if the target has a parent rule that's not itself.
func (target *BuildTarget) HasParent() bool {
return target.Label.HasParent()
}
// ShouldShowProgress returns true if the target should display progress.
// This is provided as a function to satisfy the process package.
func (target *BuildTarget) ShouldShowProgress() bool {
return target.ShowProgress
}
// ProgressDescription returns a description of what the target is doing as it runs.
// This is provided as a function to satisfy the process package.
func (target *BuildTarget) ProgressDescription() string {
if target.State() >= Built && target.IsTest() {
return "testing"
}
return target.BuildingDescription
}
// ShouldExitOnError returns true if the subprocess should exit when an error occurs.
func (target *BuildTarget) ShouldExitOnError() bool {
return target.ExitOnError
}
// SetProgress sets the current progress of this target.
func (target *BuildTarget) SetProgress(progress float32) {
target.Progress = progress
}
// BuildCouldModifyTarget will return true when the action of building this target could change the target itself e.g.
// by adding new outputs
func (target *BuildTarget) BuildCouldModifyTarget() bool {
return target.PostBuildFunction != nil || len(target.OutputDirectories) > 0
}
// AddOutputDirectory adds an output directory to the target
func (target *BuildTarget) AddOutputDirectory(dir string) {
target.OutputDirectories = append(target.OutputDirectories, OutputDirectory(dir))
}
// GetFileContent returns the file content, expanding it if it needs to
func (target *BuildTarget) GetFileContent(state *BuildState) (string, error) {
return ReplaceSequences(state, target, target.FileContent)
}
// BuildTargets makes a slice of build targets sortable by their labels.
type BuildTargets []*BuildTarget
func (slice BuildTargets) Len() int {
return len(slice)
}
func (slice BuildTargets) Less(i, j int) bool {
return slice[i].Label.Less(slice[j].Label)
}
func (slice BuildTargets) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
| 1 | 10,205 | Nice! Good idea to move these out of the main struct. | thought-machine-please | go |
@@ -201,7 +201,10 @@ func CreateGitIgnore(targetDir string, ignores ...string) error {
if fileutil.FileExists(gitIgnoreFilePath) {
sigFound, err := fileutil.FgrepStringInFile(gitIgnoreFilePath, DdevFileSignature)
- util.CheckErr(err)
+ if err != nil {
+ return err
+ }
+
// If we sigFound the file and did not find the signature in .ddev/.gitignore, warn about it.
if !sigFound {
util.Warning("User-managed %s will not be managed/overwritten by ddev", gitIgnoreFilePath) | 1 | package ddevapp
import (
"fmt"
"path"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/fsouza/go-dockerclient"
"github.com/gosuri/uitable"
"errors"
"os"
"text/template"
"github.com/Masterminds/sprig"
"github.com/drud/ddev/pkg/dockerutil"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/output"
"github.com/drud/ddev/pkg/util"
gohomedir "github.com/mitchellh/go-homedir"
)
// GetApps returns an array of ddev applications.
func GetApps() []*DdevApp {
apps := make([]*DdevApp, 0)
labels := map[string]string{
"com.ddev.platform": "ddev",
"com.docker.compose.service": "web",
}
containers, err := dockerutil.FindContainersByLabels(labels)
if err == nil {
for _, siteContainer := range containers {
app := &DdevApp{}
approot, ok := siteContainer.Labels["com.ddev.approot"]
if !ok {
break
}
err = app.Init(approot)
// Artificially populate sitename and apptype based on labels
// if app.Init() failed.
if err != nil {
app.Name = siteContainer.Labels["com.ddev.site-name"]
app.Type = siteContainer.Labels["com.ddev.app-type"]
app.AppRoot = siteContainer.Labels["com.ddev.approot"]
}
apps = append(apps, app)
}
}
return apps
}
// CreateAppTable will create a new app table for describe and list output
func CreateAppTable() *uitable.Table {
table := uitable.New()
table.MaxColWidth = 140
table.Separator = " "
table.Wrap = true
table.AddRow("NAME", "TYPE", "LOCATION", "URL(s)", "STATUS")
return table
}
// RenderHomeRootedDir shortens a directory name to replace homedir with ~
func RenderHomeRootedDir(path string) string {
userDir, err := gohomedir.Dir()
util.CheckErr(err)
result := strings.Replace(path, userDir, "~", 1)
result = strings.Replace(result, "\\", "/", -1)
return result
}
// RenderAppRow will add an application row to an existing table for describe and list output.
func RenderAppRow(table *uitable.Table, row map[string]interface{}) {
status := fmt.Sprint(row["status"])
switch {
case strings.Contains(status, SiteStopped):
status = color.YellowString(status)
case strings.Contains(status, SiteNotFound):
status = color.RedString(status)
case strings.Contains(status, SiteDirMissing):
status = color.RedString(status)
case strings.Contains(status, SiteConfigMissing):
status = color.RedString(status)
default:
status = color.CyanString(status)
}
urls := row["httpurl"].(string)
if row["httpsurl"] != "" {
urls = urls + "\n" + row["httpsurl"].(string)
}
table.AddRow(
row["name"],
row["type"],
row["shortroot"],
urls,
status,
)
}
// Cleanup will remove ddev containers and volumes even if docker-compose.yml
// has been deleted.
func Cleanup(app *DdevApp) error {
client := dockerutil.GetDockerClient()
// Find all containers which match the current site name.
labels := map[string]string{
"com.ddev.site-name": app.GetName(),
}
containers, err := dockerutil.FindContainersByLabels(labels)
if err != nil {
return err
}
// First, try stopping the listed containers if they are running.
for i := range containers {
containerName := containers[i].Names[0][1:len(containers[i].Names[0])]
removeOpts := docker.RemoveContainerOptions{
ID: containers[i].ID,
RemoveVolumes: true,
Force: true,
}
output.UserOut.Printf("Removing container: %s", containerName)
if err = client.RemoveContainer(removeOpts); err != nil {
return fmt.Errorf("could not remove container %s: %v", containerName, err)
}
}
err = StopRouterIfNoContainers()
return err
}
// CheckForConf checks for a config.yaml at the cwd or parent dirs.
func CheckForConf(confPath string) (string, error) {
if fileutil.FileExists(confPath + "/.ddev/config.yaml") {
return confPath, nil
}
pathList := strings.Split(confPath, "/")
for range pathList {
confPath = filepath.Dir(confPath)
if fileutil.FileExists(confPath + "/.ddev/config.yaml") {
return confPath, nil
}
}
return "", errors.New("no .ddev/config.yaml file was found in this directory or any parent")
}
// ddevContainersRunning determines if any ddev-controlled containers are currently running.
func ddevContainersRunning() (bool, error) {
containers, err := dockerutil.GetDockerContainers(false)
if err != nil {
return false, err
}
for _, container := range containers {
if _, ok := container.Labels["com.ddev.platform"]; ok {
return true, nil
}
}
return false, nil
}
// getTemplateFuncMap will return a map of useful template functions.
func getTemplateFuncMap() map[string]interface{} {
// Use sprig's template function map as a base
m := sprig.FuncMap()
// Add helpful utilities on top of it
m["joinPath"] = path.Join
return m
}
// gitIgnoreTemplate will write a .gitignore file.
// This template expects string slice to be provided, with each string corresponding to
// a line in the resulting .gitignore.
const gitIgnoreTemplate = `{{.Signature}}: Automatically generated ddev .gitignore.
{{range .IgnoredItems}}
/{{.}}{{end}}
`
type ignoreTemplateContents struct {
Signature string
IgnoredItems []string
}
// CreateGitIgnore will create a .gitignore file in the target directory if one does not exist.
// Each value in ignores will be added as a new line to the .gitignore.
func CreateGitIgnore(targetDir string, ignores ...string) error {
gitIgnoreFilePath := filepath.Join(targetDir, ".gitignore")
if fileutil.FileExists(gitIgnoreFilePath) {
sigFound, err := fileutil.FgrepStringInFile(gitIgnoreFilePath, DdevFileSignature)
util.CheckErr(err)
// If we sigFound the file and did not find the signature in .ddev/.gitignore, warn about it.
if !sigFound {
util.Warning("User-managed %s will not be managed/overwritten by ddev", gitIgnoreFilePath)
return nil
}
// Otherwise, remove the existing file to prevent surprising template results
err = os.Remove(gitIgnoreFilePath)
if err != nil {
return err
}
}
tmpl, err := template.New("gitignore").Funcs(getTemplateFuncMap()).Parse(gitIgnoreTemplate)
if err != nil {
return err
}
file, err := os.OpenFile(gitIgnoreFilePath, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return err
}
defer util.CheckClose(file)
parms := ignoreTemplateContents{
Signature: DdevFileSignature,
IgnoredItems: ignores,
}
if err = tmpl.Execute(file, parms); err != nil {
return err
}
return nil
}
// isTar determines whether the object at the filepath is a .tar archive.
func isTar(filepath string) bool {
if strings.HasSuffix(filepath, ".tar") {
return true
}
if strings.HasSuffix(filepath, ".tar.gz") {
return true
}
if strings.HasSuffix(filepath, ".tgz") {
return true
}
return false
}
// isZip determines if the object at hte filepath is a .zip.
func isZip(filepath string) bool {
if strings.HasSuffix(filepath, ".zip") {
return true
}
return false
}
| 1 | 13,134 | Thanks for paying attention to other places this might happen. This one is particularly important; I probably never should have gotten in the habit of CheckErr(), since it does a log.Panic() explicitly, which looks like something else until you look closely. It's supposed to be used places where "can't happen" but Things Can Happen. | drud-ddev | go |
@@ -16,10 +16,13 @@ import java.util.Map;
* @see com.fsck.k9.mail.store.StoreConfig#getTransportUri()
*/
public class ServerSettings {
+
+ public enum Type { IMAP, SMTP, WebDAV, POP3 }
+
/**
- * Name of the store or transport type (e.g. "IMAP").
+ * Name of the store or transport type (e.g. IMAP).
*/
- public final String type;
+ public final Type type;
/**
* The host name of the server. | 1 | package com.fsck.k9.mail;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* This is an abstraction to get rid of the store- and transport-specific URIs.
*
* <p>
* Right now it's only used for settings import/export. But the goal is to get rid of
* store/transport URIs altogether.
* </p>
*
* @see com.fsck.k9.mail.store.StoreConfig#getStoreUri()
* @see com.fsck.k9.mail.store.StoreConfig#getTransportUri()
*/
public class ServerSettings {
/**
* Name of the store or transport type (e.g. "IMAP").
*/
public final String type;
/**
* The host name of the server.
*
* {@code null} if not applicable for the store or transport.
*/
public final String host;
/**
* The port number of the server.
*
* {@code -1} if not applicable for the store or transport.
*/
public final int port;
/**
* The type of connection security to be used when connecting to the server.
*
* {@link ConnectionSecurity#NONE} if not applicable for the store or transport.
*/
public final ConnectionSecurity connectionSecurity;
/**
* The authentication method to use when connecting to the server.
*
* {@code null} if not applicable for the store or transport.
*/
public final AuthType authenticationType;
/**
* The username part of the credentials needed to authenticate to the server.
*
* {@code null} if not applicable for the store or transport.
*/
public final String username;
/**
* The password part of the credentials needed to authenticate to the server.
*
* {@code null} if not applicable for the store or transport.
*/
public final String password;
/**
* The alias to retrieve a client certificate using Android 4.0 KeyChain API
* for TLS client certificate authentication with the server.
*
* {@code null} if not applicable for the store or transport.
*/
public final String clientCertificateAlias;
/**
* Store- or transport-specific settings as key/value pair.
*
* {@code null} if not applicable for the store or transport.
*/
private final Map<String, String> extra;
/**
* Creates a new {@code ServerSettings} object.
*
* @param type
* see {@link ServerSettings#type}
* @param host
* see {@link ServerSettings#host}
* @param port
* see {@link ServerSettings#port}
* @param connectionSecurity
* see {@link ServerSettings#connectionSecurity}
* @param authenticationType
* see {@link ServerSettings#authenticationType}
* @param username
* see {@link ServerSettings#username}
* @param password
* see {@link ServerSettings#password}
* @param clientCertificateAlias
* see {@link ServerSettings#clientCertificateAlias}
*/
public ServerSettings(String type, String host, int port,
ConnectionSecurity connectionSecurity, AuthType authenticationType, String username,
String password, String clientCertificateAlias) {
this.type = type;
this.host = host;
this.port = port;
this.connectionSecurity = connectionSecurity;
this.authenticationType = authenticationType;
this.username = username;
this.password = password;
this.clientCertificateAlias = clientCertificateAlias;
this.extra = null;
}
/**
* Creates a new {@code ServerSettings} object.
*
* @param type
* see {@link ServerSettings#type}
* @param host
* see {@link ServerSettings#host}
* @param port
* see {@link ServerSettings#port}
* @param connectionSecurity
* see {@link ServerSettings#connectionSecurity}
* @param authenticationType
* see {@link ServerSettings#authenticationType}
* @param username
* see {@link ServerSettings#username}
* @param password
* see {@link ServerSettings#password}
* @param clientCertificateAlias
* see {@link ServerSettings#clientCertificateAlias}
* @param extra
* see {@link ServerSettings#extra}
*/
public ServerSettings(String type, String host, int port,
ConnectionSecurity connectionSecurity, AuthType authenticationType, String username,
String password, String clientCertificateAlias, Map<String, String> extra) {
this.type = type;
this.host = host;
this.port = port;
this.connectionSecurity = connectionSecurity;
this.authenticationType = authenticationType;
this.username = username;
this.password = password;
this.clientCertificateAlias = clientCertificateAlias;
this.extra = (extra != null) ?
Collections.unmodifiableMap(new HashMap<String, String>(extra)) : null;
}
/**
* Creates an "empty" {@code ServerSettings} object.
*
* Everything but {@link ServerSettings#type} is unused.
*
* @param type
* see {@link ServerSettings#type}
*/
public ServerSettings(String type) {
this.type = type;
host = null;
port = -1;
connectionSecurity = ConnectionSecurity.NONE;
authenticationType = null;
username = null;
password = null;
clientCertificateAlias = null;
extra = null;
}
/**
* Returns store- or transport-specific settings as key/value pair.
*
* @return additional set of settings as key/value pair.
*/
public Map<String, String> getExtra() {
return extra;
}
protected void putIfNotNull(Map<String, String> map, String key, String value) {
if (value != null) {
map.put(key, value);
}
}
public ServerSettings newPassword(String newPassword) {
return new ServerSettings(type, host, port, connectionSecurity, authenticationType,
username, newPassword, clientCertificateAlias);
}
public ServerSettings newClientCertificateAlias(String newAlias) {
return new ServerSettings(type, host, port, connectionSecurity, AuthType.EXTERNAL,
username, password, newAlias);
}
} | 1 | 12,971 | Converting this to an enum makes it obvious that I combined things that don't really belong together. It would probably be better to create two enums `StoreType` and `TransportType` (in more appropriate locations). That also makes it necessary to have (at least) two `ServerSettings` classes. `IncomingServerSettings` and `OutgoingServerSettings`. Also, the naming is inconsistent. Maybe it would be better to make the string that is used for import/export explicit, e.g. WEBDAV("WebDAV"). | k9mail-k-9 | java |
@@ -1,7 +1,14 @@
-/*global axe */
-
+/* global axe */
+/**
+ * Converts space delimited token list to an Array
+ * @method tokenList
+ * @memberof axe.commons.utils
+ * @instance
+ * @param {String} str
+ * @return {Array}
+ */
axe.utils.tokenList = function (str) {
'use strict';
return str.trim().replace(/\s{2,}/g, ' ').split(' ');
-};
+}; | 1 | /*global axe */
axe.utils.tokenList = function (str) {
'use strict';
return str.trim().replace(/\s{2,}/g, ' ').split(' ');
}; | 1 | 11,659 | It's out of scope for this PR, but I don't find this utility's name to be particularly intuitive. It speaks to nothing of what it does. Does it create a token list? Process one? Get one? `tokenListToArray` would be nice. | dequelabs-axe-core | js |
@@ -3,7 +3,9 @@ let nodeName = node.nodeName.toUpperCase();
let type = (node.getAttribute('type') || '').toLowerCase();
let label = node.getAttribute('value');
-this.data(label);
+if (label) {
+ this.data('has-label');
+}
if (nodeName === 'INPUT' && ['submit', 'reset'].includes(type)) {
return label === null; | 1 | // Check for 'default' names, which are given to reset and submit buttons
let nodeName = node.nodeName.toUpperCase();
let type = (node.getAttribute('type') || '').toLowerCase();
let label = node.getAttribute('value');
this.data(label);
if (nodeName === 'INPUT' && ['submit', 'reset'].includes(type)) {
return label === null;
}
return false;
| 1 | 15,144 | The message for this check used the existence of a label to determine the output, which doesn't work with the current schema. So I updated it since the data only needed to know a label was present and not what it was. | dequelabs-axe-core | js |
@@ -267,6 +267,14 @@ func (a *WebAPI) SyncApplication(ctx context.Context, req *webservice.SyncApplic
return nil, err
}
+ claims, err := rpcauth.ExtractClaims(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if app.ProjectId != claims.Role.ProjectId {
+ return nil, status.Error(codes.PermissionDenied, "application cannot be synced")
+ }
+
cmd := model.Command{
Id: uuid.New().String(),
PipedId: app.PipedId, | 1 | // Copyright 2020 The PipeCD 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 api
import (
"context"
"errors"
"github.com/google/uuid"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pipe-cd/pipe/pkg/app/api/applicationlivestatestore"
"github.com/pipe-cd/pipe/pkg/app/api/service/webservice"
"github.com/pipe-cd/pipe/pkg/app/api/stagelogstore"
"github.com/pipe-cd/pipe/pkg/datastore"
"github.com/pipe-cd/pipe/pkg/model"
"github.com/pipe-cd/pipe/pkg/rpc/rpcauth"
)
// PipedAPI implements the behaviors for the gRPC definitions of WebAPI.
type WebAPI struct {
applicationStore datastore.ApplicationStore
environmentStore datastore.EnvironmentStore
deploymentStore datastore.DeploymentStore
pipedStore datastore.PipedStore
commandStore datastore.CommandStore
stageLogStore stagelogstore.Store
applicationLiveStateStore applicationlivestatestore.Store
logger *zap.Logger
}
// NewWebAPI creates a new WebAPI instance.
func NewWebAPI(ds datastore.DataStore, sls stagelogstore.Store, alss applicationlivestatestore.Store, logger *zap.Logger) *WebAPI {
a := &WebAPI{
applicationStore: datastore.NewApplicationStore(ds),
environmentStore: datastore.NewEnvironmentStore(ds),
deploymentStore: datastore.NewDeploymentStore(ds),
pipedStore: datastore.NewPipedStore(ds),
commandStore: datastore.NewCommandStore(ds),
stageLogStore: sls,
applicationLiveStateStore: alss,
logger: logger.Named("web-api"),
}
return a
}
// Register registers all handling of this service into the specified gRPC server.
func (a *WebAPI) Register(server *grpc.Server) {
webservice.RegisterWebServiceServer(server, a)
}
func (a *WebAPI) AddEnvironment(ctx context.Context, req *webservice.AddEnvironmentRequest) (*webservice.AddEnvironmentResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
return nil, err
}
env := model.Environment{
Id: uuid.New().String(),
Name: req.Name,
Desc: req.Desc,
ProjectId: claims.Role.ProjectId,
}
err = a.environmentStore.AddEnvironment(ctx, &env)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "environment already exists")
}
if err != nil {
a.logger.Error("failed to create environment", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to create environment")
}
return &webservice.AddEnvironmentResponse{}, nil
}
func (a *WebAPI) UpdateEnvironmentDesc(ctx context.Context, req *webservice.UpdateEnvironmentDescRequest) (*webservice.UpdateEnvironmentDescResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (a *WebAPI) ListEnvironments(ctx context.Context, req *webservice.ListEnvironmentsRequest) (*webservice.ListEnvironmentsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: "==",
Value: claims.Role.ProjectId,
},
},
}
envs, err := a.environmentStore.ListEnvironments(ctx, opts)
if err != nil {
a.logger.Error("failed to get environments", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get environments")
}
return &webservice.ListEnvironmentsResponse{
Environments: envs,
}, nil
}
func (a *WebAPI) RegisterPiped(ctx context.Context, req *webservice.RegisterPipedRequest) (*webservice.RegisterPipedResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
return nil, err
}
key, keyHash, err := model.GeneratePipedKey()
if err != nil {
a.logger.Error("failed to generate piped key", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to generate the piped key")
}
id := uuid.New().String()
piped := model.Piped{
Id: id,
Desc: req.Desc,
KeyHash: keyHash,
ProjectId: claims.Role.ProjectId,
}
err = a.pipedStore.AddPiped(ctx, &piped)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "piped already exists")
}
if err != nil {
a.logger.Error("failed to register piped", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to register piped")
}
return &webservice.RegisterPipedResponse{
Id: id,
Key: key,
}, nil
}
func (a *WebAPI) DisablePiped(ctx context.Context, req *webservice.DisablePipedRequest) (*webservice.DisablePipedResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (a *WebAPI) ListPipeds(ctx context.Context, req *webservice.ListPipedsRequest) (*webservice.ListPipedsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: "==",
Value: claims.Role.ProjectId,
},
{
Field: "Disabled",
Operator: "==",
Value: false,
},
},
}
pipeds, err := a.pipedStore.ListPipeds(ctx, opts)
if err != nil {
a.logger.Error("failed to get pipeds", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get pipeds")
}
// Returning a response that does not contain sensitive data like KeyHash is more safer.
webPipeds := make([]*webservice.Piped, len(pipeds))
for i := range pipeds {
webPipeds[i] = webservice.MakePiped(pipeds[i])
if req.WithStatus {
// TODO: While reducing the number of query and get ping connection status from piped_stats
webPipeds[i].Status = webservice.PipedConnectionStatus_PIPED_CONNECTION_ONLINE
}
}
return &webservice.ListPipedsResponse{
Pipeds: webPipeds,
}, nil
}
func (a *WebAPI) GetPiped(ctx context.Context, req *webservice.GetPipedRequest) (*webservice.GetPipedResponse, error) {
piped, err := a.pipedStore.GetPiped(ctx, req.PipedId)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "piped is not found")
}
if err != nil {
a.logger.Error("failed to get piped", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get piped")
}
return &webservice.GetPipedResponse{
Piped: webservice.MakePiped(piped),
}, nil
}
func (a *WebAPI) AddApplication(ctx context.Context, req *webservice.AddApplicationRequest) (*webservice.AddApplicationResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
return nil, err
}
app := model.Application{
Id: uuid.New().String(),
Name: req.Name,
EnvId: req.EnvId,
PipedId: req.PipedId,
ProjectId: claims.Role.ProjectId,
GitPath: req.GitPath,
Kind: req.Kind,
CloudProvider: req.CloudProvider,
}
err = a.applicationStore.AddApplication(ctx, &app)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "application already exists")
}
if err != nil {
a.logger.Error("failed to create application", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to create application")
}
return &webservice.AddApplicationResponse{}, nil
}
func (a *WebAPI) DisableApplication(ctx context.Context, req *webservice.DisableApplicationRequest) (*webservice.DisableApplicationResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (a *WebAPI) ListApplications(ctx context.Context, req *webservice.ListApplicationsRequest) (*webservice.ListApplicationsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: "==",
Value: claims.Role.ProjectId,
},
},
}
apps, err := a.applicationStore.ListApplications(ctx, opts)
if err != nil {
a.logger.Error("failed to get applications", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get applications")
}
return &webservice.ListApplicationsResponse{
Applications: apps,
}, nil
}
func (a *WebAPI) SyncApplication(ctx context.Context, req *webservice.SyncApplicationRequest) (*webservice.SyncApplicationResponse, error) {
app, err := a.getApplication(ctx, req.ApplicationId)
if err != nil {
return nil, err
}
cmd := model.Command{
Id: uuid.New().String(),
PipedId: app.PipedId,
ApplicationId: app.Id,
Type: model.Command_SYNC_APPLICATION,
Commander: "anonymous", // TODO: Getting value from login user.
SyncApplication: &model.Command_SyncApplication{
ApplicationId: req.ApplicationId,
},
}
if err := a.addCommand(ctx, &cmd); err != nil {
return nil, err
}
return &webservice.SyncApplicationResponse{}, nil
}
func (a *WebAPI) addCommand(ctx context.Context, cmd *model.Command) error {
if err := a.commandStore.AddCommand(ctx, cmd); err != nil {
a.logger.Error("failed to create command", zap.Error(err))
return status.Error(codes.Internal, "failed to create command")
}
return nil
}
func (a *WebAPI) GetApplication(ctx context.Context, req *webservice.GetApplicationRequest) (*webservice.GetApplicationResponse, error) {
app, err := a.getApplication(ctx, req.ApplicationId)
if err != nil {
return nil, err
}
return &webservice.GetApplicationResponse{
Application: app,
}, nil
}
func (a *WebAPI) getApplication(ctx context.Context, id string) (*model.Application, error) {
app, err := a.applicationStore.GetApplication(ctx, id)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "application is not found")
}
if err != nil {
a.logger.Error("failed to get application", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get application")
}
return app, nil
}
func (a *WebAPI) ListDeployments(ctx context.Context, req *webservice.ListDeploymentsRequest) (*webservice.ListDeploymentsResponse, error) {
// TODO: Support pagination and filtering with the search condition in ListDeployments
opts := datastore.ListOptions{}
deployments, err := a.deploymentStore.ListDeployments(ctx, opts)
if err != nil {
a.logger.Error("failed to get deployments", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get deployments")
}
return &webservice.ListDeploymentsResponse{
Deployments: deployments,
}, nil
}
func (a *WebAPI) GetDeployment(ctx context.Context, req *webservice.GetDeploymentRequest) (*webservice.GetDeploymentResponse, error) {
deployment, err := a.getDeployment(ctx, req.DeploymentId)
if err != nil {
return nil, err
}
return &webservice.GetDeploymentResponse{
Deployment: deployment,
}, nil
}
func (a *WebAPI) getDeployment(ctx context.Context, id string) (*model.Deployment, error) {
deployment, err := a.deploymentStore.GetDeployment(ctx, id)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "deployment is not found")
}
if err != nil {
a.logger.Error("failed to get deployment", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get deployment")
}
return deployment, nil
}
func (a *WebAPI) GetStageLog(ctx context.Context, req *webservice.GetStageLogRequest) (*webservice.GetStageLogResponse, error) {
blocks, completed, err := a.stageLogStore.FetchLogs(ctx, req.DeploymentId, req.StageId, req.RetriedCount, req.OffsetIndex)
if errors.Is(err, stagelogstore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "stage log not found")
}
if err != nil {
a.logger.Error("failed to get stage logs", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get stage logs")
}
return &webservice.GetStageLogResponse{
Blocks: blocks,
Completed: completed,
}, nil
}
func (a *WebAPI) CancelDeployment(ctx context.Context, req *webservice.CancelDeploymentRequest) (*webservice.CancelDeploymentResponse, error) {
deployment, err := a.getDeployment(ctx, req.DeploymentId)
if err != nil {
return nil, err
}
if model.IsCompletedDeployment(deployment.Status) {
return nil, status.Errorf(codes.FailedPrecondition, "could not cancel the deployment because it was already completed")
}
cmd := model.Command{
Id: uuid.New().String(),
PipedId: deployment.PipedId,
ApplicationId: deployment.ApplicationId,
DeploymentId: req.DeploymentId,
Type: model.Command_CANCEL_DEPLOYMENT,
Commander: "anonymous",
CancelDeployment: &model.Command_CancelDeployment{
DeploymentId: req.DeploymentId,
WithoutRollback: req.WithoutRollback,
},
}
if err := a.addCommand(ctx, &cmd); err != nil {
return nil, err
}
return &webservice.CancelDeploymentResponse{}, nil
}
func (a *WebAPI) ApproveStage(ctx context.Context, req *webservice.ApproveStageRequest) (*webservice.ApproveStageResponse, error) {
deployment, err := a.getDeployment(ctx, req.DeploymentId)
if err != nil {
return nil, err
}
stage, ok := deployment.StageStatusMap()[req.StageId]
if !ok {
return nil, status.Error(codes.FailedPrecondition, "stage was not found in the deployment")
}
if model.IsCompletedStage(stage) {
return nil, status.Errorf(codes.FailedPrecondition, "could not approve the stage because it was already completed")
}
cmd := model.Command{
Id: uuid.New().String(),
PipedId: deployment.PipedId,
ApplicationId: deployment.ApplicationId,
DeploymentId: req.DeploymentId,
StageId: req.StageId,
Type: model.Command_APPROVE_STAGE,
Commander: "anonymous",
ApproveStage: &model.Command_ApproveStage{
DeploymentId: req.DeploymentId,
StageId: req.StageId,
},
}
if err := a.addCommand(ctx, &cmd); err != nil {
return nil, err
}
return &webservice.ApproveStageResponse{}, nil
}
func (a *WebAPI) GetApplicationLiveState(ctx context.Context, req *webservice.GetApplicationLiveStateRequest) (*webservice.GetApplicationLiveStateResponse, error) {
snapshot, err := a.applicationLiveStateStore.GetStateSnapshot(ctx, req.ApplicationId)
if err != nil {
a.logger.Error("failed to get application live state", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to get application live state")
}
return &webservice.GetApplicationLiveStateResponse{
Snapshot: snapshot,
}, nil
}
func (a *WebAPI) GetProject(ctx context.Context, req *webservice.GetProjectRequest) (*webservice.GetProjectResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (a *WebAPI) GetMe(ctx context.Context, req *webservice.GetMeRequest) (*webservice.GetMeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
| 1 | 7,491 | nit: "The current project does not have requested application" | pipe-cd-pipe | go |
@@ -14,6 +14,7 @@ use Ergonode\SharedKernel\Domain\AbstractCode;
class AttributeCode extends AbstractCode
{
public const PATTERN = '/^([a-zA-Z0-9_]+)$/';
+ public const FORBIDDEN = ['id'];
public function __construct(string $value)
{ | 1 | <?php
/**
* Copyright © Bold Brand Commerce Sp. z o.o. All rights reserved.
* See LICENSE.txt for license details.
*/
declare(strict_types=1);
namespace Ergonode\Attribute\Domain\ValueObject;
use Ergonode\SharedKernel\Domain\AbstractCode;
class AttributeCode extends AbstractCode
{
public const PATTERN = '/^([a-zA-Z0-9_]+)$/';
public function __construct(string $value)
{
parent::__construct(strtolower($value));
}
public static function isValid(string $value): bool
{
$value = strtolower($value);
return parent::isValid($value)
&& preg_match(self::PATTERN, $value);
}
}
| 1 | 9,654 | Extend Unit test for this class | ergonode-backend | php |
@@ -62,6 +62,18 @@ namespace Datadog.Trace.Configuration
/// </summary>
public const string AppSecRules = "DD_APPSEC_RULES";
+ /// <summary>
+ /// Configuration key indicating the optional name of the custom header to take into account for the ip address.
+ /// Default is value is null (do not override).
+ /// </summary>
+ public const string AppSecCustomIpHeader = "DD_APPSEC_IPHEADER";
+
+ /// <summary>
+ /// Configuration key indicating the optional name of the custom header to take into account for the ip address.
+ /// Default is value is null (do not override).
+ /// </summary>
+ public const string AppSecExtraHeaders = "DD_APPSEC_EXTRA_HEADERS";
+
/// <summary>
/// Configuration key for enabling or disabling the Tracer's debug mode.
/// Default is value is false (disabled). | 1 | // <copyright file="ConfigurationKeys.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
namespace Datadog.Trace.Configuration
{
/// <summary>
/// String constants for standard Datadog configuration keys.
/// </summary>
public static class ConfigurationKeys
{
/// <summary>
/// Configuration key for the path to the configuration file.
/// Can only be set with an environment variable
/// or in the <c>app.config</c>/<c>web.config</c> file.
/// </summary>
public const string ConfigurationFileName = "DD_TRACE_CONFIG_FILE";
/// <summary>
/// Configuration key for the application's environment. Sets the "env" tag on every <see cref="Span"/>.
/// </summary>
/// <seealso cref="TracerSettings.Environment"/>
public const string Environment = "DD_ENV";
/// <summary>
/// Configuration key for the application's default service name.
/// Used as the service name for top-level spans,
/// and used to determine service name of some child spans.
/// </summary>
/// <seealso cref="TracerSettings.ServiceName"/>
public const string ServiceName = "DD_SERVICE";
/// <summary>
/// Configuration key for the application's version. Sets the "version" tag on every <see cref="Span"/>.
/// </summary>
/// <seealso cref="TracerSettings.ServiceVersion"/>
public const string ServiceVersion = "DD_VERSION";
/// <summary>
/// Configuration key for enabling or disabling the Tracer.
/// Default is value is true (enabled).
/// </summary>
/// <seealso cref="TracerSettings.TraceEnabled"/>
public const string TraceEnabled = "DD_TRACE_ENABLED";
/// <summary>
/// Configuration key for enabling or disabling the AppSec.
/// Default is value is false (disabled).
/// </summary>
public const string AppSecEnabled = "DD_APPSEC_ENABLED";
/// <summary>
/// Configuration key for enabling or disabling blocking in AppSec.
/// Default is value is false (disabled).
/// </summary>
public const string AppSecBlockingEnabled = "DD_APPSEC_BLOCKING_ENABLED";
/// <summary>
/// Override the default rules file provided. Must be a path to a valid JSON rules file.
/// Default is value is null (do not override).
/// </summary>
public const string AppSecRules = "DD_APPSEC_RULES";
/// <summary>
/// Configuration key for enabling or disabling the Tracer's debug mode.
/// Default is value is false (disabled).
/// </summary>
/// <seealso cref="TracerSettings.DebugEnabled"/>
public const string DebugEnabled = "DD_TRACE_DEBUG";
/// <summary>
/// Configuration key for a list of integrations to disable. All other integrations remain enabled.
/// Default is empty (all integrations are enabled).
/// Supports multiple values separated with semi-colons.
/// </summary>
/// <seealso cref="TracerSettings.DisabledIntegrationNames"/>
public const string DisabledIntegrations = "DD_DISABLED_INTEGRATIONS";
/// <summary>
/// Configuration key for a list of AdoNet types that will be excluded from automatic instrumentation.
/// Default is empty (all AdoNet types are included in automatic instrumentation).
/// Supports multiple values separated with semi-colons.
/// </summary>
/// <seealso cref="TracerSettings.AdoNetExcludedTypes"/>
public const string AdoNetExcludedTypes = "DD_TRACE_ADONET_EXCLUDED_TYPES";
/// <summary>
/// Configuration key for the Agent host where the Tracer can send traces.
/// Overridden by <see cref="AgentUri"/> if present.
/// Default value is "localhost".
/// </summary>
/// <seealso cref="TracerSettings.AgentUri"/>
public const string AgentHost = "DD_AGENT_HOST";
/// <summary>
/// Configuration key for the Agent port where the Tracer can send traces.
/// Default value is 8126.
/// </summary>
/// <seealso cref="TracerSettings.AgentUri"/>
public const string AgentPort = "DD_TRACE_AGENT_PORT";
/// <summary>
/// Configuration key for the named pipe where the Tracer can send traces.
/// Default value is <c>null</c>.
/// </summary>
/// <seealso cref="TracerSettings.TracesPipeName"/>
public const string TracesPipeName = "DD_TRACE_PIPE_NAME";
/// <summary>
/// Configuration key for setting the timeout in milliseconds for named pipes communication.
/// Default value is <c>0</c>.
/// </summary>
/// <seealso cref="TracerSettings.TracesPipeTimeoutMs"/>
public const string TracesPipeTimeoutMs = "DD_TRACE_PIPE_TIMEOUT_MS";
/// <summary>
/// Configuration key for the named pipe that DogStatsD binds to.
/// Default value is <c>null</c>.
/// </summary>
/// <seealso cref="TracerSettings.MetricsPipeName"/>
public const string MetricsPipeName = "DD_DOGSTATSD_PIPE_NAME";
/// <summary>
/// Sibling setting for <see cref="AgentPort"/>.
/// Used to force a specific port binding for the Trace Agent.
/// Default value is 8126.
/// </summary>
/// <seealso cref="TracerSettings.AgentUri"/>
public const string TraceAgentPortKey = "DD_APM_RECEIVER_PORT";
/// <summary>
/// Configuration key for the Agent URL where the Tracer can send traces.
/// Overrides values in <see cref="AgentHost"/> and <see cref="AgentPort"/> if present.
/// Default value is "http://localhost:8126".
/// </summary>
/// <seealso cref="TracerSettings.AgentUri"/>
public const string AgentUri = "DD_TRACE_AGENT_URL";
/// <summary>
/// Configuration key for enabling or disabling default Analytics.
/// </summary>
/// <seealso cref="TracerSettings.AnalyticsEnabled"/>
public const string GlobalAnalyticsEnabled = "DD_TRACE_ANALYTICS_ENABLED";
/// <summary>
/// Configuration key for a list of tags to be applied globally to spans.
/// </summary>
/// <seealso cref="TracerSettings.GlobalTags"/>
public const string GlobalTags = "DD_TAGS";
/// <summary>
/// Configuration key for a map of header keys to tag names.
/// Automatically apply header values as tags on traces.
/// </summary>
/// <seealso cref="TracerSettings.HeaderTags"/>
public const string HeaderTags = "DD_TRACE_HEADER_TAGS";
/// <summary>
/// Configuration key for a map of services to rename.
/// </summary>
/// <seealso cref="TracerSettings.ServiceNameMappings"/>
public const string ServiceNameMappings = "DD_TRACE_SERVICE_MAPPING";
/// <summary>
/// Configuration key for setting the size in bytes of the trace buffer
/// </summary>
public const string BufferSize = "DD_TRACE_BUFFER_SIZE";
/// <summary>
/// Configuration key for setting the batch interval in milliseconds for the serialization queue
/// </summary>
public const string SerializationBatchInterval = "DD_TRACE_BATCH_INTERVAL";
/// <summary>
/// Configuration key for enabling or disabling the automatic injection
/// of correlation identifiers into the logging context.
/// </summary>
/// <seealso cref="TracerSettings.LogsInjectionEnabled"/>
public const string LogsInjectionEnabled = "DD_LOGS_INJECTION";
/// <summary>
/// Configuration key for setting the number of traces allowed
/// to be submitted per second.
/// </summary>
/// <seealso cref="TracerSettings.MaxTracesSubmittedPerSecond"/>
public const string MaxTracesSubmittedPerSecond = "DD_MAX_TRACES_PER_SECOND";
/// <summary>
/// Configuration key for enabling or disabling the diagnostic log at startup
/// </summary>
/// <seealso cref="TracerSettings.StartupDiagnosticLogEnabled"/>
public const string StartupDiagnosticLogEnabled = "DD_TRACE_STARTUP_LOGS";
/// <summary>
/// Configuration key for setting custom sampling rules based on regular expressions.
/// Semi-colon separated list of sampling rules.
/// The rule is matched in order of specification. The first match in a list is used.
///
/// Per entry:
/// The item "sample_rate" is required in decimal format.
/// The item "service" is optional in regular expression format, to match on service name.
/// The item "name" is optional in regular expression format, to match on operation name.
///
/// To give a rate of 50% to any traces in a service starting with the text "cart":
/// '[{"sample_rate":0.5, "service":"cart.*"}]'
///
/// To give a rate of 20% to any traces which have an operation name of "http.request":
/// '[{"sample_rate":0.2, "name":"http.request"}]'
///
/// To give a rate of 100% to any traces within a service named "background" and with an operation name of "sql.query":
/// '[{"sample_rate":1.0, "service":"background", "name":"sql.query"}]
///
/// To give a rate of 10% to all traces
/// '[{"sample_rate":0.1}]'
///
/// To configure multiple rules, separate by semi-colon and order from most specific to least specific:
/// '[{"sample_rate":0.5, "service":"cart.*"}, {"sample_rate":0.2, "name":"http.request"}, {"sample_rate":1.0, "service":"background", "name":"sql.query"}, {"sample_rate":0.1}]'
///
/// If no rules are specified, or none match, default internal sampling logic will be used.
/// </summary>
/// <seealso cref="TracerSettings.CustomSamplingRules"/>
public const string CustomSamplingRules = "DD_TRACE_SAMPLING_RULES";
/// <summary>
/// Configuration key for setting the global rate for the sampler.
/// </summary>
public const string GlobalSamplingRate = "DD_TRACE_SAMPLE_RATE";
/// <summary>
/// Configuration key for the DogStatsd port where the Tracer can send metrics.
/// Default value is 8125.
/// </summary>
public const string DogStatsdPort = "DD_DOGSTATSD_PORT";
/// <summary>
/// Configuration key for enabling or disabling internal metrics sent to DogStatsD.
/// Default value is <c>false</c> (disabled).
/// </summary>
public const string TracerMetricsEnabled = "DD_TRACE_METRICS_ENABLED";
/// <summary>
/// Configuration key for enabling or disabling runtime metrics sent to DogStatsD.
/// Default value is <c>false</c> (disabled).
/// </summary>
public const string RuntimeMetricsEnabled = "DD_RUNTIME_METRICS_ENABLED";
/// <summary>
/// Configuration key for setting the approximate maximum size,
/// in bytes, for Tracer log files.
/// Default value is 10 MB.
/// </summary>
public const string MaxLogFileSize = "DD_MAX_LOGFILE_SIZE";
/// <summary>
/// Configuration key for setting the number of seconds between,
/// identical log messages, for Tracer log files.
/// Default value is 60s. Setting to 0 disables rate limiting.
/// </summary>
public const string LogRateLimit = "DD_TRACE_LOGGING_RATE";
/// <summary>
/// Configuration key for setting the path to the .NET Tracer native log file.
/// This also determines the output folder of the .NET Tracer managed log files.
/// Overridden by <see cref="LogDirectory"/> if present.
/// </summary>
public const string ProfilerLogPath = "DD_TRACE_LOG_PATH";
/// <summary>
/// Configuration key for setting the directory of the .NET Tracer logs.
/// Overrides the value in <see cref="ProfilerLogPath"/> if present.
/// Default value is "%ProgramData%"\Datadog .NET Tracer\logs\" on Windows
/// or "/var/log/datadog/dotnet/" on Linux.
/// </summary>
public const string LogDirectory = "DD_TRACE_LOG_DIRECTORY";
/// <summary>
/// Configuration key for when a standalone instance of the Trace Agent needs to be started.
/// </summary>
public const string TraceAgentPath = "DD_TRACE_AGENT_PATH";
/// <summary>
/// Configuration key for arguments to pass to the Trace Agent process.
/// </summary>
public const string TraceAgentArgs = "DD_TRACE_AGENT_ARGS";
/// <summary>
/// Configuration key for when a standalone instance of DogStatsD needs to be started.
/// </summary>
public const string DogStatsDPath = "DD_DOGSTATSD_PATH";
/// <summary>
/// Configuration key for arguments to pass to the DogStatsD process.
/// </summary>
public const string DogStatsDArgs = "DD_DOGSTATSD_ARGS";
/// <summary>
/// Configuration key for enabling or disabling the use of System.Diagnostics.DiagnosticSource.
/// Default value is <c>true</c> (enabled).
/// </summary>
public const string DiagnosticSourceEnabled = "DD_DIAGNOSTIC_SOURCE_ENABLED";
/// <summary>
/// Configuration key for setting the API key, used by the Agent.
/// This key is here for troubleshooting purposes.
/// </summary>
public const string ApiKey = "DD_API_KEY";
/// <summary>
/// Configuration key for overriding the transport to use for communicating with the trace agent.
/// Default value is <c>null</c>.
/// Override options available: <c>datadog-tcp</c>, <c>datadog-named-pipes</c>
/// </summary>
public const string TracesTransport = "DD_TRACE_TRANSPORT";
/// <summary>
/// Configuration key for overriding which URLs are skipped by the tracer.
/// </summary>
/// <seealso cref="TracerSettings.HttpClientExcludedUrlSubstrings"/>
public const string HttpClientExcludedUrlSubstrings = "DD_TRACE_HTTP_CLIENT_EXCLUDED_URL_SUBSTRINGS";
/// <summary>
/// Configuration key for the application's server http statuses to set spans as errors by.
/// </summary>
/// <seealso cref="TracerSettings.HttpServerErrorStatusCodes"/>
public const string HttpServerErrorStatusCodes = "DD_HTTP_SERVER_ERROR_STATUSES";
/// <summary>
/// Configuration key for the application's client http statuses to set spans as errors by.
/// </summary>
/// <seealso cref="TracerSettings.HttpClientErrorStatusCodes"/>
public const string HttpClientErrorStatusCodes = "DD_HTTP_CLIENT_ERROR_STATUSES";
/// <summary>
/// Configuration key to enable sending partial traces to the agent
/// </summary>
/// <seealso cref="TracerSettings.PartialFlushEnabled"/>
public const string PartialFlushEnabled = "DD_TRACE_PARTIAL_FLUSH_ENABLED";
/// <summary>
/// Configuration key to set the minimum number of closed spans in a trace before it's partially flushed
/// </summary>
/// <seealso cref="TracerSettings.PartialFlushMinSpans"/>
public const string PartialFlushMinSpans = "DD_TRACE_PARTIAL_FLUSH_MIN_SPANS";
/// <summary>
/// Configuration key to enable or disable the creation of a span context on exiting a successful Kafka
/// Consumer.Consume() call, and closing the scope on entering Consumer.Consume().
/// Default value is <c>true</c> (enabled).
/// </summary>
/// <seealso cref="TracerSettings.KafkaCreateConsumerScopeEnabled"/>
public const string KafkaCreateConsumerScopeEnabled = "DD_TRACE_KAFKA_CREATE_CONSUMER_SCOPE_ENABLED";
/// <summary>
/// Configuration key for enabling or disabling CI Visibility.
/// Default is value is false (disabled).
/// </summary>
public const string CIVisibilityEnabled = "DD_CIVISIBILITY_ENABLED";
/// <summary>
/// String format patterns used to match integration-specific configuration keys.
/// </summary>
public static class Integrations
{
/// <summary>
/// Configuration key pattern for enabling or disabling an integration.
/// </summary>
public const string Enabled = "DD_TRACE_{0}_ENABLED";
/// <summary>
/// Configuration key pattern for enabling or disabling Analytics in an integration.
/// </summary>
public const string AnalyticsEnabled = "DD_TRACE_{0}_ANALYTICS_ENABLED";
/// <summary>
/// Configuration key pattern for setting Analytics sampling rate in an integration.
/// </summary>
public const string AnalyticsSampleRate = "DD_TRACE_{0}_ANALYTICS_SAMPLE_RATE";
}
/// <summary>
/// String constants for debug configuration keys.
/// </summary>
internal static class Debug
{
/// <summary>
/// Configuration key for forcing the automatic instrumentation to only use the mdToken method lookup mechanism.
/// </summary>
public const string ForceMdTokenLookup = "DD_TRACE_DEBUG_LOOKUP_MDTOKEN";
/// <summary>
/// Configuration key for forcing the automatic instrumentation to only use the fallback method lookup mechanism.
/// </summary>
public const string ForceFallbackLookup = "DD_TRACE_DEBUG_LOOKUP_FALLBACK";
}
internal static class FeatureFlags
{
/// <summary>
/// Feature Flag: enables updated resource names on `aspnet.request`, `aspnet-mvc.request`,
/// `aspnet-webapi.request`, and `aspnet_core.request` spans. Enables `aspnet_core_mvc.request` spans and
/// additional features on `aspnet_core.request` spans.
/// </summary>
/// <seealso cref="TracerSettings.RouteTemplateResourceNamesEnabled"/>
public const string RouteTemplateResourceNamesEnabled = "DD_TRACE_ROUTE_TEMPLATE_RESOURCE_NAMES_ENABLED";
/// <summary>
/// Feature Flag: enables instrumenting calls to netstandard.dll (only applies to CallSite instrumentation)
/// </summary>
public const string NetStandardEnabled = "DD_TRACE_NETSTANDARD_ENABLED";
}
}
}
| 1 | 22,145 | This is this a copy / paste error from above. | DataDog-dd-trace-dotnet | .cs |
@@ -0,0 +1,8 @@
+/**
+ * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
+ */
+
+package net.sourceforge.pmd.lang.java.typeresolution.typeinterference;
+
+public class Variable {
+} | 1 | 1 | 12,502 | this package has to be renamed to `typeinference` | pmd-pmd | java |
|
@@ -124,6 +124,9 @@ module.exports = {
let credentials = Realm.Credentials.anonymous();
let user = await app.logIn(credentials);
TestCase.assertInstanceOf(user, Realm.User);
+ TestCase.assertNotNull(user.deviceId);
+ TestCase.assertNotNull(user.providerType);
+ TestCase.assertEqual(user.providerType, "anon-user");
await user.logOut();
},
| 1 | 'use strict';
/* global navigator, WorkerNavigator */
const require_method = require;
// Prevent React Native packager from seeing modules required with this
function node_require(module) {
return require_method(module);
}
const { ObjectId } = require("bson");
const Realm = require('realm');
const TestCase = require('./asserts');
const AppConfig = require('./support/testConfig')
const Utils = require('./test-utils');
const tmp = require('tmp');
const fs = require('fs');
const execFile = require('child_process').execFile;
tmp.setGracefulCleanup();
const path = require("path");
function runOutOfProcess() {
const args = Array.prototype.slice.call(arguments);
let tmpDir = tmp.dirSync();
console.log(`runOutOfProcess : ${args.join(' ')}`);
return new Promise((resolve, reject) => {
try {
execFile(process.execPath, args, { cwd: tmpDir.name }, (error, stdout, stderr) => {
if (error) {
console.error("runOutOfProcess failed\n", error, stdout, stderr);
reject(new Error(`Running ${args[0]} failed. error: ${error}`));
return;
}
console.log('runOutOfProcess success\n' + stdout);
resolve();
});
}
catch (e) {
reject(e);
}
});
}
const config = AppConfig.integrationAppConfig;
module.exports = {
testNewApp() {
let app = new Realm.App(config);
TestCase.assertInstanceOf(app, Realm.App);
},
testNewAppFromString() {
let app = new Realm.App(config.id);
TestCase.assertInstanceOf(app, Realm.App);
TestCase.assertEqual(app.id, config.id);
},
testNewAppFromUndefined() {
const error = TestCase.assertThrows(() => new Realm.App());
TestCase.assertEqual(
error.message,
'Invalid arguments: 1 expected, but 0 supplied.',
);
},
testNewAppFromOther() {
const error = TestCase.assertThrows(() => new Realm.App(1234));
TestCase.assertEqual(
error.message,
'Expected either a configuration object or an app id string.',
);
},
async testInvalidServer() {
const conf = {
id: 'smurf',
url: 'http://localhost:9999',
timeout: 1000,
app: {
name: 'realm-sdk-integration-tests',
version: '42'
}
};
let app = new Realm.App(conf);
let credentials = Realm.Credentials.anonymous();
let failed = false;
let user = await app.logIn(credentials).catch(err => {
failed = true;
TestCase.assertEqual(err.message, "request to http://localhost:9999/api/client/v2.0/app/smurf/location failed, reason: connect ECONNREFUSED 127.0.0.1:9999");
});
TestCase.assertEqual(failed, true);
},
async testNonexistingApp() {
const conf = {
id: 'smurf',
url: config.url,
timeout: 1000,
app: {
name: 'realm-sdk-integration-tests',
version: '42'
}
};
let app = new Realm.App(conf);
let credentials = Realm.Credentials.anonymous();
let failed = false;
let user = await app.logIn(credentials).catch(err => {
failed = true;
TestCase.assertEqual(err.message, "cannot find app using Client App ID 'smurf'");
});
TestCase.assertEqual(failed, true);
},
async testLogIn() {
let app = new Realm.App(config);
TestCase.assertTrue(app instanceof Realm.App);
let credentials = Realm.Credentials.anonymous();
let user = await app.logIn(credentials);
TestCase.assertInstanceOf(user, Realm.User);
await user.logOut();
},
async testLogInNonexistingUser() {
let app = new Realm.App(config);
TestCase.assertTrue(app instanceof Realm.App);
let credentials = Realm.Credentials.emailPassword('me', 'secret');
var didFail = false;
let user = await app.logIn(credentials).catch(err => {
TestCase.assertEqual(err.message, "invalid username/password");
TestCase.assertEqual(err.code, -1);
didFail = true;
});
TestCase.assertUndefined(user);
TestCase.assertEqual(didFail, true);
},
async testLogoutAndAllUsers() {
let app = new Realm.App(config);
let credentials = Realm.Credentials.anonymous();
let users = app.allUsers;
const nUsers = Object.keys(users).length;
let user = await app.logIn(credentials);
users = app.allUsers;
TestCase.assertEqual(Object.keys(users).length, nUsers + 1)
await user.logOut();
users = app.allUsers;
TestCase.assertEqual(Object.keys(users).length, nUsers);
},
async testCurrentUser() {
let app = new Realm.App(config);
TestCase.assertNull(app.currentUser);
let credentials = Realm.Credentials.anonymous();
let user1 = await app.logIn(credentials);
let user2 = app.currentUser;
TestCase.assertEqual(user1.id, user2.id);
await user1.logOut();
TestCase.assertNull(app.currentUser);
},
async testMongoDBRealmSync() {
let app = new Realm.App(config);
let credentials = Realm.Credentials.anonymous();
let user = await app.logIn(credentials);
const partition = Utils.genPartition();
const realmConfig = {
schema: [{
name: 'Dog',
primaryKey: '_id',
properties: {
_id: 'objectId?',
breed: 'string?',
name: 'string',
realm_id: 'string?',
}
}],
sync: {
user: user,
partitionValue: partition,
_sessionStopPolicy: 'immediately', // Make it safe to delete files after realm.close()
}
};
Realm.deleteFile(realmConfig);
let realm = await Realm.open(realmConfig);
realm.write(() => {
realm.create("Dog", { "_id": new ObjectId(), name: "King" });
realm.create("Dog", { "_id": new ObjectId(), name: "King" });
});
await realm.syncSession.uploadAllLocalChanges();
TestCase.assertEqual(realm.objects("Dog").length, 2);
realm.close();
Realm.deleteFile(realmConfig);
let realm2 = await Realm.open(realmConfig);
await realm2.syncSession.downloadAllServerChanges();
TestCase.assertEqual(realm2.objects("Dog").length, 2);
realm2.close();
await user.logOut();
},
};
| 1 | 19,301 | This cancels the above null-check I guess. | realm-realm-js | js |
@@ -31,9 +31,9 @@ public final class Configuration {
//// 2.1 configuration items
public static final String PROP_ROOT = "servicecomb.loadbalance.";
- public static final String RPOP_SERVER_EXPIRED_IN_SECONDS = "servicecomb.loadbalance.stats.serverExpiredInSeconds";
+ public static final String PROP_SERVER_EXPIRED_IN_SECONDS = "servicecomb.loadbalance.stats.serverExpiredInSeconds";
- public static final String RPOP_TIMER_INTERVAL_IN_MINIS = "servicecomb.loadbalance.stats.timerIntervalInMilis";
+ public static final String PROP_TIMER_INTERVAL_IN_MILLIS = "servicecomb.loadbalance.stats.timerIntervalInMilis";
public static final String PROP_RULE_STRATEGY_NAME = "strategy.name";
| 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.loadbalance;
import java.util.Map;
import org.apache.servicecomb.serviceregistry.config.ConfigurePropertyUtils;
import com.netflix.config.DynamicPropertyFactory;
/**
* configuration items
*
*/
public final class Configuration {
//// 2.1 configuration items
public static final String PROP_ROOT = "servicecomb.loadbalance.";
public static final String RPOP_SERVER_EXPIRED_IN_SECONDS = "servicecomb.loadbalance.stats.serverExpiredInSeconds";
public static final String RPOP_TIMER_INTERVAL_IN_MINIS = "servicecomb.loadbalance.stats.timerIntervalInMilis";
public static final String PROP_RULE_STRATEGY_NAME = "strategy.name";
// 2.0 configuration items
public static final String PROP_ROOT_20 = "ribbon.";
// retry configurations
public static final String PROP_RETRY_HANDLER = "retryHandler";
public static final String PROP_RETRY_ENABLED = "retryEnabled";
public static final String PROP_RETRY_ONNEXT = "retryOnNext";
public static final String PROP_RETRY_ONSAME = "retryOnSame";
// SessionStickinessRule configruation
public static final String SESSION_TIMEOUT_IN_SECONDS = "SessionStickinessRule.sessionTimeoutInSeconds";
public static final String SUCCESSIVE_FAILED_TIMES = "SessionStickinessRule.successiveFailedTimes";
private static final double PERCENT = 100;
public static final String FILTER_ISOLATION = "isolation.";
public static final String FILTER_OPEN = "enabled";
public static final String FILTER_ERROR_PERCENTAGE = "errorThresholdPercentage";
public static final String FILTER_ENABLE_REQUEST = "enableRequestThreshold";
public static final String FILTER_SINGLE_TEST = "singleTestTime";
public static final String FILTER_MIN_ISOLATION_TIME = "minIsolationTime";
public static final String FILTER_CONTINUOUS_FAILURE_THRESHOLD = "continuousFailureThreshold";
public static final String TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN =
"servicecomb.loadbalance.%s.transactionControl.options";
public static final Configuration INSTANCE = new Configuration();
private Configuration() {
}
public String getRuleStrategyName(String microservice) {
return getStringProperty(null,
PROP_ROOT + microservice + "." + PROP_RULE_STRATEGY_NAME,
PROP_ROOT + PROP_RULE_STRATEGY_NAME);
}
public int getSessionTimeoutInSeconds(String microservice) {
final int defaultValue = 30;
String p = getStringProperty("30",
PROP_ROOT + microservice + "." + SESSION_TIMEOUT_IN_SECONDS,
PROP_ROOT + SESSION_TIMEOUT_IN_SECONDS);
try {
return Integer.parseInt(p); // can be negative
} catch (NumberFormatException e) {
return defaultValue;
}
}
public int getSuccessiveFailedTimes(String microservice) {
final int defaultValue = 5;
String p = getStringProperty("5",
PROP_ROOT + microservice + "." + SUCCESSIVE_FAILED_TIMES,
PROP_ROOT + SUCCESSIVE_FAILED_TIMES);
try {
return Integer.parseInt(p); // can be negative
} catch (NumberFormatException e) {
return defaultValue;
}
}
public String getRetryHandler(String microservice) {
return getStringProperty("default",
PROP_ROOT + microservice + "." + PROP_RETRY_HANDLER,
PROP_ROOT + PROP_RETRY_HANDLER);
}
public boolean isRetryEnabled(String microservice) {
String p = getStringProperty("false",
PROP_ROOT + microservice + "." + PROP_RETRY_ENABLED,
PROP_ROOT + PROP_RETRY_ENABLED);
return Boolean.parseBoolean(p);
}
public int getRetryOnNext(String microservice) {
final int defaultValue = 0;
String p = getStringProperty("0",
PROP_ROOT + microservice + "." + PROP_RETRY_ONNEXT,
PROP_ROOT + PROP_RETRY_ONNEXT);
try {
int result = Integer.parseInt(p);
if (result > 0) {
return result;
}
return defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
public int getRetryOnSame(String microservice) {
final int defaultValue = 0;
String p = getStringProperty("0",
PROP_ROOT + microservice + "." + PROP_RETRY_ONSAME,
PROP_ROOT + PROP_RETRY_ONSAME);
try {
int result = Integer.parseInt(p);
if (result > 0) {
return result;
}
return defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
public boolean isIsolationFilterOpen(String microservice) {
String p = getStringProperty("true",
PROP_ROOT + microservice + "." + FILTER_ISOLATION + FILTER_OPEN,
PROP_ROOT + FILTER_ISOLATION + FILTER_OPEN);
return Boolean.parseBoolean(p);
}
public int getErrorThresholdPercentage(String microservice) {
final int defaultValue = 0;
String p = getStringProperty("0",
PROP_ROOT + microservice + "." + FILTER_ISOLATION + FILTER_ERROR_PERCENTAGE,
PROP_ROOT + FILTER_ISOLATION + FILTER_ERROR_PERCENTAGE);
try {
int result = Integer.parseInt(p);
if (result <= PERCENT && result > 0) {
return result;
}
return defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
public int getEnableRequestThreshold(String microservice) {
final int defaultValue = 5;
String p = getStringProperty("5",
PROP_ROOT + microservice + "." + FILTER_ISOLATION + FILTER_ENABLE_REQUEST,
PROP_ROOT + FILTER_ISOLATION + FILTER_ENABLE_REQUEST);
try {
int result = Integer.parseInt(p);
if (result > 0) {
return result;
}
return defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
public int getSingleTestTime(String microservice) {
final int defaultValue = 60000;
String p = getStringProperty("60000",
PROP_ROOT + microservice + "." + FILTER_ISOLATION + FILTER_SINGLE_TEST,
PROP_ROOT + FILTER_ISOLATION + FILTER_SINGLE_TEST);
try {
int result = Integer.parseInt(p);
if (result >= 0) {
return result;
}
return defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
public int getMinIsolationTime(String microservice) {
final int defaultValue = 3000; // 3 seconds
String p = getStringProperty("3000",
PROP_ROOT + microservice + "." + FILTER_ISOLATION + FILTER_MIN_ISOLATION_TIME,
PROP_ROOT + FILTER_ISOLATION + FILTER_MIN_ISOLATION_TIME);
try {
int result = Integer.parseInt(p);
if (result >= 0) {
return result;
}
return defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
public Map<String, String> getFlowsplitFilterOptions(String microservice) {
String keyPrefix = String.format(TRANSACTIONCONTROL_OPTIONS_PREFIX_PATTERN, microservice);
return ConfigurePropertyUtils.getPropertiesWithPrefix(keyPrefix);
}
public static String getStringProperty(String defaultValue, String... keys) {
String property = null;
for (String key : keys) {
property = DynamicPropertyFactory.getInstance().getStringProperty(key, null).get();
if (property != null) {
return property;
}
}
return defaultValue;
}
public int getContinuousFailureThreshold(String microservice) {
final int defaultValue = 5;
String p = getStringProperty("5",
PROP_ROOT + microservice + "." + FILTER_ISOLATION + FILTER_CONTINUOUS_FAILURE_THRESHOLD,
PROP_ROOT + FILTER_ISOLATION + FILTER_CONTINUOUS_FAILURE_THRESHOLD);
try {
int result = Integer.parseInt(p);
if (result > 0) {
return result;
}
return defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
}
| 1 | 11,579 | change to timerIntervalInMillis | apache-servicecomb-java-chassis | java |
@@ -121,6 +121,8 @@ return [
'email' => 'Email',
'role_field' => 'Role',
'role_comment' => 'Roles define user permissions, which can be overriden on the user level, on the Permissions tab.',
+ 'role_none' => 'None',
+ 'role_none_comment' => 'This administrator does not belong to any rules.',
'groups' => 'Groups',
'groups_comment' => 'Specify which groups this account should belong to.',
'avatar' => 'Avatar', | 1 | <?php
return [
'auth' => [
'title' => 'Administration Area',
'invalid_login' => 'The details you entered did not match our records. Please double-check and try again.'
],
'field' => [
'invalid_type' => 'Invalid field type used :type.',
'options_method_invalid_model' => "The attribute ':field' does not resolve to a valid model. Try specifying the options method for model class :model explicitly.",
'options_method_not_exists' => "The model class :model must define a method :method() returning options for the ':field' form field.",
'colors_method_not_exists' => "The model class :model must define a method :method() returning html color HEX codes for the ':field' form field."
],
'widget' => [
'not_registered' => "A widget class name ':name' has not been registered",
'not_bound' => "A widget with class name ':name' has not been bound to the controller"
],
'page' => [
'untitled' => 'Untitled',
'access_denied' => [
'label' => 'Access denied',
'help' => "You don't have the required permissions to view this page.",
'cms_link' => 'Return to the back-end'
],
'no_database' => [
'label' => 'Database missing',
'help' => "A database is required to access the back-end. Check the database is configured and migrated before trying again.",
'cms_link' => 'Return to the homepage'
],
'invalid_token' => [
'label' => 'Invalid security token'
]
],
'partial' => [
'not_found_name' => "The partial ':name' is not found."
],
'account' => [
'signed_in_as' => 'Signed in as :full_name',
'sign_out' => 'Sign out',
'login' => 'Login',
'reset' => 'Reset',
'restore' => 'Restore',
'login_placeholder' => 'login',
'password_placeholder' => 'password',
'remember_me' => 'Stay logged in',
'forgot_password' => 'Forgot your password?',
'enter_email' => 'Enter your email',
'enter_login' => 'Enter your login',
'email_placeholder' => 'email',
'enter_new_password' => 'Enter a new password',
'password_reset' => 'Password Reset',
'restore_success' => 'Message sent to your email address with instructions.',
'restore_error' => "A user could not be found with a login value of ':login'",
'reset_success' => 'Password has been reset. You may now sign in.',
'reset_error' => 'Invalid password reset data supplied. Please try again!',
'reset_fail' => 'Unable to reset your password!',
'apply' => 'Apply',
'cancel' => 'Cancel',
'delete' => 'Delete',
'ok' => 'OK'
],
'dashboard' => [
'menu_label' => 'Dashboard',
'widget_label' => 'Widget',
'widget_width' => 'Width',
'full_width' => 'full width',
'manage_widgets' => 'Manage widgets',
'add_widget' => 'Add widget',
'widget_inspector_title' => 'Widget configuration',
'widget_inspector_description' => 'Configure the report widget',
'widget_columns_label' => 'Width :columns',
'widget_columns_description' => 'The widget width, a number between 1 and 10.',
'widget_columns_error' => 'Please enter the widget width as a number between 1 and 10.',
'columns' => '{1} column|[2,Inf] columns',
'widget_new_row_label' => 'Force new row',
'widget_new_row_description' => 'Put the widget in a new row.',
'widget_title_label' => 'Widget title',
'widget_title_error' => 'The Widget Title is required.',
'reset_layout' => 'Reset layout',
'reset_layout_confirm' => 'Reset layout back to default?',
'reset_layout_success' => 'Layout has been reset',
'make_default' => 'Make default',
'make_default_confirm' => 'Set the current layout as the default?',
'make_default_success' => 'Current layout is now the default',
'collapse_all' => 'Collapse all',
'expand_all' => 'Expand all',
'status' => [
'widget_title_default' => 'System status',
'update_available' => '{0} updates available!|{1} update available!|[2,Inf] updates available!',
'updates_pending' => 'Pending software updates',
'updates_nil' => 'Software is up to date',
'updates_link' => 'Update',
'warnings_pending' => 'Some issues need attention',
'warnings_nil' => 'No warnings to display',
'warnings_link' => 'View',
'core_build' => 'System build',
'event_log' => 'Event log',
'request_log' => 'Request log',
'app_birthday' => 'Online since',
],
'welcome' => [
'widget_title_default' => 'Welcome',
'welcome_back_name' => 'Welcome back to :app, :name.',
'welcome_to_name' => 'Welcome to :app, :name.',
'first_sign_in' => 'This is the first time you have signed in.',
'last_sign_in' => 'Your last sign in was',
'view_access_logs' => 'View access logs',
'nice_message' => 'Have a great day!',
]
],
'user' => [
'name' => 'Administrator',
'menu_label' => 'Administrators',
'menu_description' => 'Manage back-end administrator users, groups and permissions.',
'list_title' => 'Manage Administrators',
'new' => 'New Administrator',
'login' => 'Login',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'full_name' => 'Full Name',
'email' => 'Email',
'role_field' => 'Role',
'role_comment' => 'Roles define user permissions, which can be overriden on the user level, on the Permissions tab.',
'groups' => 'Groups',
'groups_comment' => 'Specify which groups this account should belong to.',
'avatar' => 'Avatar',
'password' => 'Password',
'password_confirmation' => 'Confirm Password',
'permissions' => 'Permissions',
'account' => 'Account',
'superuser' => 'Super User',
'superuser_comment' => 'Grants this account unlimited access to all areas of the system. Super users can add and manage other users. ',
'send_invite' => 'Send invitation by email',
'send_invite_comment' => 'Sends a welcome message containing login and password information.',
'delete_confirm' => 'Delete this administrator?',
'return' => 'Return to admin list',
'allow' => 'Allow',
'inherit' => 'Inherit',
'deny' => 'Deny',
'activated' => 'Activated',
'last_login' => 'Last login',
'created_at' => 'Created at',
'updated_at' => 'Updated at',
'group' => [
'name' => 'Group',
'name_field' => 'Name',
'name_comment' => 'The name is displayed in the group list on the Administrator form.',
'description_field' => 'Description',
'is_new_user_default_field_label' => 'Default group',
'is_new_user_default_field_comment' => 'Add new administrators to this group by default',
'code_field' => 'Code',
'code_comment' => 'Enter a unique code if you want to access the group object with the API.',
'menu_label' => 'Manage Groups',
'list_title' => 'Manage Groups',
'new' => 'New Group',
'delete_confirm' => 'Delete this administrator group?',
'return' => 'Return to group list',
'users_count' => 'Users'
],
'role' => [
'name' => 'Role',
'name_field' => 'Name',
'name_comment' => 'The name is displayed in the role list on the Administrator form.',
'description_field' => 'Description',
'code_field' => 'Code',
'code_comment' => 'Enter a unique code if you want to access the role object with the API.',
'menu_label' => 'Manage Roles',
'list_title' => 'Manage Roles',
'new' => 'New Role',
'delete_confirm' => 'Delete this administrator role?',
'return' => 'Return to role list',
'users_count' => 'Users'
],
'preferences' => [
'not_authenticated' => 'There is no an authenticated user to load or save preferences for.'
]
],
'list' => [
'default_title' => 'List',
'search_prompt' => 'Search...',
'no_records' => 'There are no records in this view.',
'missing_model' => 'List behavior used in :class does not have a model defined.',
'missing_column' => 'There are no column definitions for :columns.',
'missing_columns' => 'List used in :class has no list columns defined.',
'missing_definition' => "List behavior does not contain a column for ':field'.",
'missing_parent_definition' => "List behavior does not contain a definition for ':definition'.",
'behavior_not_ready' => 'List behavior has not been initialized, check that you have called makeLists() in your controller.',
'invalid_column_datetime' => "Column value ':column' is not a DateTime object, are you missing a \$dates reference in the Model?",
'pagination' => 'Displayed records: :from-:to of :total',
'first_page' => 'First page',
'last_page' => 'Last page',
'prev_page' => 'Previous page',
'next_page' => 'Next page',
'refresh' => 'Refresh',
'updating' => 'Updating...',
'loading' => 'Loading...',
'setup_title' => 'List setup',
'setup_help' => 'Use checkboxes to select columns you want to see in the list. You can change position of columns by dragging them up or down.',
'records_per_page' => 'Records per page',
'records_per_page_help' => 'Select the number of records per page to display. Please note that high number of records on a single page can reduce performance.',
'check' => 'Check',
'delete_selected' => 'Delete selected',
'delete_selected_empty' => 'There are no selected records to delete.',
'delete_selected_confirm' => 'Delete the selected records?',
'delete_selected_success' => 'Deleted selected records.',
'column_switch_true' => 'Yes',
'column_switch_false' => 'No'
],
'fileupload' => [
'attachment' => 'Attachment',
'help' => 'Add a title and description for this attachment.',
'title_label' => 'Title',
'description_label' => 'Description',
'default_prompt' => 'Click the %s or drag a file here to upload',
'attachment_url' => 'Attachment URL',
'upload_file' => 'Upload file',
'upload_error' => 'Upload error',
'remove_confirm' => 'Are you sure?',
'remove_file' => 'Remove file'
],
'repeater' => [
'min_items_failed' => ':name requires a minimum of :min items, only :items were provided',
'max_items_failed' => ':name only allows up to :max items, :items were provided',
],
'form' => [
'create_title' => 'New :name',
'update_title' => 'Edit :name',
'preview_title' => 'Preview :name',
'create_success' => ':name created',
'update_success' => ':name updated',
'delete_success' => ':name deleted',
'reset_success' => 'Reset complete',
'missing_id' => 'Form record ID has not been specified.',
'missing_model' => 'Form behavior used in :class does not have a model defined.',
'missing_definition' => "Form behavior does not contain a field for ':field'.",
'not_found' => 'Form record with an ID of :id could not be found.',
'action_confirm' => 'Are you sure?',
'create' => 'Create',
'create_and_close' => 'Create and close',
'creating' => 'Creating...',
'creating_name' => 'Creating :name...',
'save' => 'Save',
'save_and_close' => 'Save and close',
'saving' => 'Saving...',
'saving_name' => 'Saving :name...',
'delete' => 'Delete',
'deleting' => 'Deleting...',
'confirm_delete' => 'Delete record?',
'confirm_delete_multiple' => 'Delete selected records?',
'deleting_name' => 'Deleting :name...',
'reset_default' => 'Reset to default',
'resetting' => 'Resetting',
'resetting_name' => 'Resetting :name',
'undefined_tab' => 'Misc',
'field_off' => 'Off',
'field_on' => 'On',
'add' => 'Add',
'apply' => 'Apply',
'cancel' => 'Cancel',
'close' => 'Close',
'confirm' => 'Confirm',
'reload' => 'Reload',
'complete' => 'Complete',
'ok' => 'OK',
'or' => 'or',
'confirm_tab_close' => 'Close the tab? Unsaved changes will be lost.',
'behavior_not_ready' => 'Form behavior has not been initialized, check that you have called initForm() in your controller.',
'preview_no_files_message' => 'There are no files uploaded.',
'preview_no_media_message' => 'There is no media selected.',
'preview_no_record_message' => 'There is no record selected.',
'select' => 'Select',
'select_all' => 'all',
'select_none' => 'none',
'select_placeholder' => 'please select',
'insert_row' => 'Insert Row',
'insert_row_below' => 'Insert Row Below',
'delete_row' => 'Delete Row',
'concurrency_file_changed_title' => 'File was changed',
'concurrency_file_changed_description' => "The file you're editing has been changed on disk by another user. You can either reload the file and lose your changes or override the file on the disk.",
'return_to_list' => 'Return to the list'
],
'recordfinder' => [
'find_record' => 'Find Record',
'cancel' => 'Cancel',
],
'pagelist' => [
'page_link' => 'Page link',
'select_page' => 'Select a page...'
],
'relation' => [
'missing_config' => "Relation behavior does not have any configuration for ':config'.",
'missing_definition' => "Relation behavior does not contain a definition for ':field'.",
'missing_model' => 'Relation behavior used in :class does not have a model defined.',
'invalid_action_single' => 'This action cannot be performed on a singular relationship.',
'invalid_action_multi' => 'This action cannot be performed on a multiple relationship.',
'help' => 'Click on an item to add',
'related_data' => 'Related :name data',
'add' => 'Add',
'add_selected' => 'Add selected',
'add_a_new' => 'Add a new :name',
'link_selected' => 'Link selected',
'link_a_new' => 'Link a new :name',
'cancel' => 'Cancel',
'close' => 'Close',
'add_name' => 'Add :name',
'create' => 'Create',
'create_name' => 'Create :name',
'update' => 'Update',
'update_name' => 'Update :name',
'preview' => 'Preview',
'preview_name' => 'Preview :name',
'remove' => 'Remove',
'remove_name' => 'Remove :name',
'delete' => 'Delete',
'delete_name' => 'Delete :name',
'delete_confirm' => 'Are you sure?',
'link' => 'Link',
'link_name' => 'Link :name',
'unlink' => 'Unlink',
'unlink_name' => 'Unlink :name',
'unlink_confirm' => 'Are you sure?'
],
'reorder' => [
'default_title' => 'Reorder records',
'no_records' => 'There are no records available to sort.'
],
'model' => [
'name' => 'Model',
'not_found' => "Model ':class' with an ID of :id could not be found",
'missing_id' => 'There is no ID specified for looking up the model record.',
'missing_relation' => "Model ':class' does not contain a definition for ':relation'.",
'missing_method' => "Model ':class' does not contain a method ':method'.",
'invalid_class' => "Model :model used in :class is not valid, it must inherit the \Model class.",
'mass_assignment_failed' => "Mass assignment failed for Model attribute ':attribute'."
],
'warnings' => [
'tips' => 'System configuration tips',
'tips_description' => 'There are issues you need to pay attention to in order to configure the system properly.',
'permissions' => 'Directory :name or its subdirectories is not writable for PHP. Please set corresponding permissions for the webserver on this directory.',
'extension' => 'The PHP extension :name is not installed. Please install this library and activate the extension.',
'plugin_missing' => 'The plugin :name is a dependency but is not installed. Please install this plugin.',
],
'editor' => [
'menu_label' => 'Editor settings',
'menu_description' => 'Customize the global editor preferences, such as font size and color scheme.',
'font_size' => 'Font size',
'tab_size' => 'Tab size',
'use_hard_tabs' => 'Indent using tabs',
'code_folding' => 'Code folding',
'code_folding_begin' => 'Mark begin',
'code_folding_begin_end' => 'Mark begin and end',
'autocompletion' => 'Autocompletion',
'word_wrap' => 'Word wrap',
'highlight_active_line' => 'Highlight active line',
'auto_closing' => 'Automatically close tags',
'show_invisibles' => 'Show invisible characters',
'show_gutter' => 'Show gutter',
'basic_autocompletion'=> 'Basic Autocompletion (Ctrl + Space)',
'live_autocompletion'=> 'Live Autocompletion',
'enable_snippets'=> 'Enable code snippets (Tab)',
'display_indent_guides'=> 'Show indent guides',
'show_print_margin'=> 'Show print margin',
'mode_off' => 'Off',
'mode_fluid' => 'Fluid',
'40_characters' => '40 Characters',
'80_characters' => '80 Characters',
'theme' => 'Color scheme',
'markup_styles' => 'Markup Styles',
'custom_styles' => 'Custom stylesheet',
'custom styles_comment' => 'Custom styles to include in the HTML editor.',
'markup_classes' => 'Markup Classes',
'paragraph' => 'Paragraph',
'link' => 'Link',
'table' => 'Table',
'table_cell' => 'Table Cell',
'image' => 'Image',
'label' => 'Label',
'class_name' => 'Class name',
'markup_tags' => 'Markup Tags',
'allowed_empty_tags' => 'Allowed empty tags',
'allowed_empty_tags_comment' => 'The list of tags that are not removed when they have no content inside.',
'allowed_tags' => 'Allowed tags',
'allowed_tags_comment' => 'The list of allowed tags.',
'no_wrap' => 'Do not wrap tags',
'no_wrap_comment' => 'The list of tags that should not be wrapped inside block tags.',
'remove_tags' => 'Remove tags',
'remove_tags_comment' => 'The list of tags that are removed together with their content.',
'line_breaker_tags' => 'Line breaker tags',
'line_breaker_tags_comment' => 'The list of tags that are used to place a line breaker element between.',
'toolbar_buttons' => 'Toolbar Buttons',
'toolbar_buttons_comment' => 'The Toolbar Buttons to be displayed in the Rich Editor by default. [fullscreen, bold, italic, underline, strikeThrough, subscript, superscript, fontFamily, fontSize, |, color, emoticons, inlineStyle, paragraphStyle, |, paragraphFormat, align, formatOL, formatUL, outdent, indent, quote, insertHR, -, insertLink, insertImage, insertVideo, insertAudio, insertFile, insertTable, undo, redo, clearFormatting, selectAll, html]',
],
'tooltips' => [
'preview_website' => 'Preview the website'
],
'mysettings' => [
'menu_label' => 'My Settings',
'menu_description' => 'Settings related to your administration account'
],
'myaccount' => [
'menu_label' => 'My account',
'menu_description' => 'Update your account details such as name, email address and password.',
'menu_keywords' => 'security login'
],
'branding' => [
'menu_label' => 'Customize back-end',
'menu_description' => 'Customize the administration area such as name, colors and logo.',
'brand' => 'Brand',
'logo' => 'Logo',
'logo_description' => 'Upload a custom logo to use in the back-end.',
'app_name' => 'App Name',
'app_name_description' => 'This name is shown in the title area of the back-end.',
'app_tagline' => 'App Tagline',
'app_tagline_description' => 'This name is shown on the sign in screen for the back-end.',
'colors' => 'Colors',
'primary_color' => 'Primary color',
'secondary_color' => 'Secondary color',
'accent_color' => 'Accent color',
'styles' => 'Styles',
'custom_stylesheet' => 'Custom stylesheet',
'navigation' => 'Navigation',
'menu_mode' => 'Menu style',
'menu_mode_inline' => 'Inline',
'menu_mode_tile' => 'Tiles',
'menu_mode_collapsed' => 'Collapsed'
],
'backend_preferences' => [
'menu_label' => 'Back-end preferences',
'menu_description' => 'Manage your account preferences such as desired language.',
'region' => 'Region',
'code_editor' => 'Code editor',
'timezone' => 'Timezone',
'timezone_comment' => 'Adjust displayed dates to this timezone.',
'locale' => 'Locale',
'locale_comment' => 'Select your desired locale for language use.'
],
'access_log' => [
'hint' => 'This log displays a list of successful sign in attempts by administrators. Records are kept for a total of :days days.',
'menu_label' => 'Access log',
'menu_description' => 'View a list of successful back-end user sign ins.',
'created_at' => 'Date & Time',
'login' => 'Login',
'ip_address' => 'IP address',
'first_name' => 'First name',
'last_name' => 'Last name',
'email' => 'Email'
],
'filter' => [
'all' => 'all',
'options_method_not_exists' => "The model class :model must define a method :method() returning options for the ':filter' filter.",
'date_all' => 'all periods',
'number_all' => 'all numbers',
],
'import_export' => [
'upload_csv_file' => '1. Upload a CSV file',
'import_file' => 'Import file',
'row' => 'Row :row',
'first_row_contains_titles' => 'First row contains column titles',
'first_row_contains_titles_desc' => 'Leave this checked if the first row in the CSV is used as the column titles.',
'match_columns' => '2. Match the file columns to database fields',
'file_columns' => 'File columns',
'database_fields' => 'Database fields',
'set_import_options' => '3. Set import options',
'export_output_format' => '1. Export output format',
'file_format' => 'File format',
'standard_format' => 'Standard format',
'custom_format' => 'Custom format',
'delimiter_char' => 'Delimiter character',
'enclosure_char' => 'Enclosure character',
'escape_char' => 'Escape character',
'select_columns' => '2. Select columns to export',
'column' => 'Column',
'columns' => 'Columns',
'set_export_options' => '3. Set export options',
'show_ignored_columns' => 'Show ignored columns',
'auto_match_columns' => 'Auto match columns',
'created' => 'Created',
'updated' => 'Updated',
'skipped' => 'Skipped',
'warnings' => 'Warnings',
'errors' => 'Errors',
'skipped_rows' => 'Skipped Rows',
'import_progress' => 'Import progress',
'processing' => 'Processing',
'import_error' => 'Import error',
'upload_valid_csv' => 'Please upload a valid CSV file.',
'drop_column_here' => 'Drop column here...',
'ignore_this_column' => 'Ignore this column',
'processing_successful_line1' => 'File export process completed!',
'processing_successful_line2' => 'The browser will now redirect to the file download.',
'export_progress' => 'Export progress',
'export_error' => 'Export error',
'column_preview' => 'Column preview',
'file_not_found_error' => 'File not found',
'empty_error' => 'There was no data supplied to export',
'empty_import_columns_error' => 'Please specify some columns to import.',
'match_some_column_error' => 'Please match some columns first.',
'required_match_column_error' => 'Please specify a match for the required field :label.',
'empty_export_columns_error' => 'Please specify some columns to export.',
'behavior_missing_uselist_error' => 'You must implement the controller behavior ListController with the export "useList" option enabled.',
'missing_model_class_error' => 'Please specify the modelClass property for :type',
'missing_column_id_error' => 'Missing column identifier',
'unknown_column_error' => 'Unknown column',
'encoding_not_supported_error' => 'Source file encoding is not recognized. Please select the custom file format option with the proper encoding to import your file.',
'encoding_format' => 'File encoding',
'encodings' => [
'utf_8' => 'UTF-8',
'us_ascii' => 'US-ASCII',
'iso_8859_1' => 'ISO-8859-1 (Latin-1, Western European)',
'iso_8859_2' => 'ISO-8859-2 (Latin-2, Central European)',
'iso_8859_3' => 'ISO-8859-3 (Latin-3, South European)',
'iso_8859_4' => 'ISO-8859-4 (Latin-4, North European)',
'iso_8859_5' => 'ISO-8859-5 (Latin, Cyrillic)',
'iso_8859_6' => 'ISO-8859-6 (Latin, Arabic)',
'iso_8859_7' => 'ISO-8859-7 (Latin, Greek)',
'iso_8859_8' => 'ISO-8859-8 (Latin, Hebrew)',
'iso_8859_0' => 'ISO-8859-9 (Latin-5, Turkish)',
'iso_8859_10' => 'ISO-8859-10 (Latin-6, Nordic)',
'iso_8859_11' => 'ISO-8859-11 (Latin, Thai)',
'iso_8859_13' => 'ISO-8859-13 (Latin-7, Baltic Rim)',
'iso_8859_14' => 'ISO-8859-14 (Latin-8, Celtic)',
'iso_8859_15' => 'ISO-8859-15 (Latin-9, Western European revision with euro sign)',
'windows_1251' => 'Windows-1251 (CP1251)',
'windows_1252' => 'Windows-1252 (CP1252)'
]
],
'permissions' => [
'manage_media' => 'Upload and manage media contents - images, videos, sounds, documents'
],
'mediafinder' => [
'label' => 'Media Finder',
'default_prompt' => 'Click the %s button to find a media item'
],
'media' => [
'menu_label' => 'Media',
'upload' => 'Upload',
'move' => 'Move',
'delete' => 'Delete',
'add_folder' => 'Add folder',
'search' => 'Search',
'display' => 'Display',
'filter_everything' => 'Everything',
'filter_images' => 'Images',
'filter_video' => 'Video',
'filter_audio' => 'Audio',
'filter_documents' => 'Documents',
'library' => 'Library',
'size' => 'Size',
'title' => 'Title',
'last_modified' => 'Last modified',
'public_url' => 'URL',
'click_here' => 'Click here',
'thumbnail_error' => 'Error generating thumbnail.',
'return_to_parent' => 'Return to the parent folder',
'return_to_parent_label' => 'Go up ..',
'nothing_selected' => 'Nothing is selected.',
'multiple_selected' => 'Multiple items selected.',
'uploading_file_num' => 'Uploading :number file(s)...',
'uploading_complete' => 'Upload complete',
'uploading_error' => 'Upload failed',
'type_blocked' => 'The file type used is blocked for security reasons.',
'order_by' => 'Order by',
'direction' => 'Direction',
'direction_asc' => 'Ascending',
'direction_desc' => 'Descending',
'folder' => 'Folder',
'no_files_found' => 'No files found by your request.',
'delete_empty' => 'Please select items to delete.',
'delete_confirm' => 'Delete the selected item(s)?',
'error_renaming_file' => 'Error renaming the item.',
'new_folder_title' => 'New folder',
'folder_name' => 'Folder name',
'error_creating_folder' => 'Error creating folder',
'folder_or_file_exist' => 'A folder or file with the specified name already exists.',
'move_empty' => 'Please select items to move.',
'move_popup_title' => 'Move files or folders',
'move_destination' => 'Destination folder',
'please_select_move_dest' => 'Please select a destination folder.',
'move_dest_src_match' => 'Please select another destination folder.',
'empty_library' => 'It looks a bit empty here. Upload files or create folders to get started.',
'insert' => 'Insert',
'crop_and_insert' => 'Crop & Insert',
'select_single_image' => 'Please select a single image.',
'selection_not_image' => 'The selected item is not an image.',
'restore' => 'Undo all changes',
'resize' => 'Resize...',
'selection_mode_normal' => 'Normal',
'selection_mode_fixed_ratio' => 'Fixed ratio',
'selection_mode_fixed_size' => 'Fixed size',
'height' => 'Height',
'width' => 'Width',
'selection_mode' => 'Selection mode',
'resize_image' => 'Resize image',
'image_size' => 'Image size:',
'selected_size' => 'Selected:'
],
];
| 1 | 13,646 | `any rules` should be `any roles` | octobercms-october | php |
@@ -105,13 +105,12 @@ public class AllEpisodesFragment extends EpisodesListFragment {
@NonNull
@Override
protected List<FeedItem> loadData() {
- return feedItemFilter.filter(DBReader.getRecentlyPublishedEpisodes(0, page * EPISODES_PER_PAGE));
+ return DBReader.getRecentlyPublishedEpisodesFiltered(0, page * EPISODES_PER_PAGE, feedItemFilter);
}
@NonNull
@Override
protected List<FeedItem> loadMoreData() {
- return feedItemFilter.filter(DBReader.getRecentlyPublishedEpisodes((page - 1) * EPISODES_PER_PAGE,
- EPISODES_PER_PAGE));
+ return DBReader.getRecentlyPublishedEpisodesFiltered((page - 1) * EPISODES_PER_PAGE, EPISODES_PER_PAGE, feedItemFilter);
}
} | 1 | package de.danoeh.antennapod.fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.joanzapata.iconify.Iconify;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.feed.FeedItem;
import de.danoeh.antennapod.core.feed.FeedItemFilter;
import de.danoeh.antennapod.core.storage.DBReader;
import de.danoeh.antennapod.dialog.FilterDialog;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Set;
/**
* Like 'EpisodesFragment' except that it only shows new episodes and
* supports swiping to mark as read.
*/
public class AllEpisodesFragment extends EpisodesListFragment {
private static final String PREF_NAME = "PrefAllEpisodesFragment";
private static final String PREF_FILTER = "filter";
private static FeedItemFilter feedItemFilter = new FeedItemFilter("");
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = getActivity().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
feedItemFilter = new FeedItemFilter(prefs.getString(PREF_FILTER, ""));
}
@Override
protected String getPrefName() {
return PREF_NAME;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!super.onOptionsItemSelected(item)) {
if (item.getItemId() == R.id.filter_items) {
showFilterDialog();
return true;
}
return false;
} else {
return true;
}
}
@Override
public void onPrepareOptionsMenu(@NonNull Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.filter_items).setVisible(true);
menu.findItem(R.id.mark_all_read_item).setVisible(true);
menu.findItem(R.id.remove_all_new_flags_item).setVisible(false);
}
@Override
protected void onFragmentLoaded(List<FeedItem> episodes) {
super.onFragmentLoaded(episodes);
if (feedItemFilter.getValues().length > 0) {
txtvInformation.setText("{md-info-outline} " + this.getString(R.string.filtered_label));
Iconify.addIcons(txtvInformation);
txtvInformation.setVisibility(View.VISIBLE);
} else {
txtvInformation.setVisibility(View.GONE);
}
}
private void showFilterDialog() {
FilterDialog filterDialog = new FilterDialog(getContext(), feedItemFilter) {
@Override
protected void updateFilter(Set<String> filterValues) {
feedItemFilter = new FeedItemFilter(filterValues.toArray(new String[0]));
SharedPreferences prefs = getActivity().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
prefs.edit().putString(PREF_FILTER, StringUtils.join(filterValues, ",")).apply();
loadItems();
}
};
filterDialog.openDialog();
}
@Override
protected boolean shouldUpdatedItemRemainInList(FeedItem item) {
SharedPreferences prefs = getActivity().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
FeedItemFilter feedItemFilter = new FeedItemFilter(prefs.getString(PREF_FILTER, ""));
if (feedItemFilter.isShowDownloaded() && (!item.hasMedia() || !item.getMedia().isDownloaded())) {
return false;
}
return true;
}
@NonNull
@Override
protected List<FeedItem> loadData() {
return feedItemFilter.filter(DBReader.getRecentlyPublishedEpisodes(0, page * EPISODES_PER_PAGE));
}
@NonNull
@Override
protected List<FeedItem> loadMoreData() {
return feedItemFilter.filter(DBReader.getRecentlyPublishedEpisodes((page - 1) * EPISODES_PER_PAGE,
EPISODES_PER_PAGE));
}
}
| 1 | 17,459 | Why does the method need to be renamed? I would just keep the old name and update the other uses (which are only tests). That way, we can reduce code duplication. | AntennaPod-AntennaPod | java |
@@ -29,9 +29,11 @@ from qutebrowser.utils import message
from qutebrowser.config import config
from qutebrowser.keyinput import keyparser
from qutebrowser.utils import usertypes, log, objreg, utils
+from qutebrowser.config.parsers import keyconf
-STARTCHARS = ":/?"
+conf = keyconf.KeyConfigParser(None, None)
+STARTCHARS = conf.get_bindings_for('normal').keys()
LastPress = usertypes.enum('LastPress', ['none', 'filtertext', 'keystring'])
| 1 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]>
#
# 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/>.
"""KeyChainParser for "hint" and "normal" modes.
Module attributes:
STARTCHARS: Possible chars for starting a commandline input.
"""
from PyQt5.QtCore import pyqtSlot, Qt
from qutebrowser.utils import message
from qutebrowser.config import config
from qutebrowser.keyinput import keyparser
from qutebrowser.utils import usertypes, log, objreg, utils
STARTCHARS = ":/?"
LastPress = usertypes.enum('LastPress', ['none', 'filtertext', 'keystring'])
class NormalKeyParser(keyparser.CommandKeyParser):
"""KeyParser for normal mode with added STARTCHARS detection and more.
Attributes:
_partial_timer: Timer to clear partial keypresses.
"""
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=True,
supports_chains=True)
self.read_config('normal')
self._partial_timer = usertypes.Timer(self, 'partial-match')
self._partial_timer.setSingleShot(True)
self._inhibited = False
self._inhibited_timer = usertypes.Timer(self, 'normal-inhibited')
self._inhibited_timer.setSingleShot(True)
def __repr__(self):
return utils.get_repr(self)
def _handle_single_key(self, e):
"""Override _handle_single_key to abort if the key is a startchar.
Args:
e: the KeyPressEvent from Qt.
Return:
A self.Match member.
"""
txt = e.text().strip()
if self._inhibited:
self._debug_log("Ignoring key '{}', because the normal mode is "
"currently inhibited.".format(txt))
return self.Match.none
if not self._keystring and any(txt == c for c in STARTCHARS):
message.set_cmd_text(self._win_id, txt)
return self.Match.definitive
match = super()._handle_single_key(e)
if match == self.Match.partial:
timeout = config.get('input', 'partial-timeout')
if timeout != 0:
self._partial_timer.setInterval(timeout)
self._partial_timer.timeout.connect(self._clear_partial_match)
self._partial_timer.start()
return match
def set_inhibited_timeout(self, timeout):
if timeout != 0:
self._debug_log("Inhibiting the normal mode for {}ms.".format(
timeout))
self._inhibited = True
self._inhibited_timer.setInterval(timeout)
self._inhibited_timer.timeout.connect(self._clear_inhibited)
self._inhibited_timer.start()
@pyqtSlot()
def _clear_partial_match(self):
"""Clear a partial keystring after a timeout."""
self._debug_log("Clearing partial keystring {}".format(
self._keystring))
self._keystring = ''
self.keystring_updated.emit(self._keystring)
@pyqtSlot()
def _clear_inhibited(self):
"""Reset inhibition state after a timeout."""
self._debug_log("Releasing inhibition state of normal mode.")
self._inhibited = False
@pyqtSlot()
def _stop_timers(self):
super()._stop_timers()
self._partial_timer.stop()
try:
self._partial_timer.timeout.disconnect(self._clear_partial_match)
except TypeError:
# no connections
pass
self._inhibited_timer.stop()
try:
self._inhibited_timer.timeout.disconnect(self._clear_inhibited)
except TypeError:
# no connections
pass
class PromptKeyParser(keyparser.CommandKeyParser):
"""KeyParser for yes/no prompts."""
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=False,
supports_chains=True)
# We don't want an extra section for this in the config, so we just
# abuse the prompt section.
self.read_config('prompt')
def __repr__(self):
return utils.get_repr(self)
class HintKeyParser(keyparser.CommandKeyParser):
"""KeyChainParser for hints.
Attributes:
_filtertext: The text to filter with.
_last_press: The nature of the last keypress, a LastPress member.
"""
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=False,
supports_chains=True)
self._filtertext = ''
self._last_press = LastPress.none
self.read_config('hint')
self.keystring_updated.connect(self.on_keystring_updated)
def _handle_special_key(self, e):
"""Override _handle_special_key to handle string filtering.
Return True if the keypress has been handled, and False if not.
Args:
e: the KeyPressEvent from Qt.
Return:
True if event has been handled, False otherwise.
"""
log.keyboard.debug("Got special key 0x{:x} text {}".format(
e.key(), e.text()))
hintmanager = objreg.get('hintmanager', scope='tab',
window=self._win_id, tab='current')
if e.key() == Qt.Key_Backspace:
log.keyboard.debug("Got backspace, mode {}, filtertext '{}', "
"keystring '{}'".format(self._last_press,
self._filtertext,
self._keystring))
if self._last_press == LastPress.filtertext and self._filtertext:
self._filtertext = self._filtertext[:-1]
hintmanager.filter_hints(self._filtertext)
return True
elif self._last_press == LastPress.keystring and self._keystring:
self._keystring = self._keystring[:-1]
self.keystring_updated.emit(self._keystring)
if not self._keystring and self._filtertext:
# Switch back to hint filtering mode (this can happen only
# in numeric mode after the number has been deleted).
hintmanager.filter_hints(self._filtertext)
self._last_press = LastPress.filtertext
return True
else:
return super()._handle_special_key(e)
elif hintmanager.current_mode() != 'number':
return super()._handle_special_key(e)
elif not e.text():
return super()._handle_special_key(e)
else:
self._filtertext += e.text()
hintmanager.filter_hints(self._filtertext)
self._last_press = LastPress.filtertext
return True
def handle(self, e):
"""Handle a new keypress and call the respective handlers.
Args:
e: the KeyPressEvent from Qt
Returns:
True if the match has been handled, False otherwise.
"""
match = self._handle_single_key(e)
if match == self.Match.partial:
self.keystring_updated.emit(self._keystring)
self._last_press = LastPress.keystring
return True
elif match == self.Match.definitive:
self._last_press = LastPress.none
return True
elif match == self.Match.other:
pass
elif match == self.Match.none:
# We couldn't find a keychain so we check if it's a special key.
return self._handle_special_key(e)
else:
raise ValueError("Got invalid match type {}!".format(match))
def execute(self, cmdstr, keytype, count=None):
"""Handle a completed keychain."""
if not isinstance(keytype, self.Type):
raise TypeError("Type {} is no Type member!".format(keytype))
if keytype == self.Type.chain:
hintmanager = objreg.get('hintmanager', scope='tab',
window=self._win_id, tab='current')
hintmanager.fire(cmdstr)
else:
# execute as command
super().execute(cmdstr, keytype, count)
def update_bindings(self, strings, preserve_filter=False):
"""Update bindings when the hint strings changed.
Args:
strings: A list of hint strings.
preserve_filter: Whether to keep the current value of
`self._filtertext`.
"""
self.bindings = {s: s for s in strings}
if not preserve_filter:
self._filtertext = ''
@pyqtSlot(str)
def on_keystring_updated(self, keystr):
"""Update hintmanager when the keystring was updated."""
hintmanager = objreg.get('hintmanager', scope='tab',
window=self._win_id, tab='current')
hintmanager.handle_partial_key(keystr)
class CaretKeyParser(keyparser.CommandKeyParser):
"""KeyParser for caret mode."""
passthrough = True
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=True,
supports_chains=True)
self.read_config('caret')
class MarkKeyParser(keyparser.BaseKeyParser):
"""KeyParser for set_mark and jump_mark mode.
Attributes:
_mode: Either KeyMode.set_mark or KeyMode.jump_mark.
"""
def __init__(self, win_id, mode, parent=None):
super().__init__(win_id, parent, supports_count=False,
supports_chains=False)
self._mode = mode
def handle(self, e):
"""Override handle to always match the next key and create a mark.
Args:
e: the KeyPressEvent from Qt.
Return:
True if event has been handled, False otherwise.
"""
if utils.keyevent_to_string(e) is None:
# this is a modifier key, let it pass and keep going
return False
key = e.text()
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=self._win_id)
if self._mode == usertypes.KeyMode.set_mark:
tabbed_browser.set_mark(key)
elif self._mode == usertypes.KeyMode.jump_mark:
tabbed_browser.jump_mark(key)
else:
raise ValueError("{} is not a valid mark mode".format(self._mode))
self.request_leave.emit(self._mode, "valid mark key")
return True
@pyqtSlot(str)
def on_keyconfig_changed(self, mode):
"""MarkKeyParser has no config section (no bindable keys)."""
pass
def execute(self, cmdstr, _keytype, count=None):
"""Should never be called on MarkKeyParser."""
assert False
| 1 | 16,081 | I'm not sure if this is going to work - I think it's fine to keep them hardcoded here, as the statusbar can still show `:`, `/` and `?` even if the key is rebound. | qutebrowser-qutebrowser | py |
@@ -69,7 +69,6 @@ public abstract class TomcatServerBootstrap extends EmbeddedServerBootstrap {
.useLegacyLocalRepo(true).configureViaPlugin();
WebArchive wa = ShrinkWrap.create(WebArchive.class, "rest-test.war").setWebXML(webXmlPath)
- .addAsLibraries(resolver.resolve("org.codehaus.jackson:jackson-jaxrs:1.6.5").withTransitivity().asFile())
.addAsLibraries(resolver.addDependencies(
MavenDependencies.createDependency("org.mockito:mockito-core", ScopeType.TEST, false,
MavenDependencies.createExclusion("org.hamcrest:hamcrest-core"))).resolve() | 1 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.rest.util.container;
import java.io.File;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider;
import org.camunda.bpm.engine.rest.spi.impl.MockedProcessEngineProvider;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage;
import org.jboss.shrinkwrap.resolver.api.maven.ScopeType;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies;
public abstract class TomcatServerBootstrap extends EmbeddedServerBootstrap {
private Tomcat tomcat;
private String workingDir;
private String webXmlPath;
public TomcatServerBootstrap(String webXmlPath) {
this.webXmlPath = webXmlPath;
}
public void start() {
Properties serverProperties = readProperties();
int port = Integer.parseInt(serverProperties.getProperty(PORT_PROPERTY));
tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.setBaseDir(getWorkingDir());
tomcat.getHost().setAppBase(getWorkingDir());
tomcat.getHost().setAutoDeploy(true);
tomcat.getHost().setDeployOnStartup(true);
String contextPath = "/" + getContextPath();
// 1) Must not use shrinkwrap offline mode (see longer explanation at the end of the file)
// 2) Must use configuration via Shrinkwrap Maven plugin (see pom.xml for plugin definition);
// This forwards things like the location of the settings.xml file to Shrinkwrap. We need
// that for our CI where settings.xml is not in the default location.
PomEquippedResolveStage resolver = Maven.configureResolver()
.useLegacyLocalRepo(true).configureViaPlugin();
WebArchive wa = ShrinkWrap.create(WebArchive.class, "rest-test.war").setWebXML(webXmlPath)
.addAsLibraries(resolver.resolve("org.codehaus.jackson:jackson-jaxrs:1.6.5").withTransitivity().asFile())
.addAsLibraries(resolver.addDependencies(
MavenDependencies.createDependency("org.mockito:mockito-core", ScopeType.TEST, false,
MavenDependencies.createExclusion("org.hamcrest:hamcrest-core"))).resolve()
.withTransitivity().asFile())
.addAsServiceProvider(ProcessEngineProvider.class, MockedProcessEngineProvider.class)
.add(new ClassLoaderAsset("runtime/tomcat/context.xml"), "META-INF/context.xml")
.addPackages(true, "org.camunda.bpm.engine.rest");
addRuntimeSpecificLibraries(wa, resolver);
wa.setWebXML(webXmlPath);
String webAppPath = getWorkingDir() + "/" + getContextPath() + ".war";
wa.as(ZipExporter.class).exportTo(new File(webAppPath), true);
tomcat.addWebapp(tomcat.getHost(), contextPath, webAppPath);
try {
tomcat.start();
} catch (LifecycleException e) {
throw new RuntimeException(e);
}
}
protected abstract void addRuntimeSpecificLibraries(WebArchive wa, PomEquippedResolveStage resolver);
private String getContextPath() {
return "rest-test";
}
public void stop() {
try {
try {
tomcat.stop();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.WARNING, "Failed to stop tomcat instance", e);
}
try {
tomcat.destroy();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.WARNING, "Failed to destroy instance", e);
}
tomcat = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getWorkingDir() {
if (workingDir == null) {
workingDir = System.getProperty("java.io.tmpdir");
}
return workingDir;
}
public void setWorkingDir(String workingDir) {
this.workingDir = workingDir;
}
/*
* Must not use Shrinkwrap offline mode or else some Maven builds can fail. In particular, a
* Maven build will fail with offline mode in the following circumstances:
*
* - The BOM is part of the Maven reactor (e.g. if we build the root pom)
* - The Maven build does not install its modules (e.g. we run mvn clean verify)
* - There is no BOM snapshot in the local repository yet (this is mostly the case in CI)
*
* Why?
*
* - The BOM is imported in the dependencyManagement section of this pom (via camunda-parent)
* - As the BOM is part of the reactor, it will not be fetched from remote by the Maven build
* - As we do not run "install", Maven does not put the BOM into the local repository
* - Shrinkwrap will not be able to resolve the BOM then; note: this is different if a pom is referenced
* as a parent; in that case, Shrinkwrap will navigate the relativePaths towards the local pom
*
* Impact
*
* - By enabling remote fetching in Shrinkwrap, a remote snapshot BOM will be fetched in this case
* - While counter-intuitive, we consider this an ok solution; other solution options were disallowing
* "mvn clean verify" in these circumstances (and changing CI builds accordingly), or reverting the
* changes made in CAM-11345.
*
* This change was made with CAM-11345. See the discussion there for more details.
*/
}
| 1 | 11,630 | @tmetzke shouldn't we replace this library with the `2.12.1` instead of removing it? | camunda-camunda-bpm-platform | java |
@@ -40,10 +40,16 @@ type Miner struct {
// PeerID is the peer ID to set as the miners owner
PeerID string
- // Power is the amount of power this miner should start off with
+ // NumCommittedSectors is the number of sectors that this miner has
+ // committed to the network.
+ //
+ // TODO: This struct needs a field which represents the size of sectors
+ // that this miner has committed. For now, sector size is configured by
+ // the StorageMarketActor's ProofsMode.
+ //
// TODO: this will get more complicated when we actually have to
- // prove real files
- Power uint64
+ // prove real files.
+ NumCommittedSectors uint64
}
// GenesisCfg is | 1 | package gengen
import (
"context"
"fmt"
"io"
"math/big"
mrand "math/rand"
"strconv"
"github.com/filecoin-project/go-filecoin/actor"
"github.com/filecoin-project/go-filecoin/actor/builtin"
"github.com/filecoin-project/go-filecoin/actor/builtin/account"
"github.com/filecoin-project/go-filecoin/address"
"github.com/filecoin-project/go-filecoin/consensus"
"github.com/filecoin-project/go-filecoin/crypto"
"github.com/filecoin-project/go-filecoin/state"
"github.com/filecoin-project/go-filecoin/types"
"github.com/filecoin-project/go-filecoin/vm"
bserv "github.com/ipfs/go-blockservice"
"github.com/ipfs/go-car"
"github.com/ipfs/go-cid"
ds "github.com/ipfs/go-datastore"
"github.com/ipfs/go-hamt-ipld"
"github.com/ipfs/go-ipfs-blockstore"
"github.com/ipfs/go-ipfs-exchange-offline"
dag "github.com/ipfs/go-merkledag"
"github.com/libp2p/go-libp2p-peer"
mh "github.com/multiformats/go-multihash"
"github.com/pkg/errors"
)
// Miner is
type Miner struct {
// Owner is the name of the key that owns this miner
// It must be a name of a key from the configs 'Keys' list
Owner int
// PeerID is the peer ID to set as the miners owner
PeerID string
// Power is the amount of power this miner should start off with
// TODO: this will get more complicated when we actually have to
// prove real files
Power uint64
}
// GenesisCfg is
type GenesisCfg struct {
// Keys is an array of names of keys. A random key will be generated
// for each name here.
Keys int
// PreAlloc is a mapping from key names to string values of whole filecoin
// that will be preallocated to each account
PreAlloc []string
// Miners is a list of miners that should be set up at the start of the network
Miners []Miner
// ProofsMode affects sealing, sector packing, PoSt, etc. in the proofs library
ProofsMode types.ProofsMode
}
// RenderedGenInfo contains information about a genesis block creation
type RenderedGenInfo struct {
// Keys is the set of keys generated
Keys []*types.KeyInfo
// Miners is the list of addresses of miners created
Miners []RenderedMinerInfo
// GenesisCid is the cid of the created genesis block
GenesisCid cid.Cid
}
// RenderedMinerInfo contains info about a created miner
type RenderedMinerInfo struct {
// Owner is the key name of the owner of this miner
Owner int
// Address is the address generated on-chain for the miner
Address address.Address
// Power is the amount of storage power this miner was created with
Power uint64
}
// GenGen takes the genesis configuration and creates a genesis block that
// matches the description. It writes all chunks to the dagservice, and returns
// the final genesis block.
//
// WARNING: Do not use maps in this code, they will make this code non deterministic.
func GenGen(ctx context.Context, cfg *GenesisCfg, cst *hamt.CborIpldStore, bs blockstore.Blockstore, seed int64) (*RenderedGenInfo, error) {
pnrg := mrand.New(mrand.NewSource(seed))
keys, err := genKeys(cfg.Keys, pnrg)
if err != nil {
return nil, err
}
st := state.NewEmptyStateTreeWithActors(cst, builtin.Actors)
storageMap := vm.NewStorageMap(bs)
if err := consensus.SetupDefaultActors(ctx, st, storageMap, cfg.ProofsMode); err != nil {
return nil, err
}
if err := setupPrealloc(st, keys, cfg.PreAlloc); err != nil {
return nil, err
}
miners, err := setupMiners(st, storageMap, keys, cfg.Miners, pnrg)
if err != nil {
return nil, err
}
if err := cst.Blocks.AddBlock(types.StorageMarketActorCodeObj); err != nil {
return nil, err
}
if err := cst.Blocks.AddBlock(types.MinerActorCodeObj); err != nil {
return nil, err
}
if err := cst.Blocks.AddBlock(types.BootstrapMinerActorCodeObj); err != nil {
return nil, err
}
if err := cst.Blocks.AddBlock(types.AccountActorCodeObj); err != nil {
return nil, err
}
if err := cst.Blocks.AddBlock(types.PaymentBrokerActorCodeObj); err != nil {
return nil, err
}
stateRoot, err := st.Flush(ctx)
if err != nil {
return nil, err
}
err = storageMap.Flush()
if err != nil {
return nil, err
}
geneblk := &types.Block{
StateRoot: stateRoot,
}
c, err := cst.Put(ctx, geneblk)
if err != nil {
return nil, err
}
return &RenderedGenInfo{
Keys: keys,
GenesisCid: c,
Miners: miners,
}, nil
}
func genKeys(cfgkeys int, pnrg io.Reader) ([]*types.KeyInfo, error) {
keys := make([]*types.KeyInfo, cfgkeys)
for i := 0; i < cfgkeys; i++ {
sk, err := crypto.GenerateKeyFromSeed(pnrg) // TODO: GenerateKey should return a KeyInfo
if err != nil {
return nil, err
}
ki := &types.KeyInfo{
PrivateKey: sk,
Curve: types.SECP256K1,
}
keys[i] = ki
}
return keys, nil
}
func setupPrealloc(st state.Tree, keys []*types.KeyInfo, prealloc []string) error {
if len(keys) < len(prealloc) {
return fmt.Errorf("keys do not match prealloc")
}
for i, v := range prealloc {
ki := keys[i]
addr, err := ki.Address()
if err != nil {
return err
}
valint, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return err
}
act, err := account.NewActor(types.NewAttoFILFromFIL(valint))
if err != nil {
return err
}
if err := st.SetActor(context.Background(), addr, act); err != nil {
return err
}
}
netact, err := account.NewActor(types.NewAttoFILFromFIL(10000000000))
if err != nil {
return err
}
return st.SetActor(context.Background(), address.NetworkAddress, netact)
}
func setupMiners(st state.Tree, sm vm.StorageMap, keys []*types.KeyInfo, miners []Miner, pnrg io.Reader) ([]RenderedMinerInfo, error) {
var minfos []RenderedMinerInfo
ctx := context.Background()
for _, m := range miners {
addr, err := keys[m.Owner].Address()
if err != nil {
return nil, err
}
var pid peer.ID
if m.PeerID != "" {
p, err := peer.IDB58Decode(m.PeerID)
if err != nil {
return nil, err
}
pid = p
} else {
// this is just deterministically deriving from the owner
h, err := mh.Sum(addr.Bytes(), mh.SHA2_256, -1)
if err != nil {
return nil, err
}
pid = peer.ID(h)
}
// give collateral to account actor
_, err = applyMessageDirect(ctx, st, sm, address.NetworkAddress, addr, types.NewAttoFILFromFIL(100000), "")
if err != nil {
return nil, err
}
// create miner
pubkey := keys[m.Owner].PublicKey()
ret, err := applyMessageDirect(ctx, st, sm, addr, address.StorageMarketAddress, types.NewAttoFILFromFIL(100000), "createMiner", big.NewInt(10000), pubkey[:], pid)
if err != nil {
return nil, err
}
// get miner address
maddr, err := address.NewFromBytes(ret[0])
if err != nil {
return nil, err
}
minfos = append(minfos, RenderedMinerInfo{
Address: maddr,
Owner: m.Owner,
Power: m.Power,
})
// commit sector to add power
for i := uint64(0); i < m.Power; i++ {
// the following statement fakes out the behavior of the SectorBuilder.sectorIDNonce,
// which is initialized to 0 and incremented (for the first sector) to 1
sectorID := i + 1
commD := make([]byte, 32)
commR := make([]byte, 32)
commRStar := make([]byte, 32)
sealProof := make([]byte, types.TwoPoRepProofPartitions.ProofLen())
if _, err := pnrg.Read(commD[:]); err != nil {
return nil, err
}
if _, err := pnrg.Read(commR[:]); err != nil {
return nil, err
}
if _, err := pnrg.Read(commRStar[:]); err != nil {
return nil, err
}
if _, err := pnrg.Read(sealProof[:]); err != nil {
return nil, err
}
_, err := applyMessageDirect(ctx, st, sm, addr, maddr, types.NewAttoFILFromFIL(0), "commitSector", sectorID, commD, commR, commRStar, sealProof)
if err != nil {
return nil, err
}
}
}
return minfos, nil
}
// GenGenesisCar generates a car for the given genesis configuration
func GenGenesisCar(cfg *GenesisCfg, out io.Writer, seed int64) (*RenderedGenInfo, error) {
// TODO: these six lines are ugly. We can do better...
mds := ds.NewMapDatastore()
bstore := blockstore.NewBlockstore(mds)
offl := offline.Exchange(bstore)
blkserv := bserv.New(bstore, offl)
cst := &hamt.CborIpldStore{Blocks: blkserv}
dserv := dag.NewDAGService(blkserv)
ctx := context.Background()
info, err := GenGen(ctx, cfg, cst, bstore, seed)
if err != nil {
return nil, err
}
return info, car.WriteCar(ctx, dserv, []cid.Cid{info.GenesisCid}, out)
}
// applyMessageDirect applies a given message directly to the given state tree and storage map and returns the result of the message.
// This is a shortcut to allow gengen to use built-in actor functionality to alter the genesis block's state.
// Outside genesis, direct execution of actor code is a really bad idea.
func applyMessageDirect(ctx context.Context, st state.Tree, vms vm.StorageMap, from, to address.Address, value *types.AttoFIL, method string, params ...interface{}) ([][]byte, error) {
pdata := actor.MustConvertParams(params...)
msg := types.NewMessage(from, to, 0, value, method, pdata)
// this should never fail due to lack of gas since gas doesn't have meaning here
gasLimit := types.BlockGasLimit
smsg, err := types.NewSignedMessage(*msg, &signer{}, types.NewGasPrice(0), gasLimit)
if err != nil {
return nil, err
}
// create new processor that doesn't reward and doesn't validate
applier := consensus.NewConfiguredProcessor(&messageValidator{}, &blockRewarder{})
res, err := applier.ApplyMessagesAndPayRewards(ctx, st, vms, []*types.SignedMessage{smsg}, address.Undef, types.NewBlockHeight(0), nil)
if err != nil {
return nil, err
}
if len(res.Results) == 0 {
return nil, errors.New("GenGen message did not produce a result")
}
if res.Results[0].ExecutionError != nil {
return nil, res.Results[0].ExecutionError
}
return res.Results[0].Receipt.Return, nil
}
// GenGenMessageValidator is a validator that doesn't validate to simplify message creation in tests.
type messageValidator struct{}
var _ consensus.SignedMessageValidator = (*messageValidator)(nil)
// Validate always returns nil
func (ggmv *messageValidator) Validate(ctx context.Context, msg *types.SignedMessage, fromActor *actor.Actor) error {
return nil
}
// blockRewarder is a rewarder that doesn't actually add any rewards to simplify state tracking in tests
type blockRewarder struct{}
var _ consensus.BlockRewarder = (*blockRewarder)(nil)
// BlockReward is a noop
func (gbr *blockRewarder) BlockReward(ctx context.Context, st state.Tree, minerAddr address.Address) error {
return nil
}
// GasReward is a noop
func (gbr *blockRewarder) GasReward(ctx context.Context, st state.Tree, minerAddr address.Address, msg *types.SignedMessage, cost *types.AttoFIL) error {
return nil
}
// signer doesn't actually sign because it's not actually validated
type signer struct{}
var _ types.Signer = (*signer)(nil)
func (ggs *signer) SignBytes(data []byte, addr address.Address) (types.Signature, error) {
return nil, nil
}
| 1 | 19,248 | uint64 seems excessive here. Should we reduce to a uint32 @whyrusleeping ? | filecoin-project-venus | go |
@@ -109,7 +109,6 @@ type initStorageOpts struct {
ws wsAddonManager
store store
- app *config.Application
sel wsSelector
}
| 1 | // Copyright Amazon.com, Inc or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package cli
import (
"encoding"
"fmt"
"github.com/aws/copilot-cli/internal/pkg/addon"
"github.com/aws/copilot-cli/internal/pkg/config"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/aws/copilot-cli/internal/pkg/term/color"
"github.com/aws/copilot-cli/internal/pkg/term/log"
"github.com/aws/copilot-cli/internal/pkg/term/prompt"
"github.com/aws/copilot-cli/internal/pkg/term/selector"
"github.com/aws/copilot-cli/internal/pkg/workspace"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const (
dynamoDBStorageType = "DynamoDB"
s3StorageType = "S3"
)
const (
s3BucketFriendlyText = "S3 Bucket"
dynamoDBTableFriendlyText = "DynamoDB Table"
)
const (
ddbKeyString = "key"
)
var storageTypes = []string{
dynamoDBStorageType,
s3StorageType,
}
// General-purpose prompts, collected for all storage resources.
var (
fmtStorageInitTypePrompt = "What " + color.Emphasize("type") + " of storage would you like to associate with %s?"
storageInitTypeHelp = `The type of storage you'd like to add to your service.
DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale.
S3 is a web object store built to store and retrieve any amount of data from anywhere on the Internet.`
fmtStorageInitNamePrompt = "What would you like to " + color.Emphasize("name") + " this %s?"
storageInitNameHelp = "The name of this storage resource. You can use the following characters: a-zA-Z0-9-_"
storageInitSvcPrompt = "Which " + color.Emphasize("service") + " would you like to associate with this storage resource?"
storageInitSvcHelp = `The service you'd like to have access to this storage resource.
We'll deploy the resources for the storage when you run 'svc deploy'.`
)
// DDB-specific questions and help prompts.
var (
fmtStorageInitDDBKeyPrompt = "What would you like to name the %s of this %s?"
storageInitDDBPartitionKeyHelp = "The partition key of this table. This key, along with the sort key, will make up the primary key."
storageInitDDBSortKeyConfirm = "Would you like to add a sort key to this table?"
storageInitDDBSortKeyHelp = "The sort key of this table. Without a sort key, the partition key " + color.Emphasize("must") + ` be unique on the table.
You must specify a sort key if you wish to add alternate sort keys later.`
fmtStorageInitDDBKeyTypePrompt = "What datatype is this %s?"
fmtStorageInitDDBKeyTypeHelp = "The datatype to store in the %s. N is number, S is string, B is binary."
storageInitDDBLSIPrompt = "Would you like to add any alternate sort keys to this table?"
storageInitDDBLSIHelp = `Alternate sort keys create Local Secondary Indexes, which allow you to sort the table using the same
partition key but a different sort key. You may specify up to 5 alternate sort keys.`
storageInitDDBMoreLSIPrompt = "Would you like to add more alternate sort keys to this table?"
storageInitDDBLSINamePrompt = "What would you like to name this " + color.Emphasize("alternate sort key") + "?"
storageInitDDBLSINameHelp = "You can use the characters [a-zA-Z0-9.-_]"
)
const (
ddbStringType = "String"
ddbIntType = "Number"
ddbBinaryType = "Binary"
)
var attributeTypes = []string{
ddbStringType,
ddbIntType,
ddbBinaryType,
}
type initStorageVars struct {
*GlobalOpts
storageType string
storageName string
storageSvc string
// Dynamo DB specific values collected via flags or prompts
partitionKey string
sortKey string
lsiSorts []string // lsi sort keys collected as "name:T" where T is one of [SNB]
noLSI bool
noSort bool
}
type initStorageOpts struct {
initStorageVars
fs afero.Fs
ws wsAddonManager
store store
app *config.Application
sel wsSelector
}
func newStorageInitOpts(vars initStorageVars) (*initStorageOpts, error) {
store, err := config.NewStore()
if err != nil {
return nil, fmt.Errorf("new config store client: %w", err)
}
ws, err := workspace.New()
if err != nil {
return nil, fmt.Errorf("new workspace client: %w", err)
}
return &initStorageOpts{
initStorageVars: vars,
fs: &afero.Afero{Fs: afero.NewOsFs()},
store: store,
ws: ws,
sel: selector.NewWorkspaceSelect(vars.prompt, store, ws),
}, nil
}
func (o *initStorageOpts) Validate() error {
if o.AppName() == "" {
return errNoAppInWorkspace
}
if o.storageSvc != "" {
if err := o.validateServiceName(); err != nil {
return err
}
}
if o.storageType != "" {
if err := validateStorageType(o.storageType); err != nil {
return err
}
}
if o.storageName != "" {
var err error
switch o.storageType {
case dynamoDBStorageType:
err = dynamoTableNameValidation(o.storageName)
case s3StorageType:
err = s3BucketNameValidation(o.storageName)
default:
// use dynamo since it's a superset of s3
err = dynamoTableNameValidation(o.storageName)
}
if err != nil {
return err
}
}
if err := o.validateDDB(); err != nil {
return err
}
return nil
}
func (o *initStorageOpts) validateDDB() error {
if o.partitionKey != "" {
if err := validateKey(o.partitionKey); err != nil {
return err
}
}
if o.sortKey != "" {
if err := validateKey(o.sortKey); err != nil {
return err
}
}
// --no-lsi and --lsi are mutually exclusive.
if o.noLSI && len(o.lsiSorts) != 0 {
return fmt.Errorf("validate LSI configuration: cannot specify --no-lsi and --lsi options at once")
}
// --no-sort and --lsi are mutually exclusive.
if o.noSort && len(o.lsiSorts) != 0 {
return fmt.Errorf("validate LSI configuration: cannot specify --no-sort and --lsi options at once")
}
if len(o.lsiSorts) != 0 {
if err := validateLSIs(o.lsiSorts); err != nil {
return err
}
}
return nil
}
func (o *initStorageOpts) Ask() error {
if err := o.askStorageSvc(); err != nil {
return err
}
if err := o.askStorageType(); err != nil {
return err
}
if err := o.askStorageName(); err != nil {
return err
}
switch o.storageType {
case dynamoDBStorageType:
if err := o.askDynamoPartitionKey(); err != nil {
return err
}
if err := o.askDynamoSortKey(); err != nil {
return err
}
if err := o.askDynamoLSIConfig(); err != nil {
return err
}
}
return nil
}
func (o *initStorageOpts) askStorageType() error {
if o.storageType != "" {
return nil
}
storageType, err := o.prompt.SelectOne(fmt.Sprintf(
fmtStorageInitTypePrompt, color.HighlightUserInput(o.storageSvc)),
storageInitTypeHelp,
storageTypes,
prompt.WithFinalMessage("Storage type:"))
if err != nil {
return fmt.Errorf("select storage type: %w", err)
}
o.storageType = storageType
return nil
}
func (o *initStorageOpts) askStorageName() error {
if o.storageName != "" {
return nil
}
var validator func(interface{}) error
var friendlyText string
switch o.storageType {
case s3StorageType:
validator = s3BucketNameValidation
friendlyText = s3BucketFriendlyText
case dynamoDBStorageType:
validator = dynamoTableNameValidation
friendlyText = dynamoDBTableFriendlyText
}
name, err := o.prompt.Get(fmt.Sprintf(fmtStorageInitNamePrompt,
color.HighlightUserInput(friendlyText)),
storageInitNameHelp,
validator,
prompt.WithFinalMessage("Storage resource name:"))
if err != nil {
return fmt.Errorf("input storage name: %w", err)
}
o.storageName = name
return nil
}
func (o *initStorageOpts) askStorageSvc() error {
if o.storageSvc != "" {
return nil
}
svc, err := o.sel.Service(storageInitSvcPrompt,
storageInitSvcHelp,
)
if err != nil {
return fmt.Errorf("retrieve local service names: %w", err)
}
o.storageSvc = svc
return nil
}
func (o *initStorageOpts) askDynamoPartitionKey() error {
if o.partitionKey != "" {
return nil
}
keyPrompt := fmt.Sprintf(fmtStorageInitDDBKeyPrompt,
color.HighlightUserInput("partition key"),
color.HighlightUserInput(dynamoDBStorageType),
)
key, err := o.prompt.Get(keyPrompt,
storageInitDDBPartitionKeyHelp,
dynamoTableNameValidation,
prompt.WithFinalMessage("Partition key:"),
)
if err != nil {
return fmt.Errorf("get DDB partition key: %w", err)
}
keyTypePrompt := fmt.Sprintf(fmtStorageInitDDBKeyTypePrompt, ddbKeyString)
keyTypeHelp := fmt.Sprintf(fmtStorageInitDDBKeyTypeHelp, ddbKeyString)
keyType, err := o.prompt.SelectOne(keyTypePrompt,
keyTypeHelp,
attributeTypes,
prompt.WithFinalMessage("Partition key datatype:"),
)
if err != nil {
return fmt.Errorf("get DDB partition key datatype: %w", err)
}
o.partitionKey = key + ":" + keyType
return nil
}
func (o *initStorageOpts) askDynamoSortKey() error {
if o.sortKey != "" {
return nil
}
// If the user has not specified a sort key and has specified the --no-sort flag we don't have to demand it of them.
if o.noSort {
return nil
}
response, err := o.prompt.Confirm(storageInitDDBSortKeyConfirm, storageInitDDBSortKeyHelp, prompt.WithFinalMessage("Sort key?"))
if err != nil {
return fmt.Errorf("confirm DDB sort key: %w", err)
}
if !response {
o.noSort = true
return nil
}
keyPrompt := fmt.Sprintf(fmtStorageInitDDBKeyPrompt,
color.HighlightUserInput("sort key"),
color.HighlightUserInput(dynamoDBStorageType),
)
key, err := o.prompt.Get(keyPrompt,
storageInitDDBSortKeyHelp,
dynamoTableNameValidation,
prompt.WithFinalMessage("Sort key:"),
)
if err != nil {
return fmt.Errorf("get DDB sort key: %w", err)
}
keyTypePrompt := fmt.Sprintf(fmtStorageInitDDBKeyTypePrompt, ddbKeyString)
keyTypeHelp := fmt.Sprintf(fmtStorageInitDDBKeyTypeHelp, ddbKeyString)
keyType, err := o.prompt.SelectOne(keyTypePrompt,
keyTypeHelp,
attributeTypes,
prompt.WithFinalMessage("Sort key datatype:"),
)
if err != nil {
return fmt.Errorf("get DDB sort key datatype: %w", err)
}
o.sortKey = key + ":" + keyType
return nil
}
func (o *initStorageOpts) askDynamoLSIConfig() error {
// LSI has already been specified by flags.
if len(o.lsiSorts) > 0 {
return nil
}
// If --no-lsi has been specified, there is no need to ask for local secondary indices.
if o.noLSI {
return nil
}
// If --no-sort has been specified, there is no need to ask for local secondary indices.
if o.noSort {
o.noLSI = true
return nil
}
lsiTypePrompt := fmt.Sprintf(fmtStorageInitDDBKeyTypePrompt, color.Emphasize("alternate sort key"))
lsiTypeHelp := fmt.Sprintf(fmtStorageInitDDBKeyTypeHelp, "alternate sort key")
moreLSI, err := o.prompt.Confirm(storageInitDDBLSIPrompt, storageInitDDBLSIHelp, prompt.WithFinalMessage("Additional sort keys?"))
if err != nil {
return fmt.Errorf("confirm add alternate sort key: %w", err)
}
for {
if len(o.lsiSorts) > 5 {
log.Infoln("You may not specify more than 5 alternate sort keys. Continuing...")
moreLSI = false
}
// This will execute last in the loop if moreLSI is set to false by any confirm prompts.
if !moreLSI {
o.noLSI = len(o.lsiSorts) == 0
return nil
}
lsiName, err := o.prompt.Get(storageInitDDBLSINamePrompt,
storageInitDDBLSINameHelp,
dynamoTableNameValidation,
prompt.WithFinalMessage("Alternate Sort Key:"),
)
if err != nil {
return fmt.Errorf("get DDB alternate sort key name: %w", err)
}
lsiType, err := o.prompt.SelectOne(lsiTypePrompt,
lsiTypeHelp,
attributeTypes,
prompt.WithFinalMessage("Attribute type:"),
)
if err != nil {
return fmt.Errorf("get DDB alternate sort key type: %w", err)
}
o.lsiSorts = append(o.lsiSorts, lsiName+":"+lsiType)
moreLSI, err = o.prompt.Confirm(
storageInitDDBMoreLSIPrompt,
storageInitDDBLSIHelp,
prompt.WithFinalMessage("Additional sort keys?"),
)
if err != nil {
return fmt.Errorf("confirm add alternate sort key: %w", err)
}
}
}
func (o *initStorageOpts) validateServiceName() error {
names, err := o.ws.ServiceNames()
if err != nil {
return fmt.Errorf("retrieve local service names: %w", err)
}
for _, name := range names {
if o.storageSvc == name {
return nil
}
}
return fmt.Errorf("service %s not found in the workspace", o.storageSvc)
}
func (o *initStorageOpts) Execute() error {
return o.createAddon()
}
func (o *initStorageOpts) createAddon() error {
addonCf, err := o.newAddon()
if err != nil {
return err
}
addonPath, err := o.ws.WriteAddon(addonCf, o.storageSvc, o.storageName)
if err != nil {
e, ok := err.(*workspace.ErrFileExists)
if !ok {
return err
}
return fmt.Errorf("addon already exists: %w", e)
}
addonPath, err = relPath(addonPath)
if err != nil {
return err
}
addonMsgFmt := "Wrote CloudFormation template for %[1]s %[2]s at %[3]s\n"
var addonFriendlyText string
switch o.storageType {
case dynamoDBStorageType:
addonFriendlyText = dynamoDBTableFriendlyText
case s3StorageType:
addonFriendlyText = s3BucketFriendlyText
default:
return fmt.Errorf(fmtErrInvalidStorageType, o.storageType, prettify(storageTypes))
}
log.Successf(addonMsgFmt,
color.Emphasize(addonFriendlyText),
color.HighlightUserInput(o.storageName),
color.HighlightResource(addonPath),
)
log.Infoln(color.Help(`The Cloudformation template is a nested stack which fully describes your resource,
the IAM policy necessary for an ECS task to access that resource, and outputs
which are injected as environment variables into the Copilot service this addon
is associated with.`))
log.Infoln()
return nil
}
func (o *initStorageOpts) newAddon() (encoding.BinaryMarshaler, error) {
switch o.storageType {
case dynamoDBStorageType:
return o.newDynamoDBAddon()
case s3StorageType:
return o.newS3Addon()
default:
return nil, fmt.Errorf("storage type %s doesn't have a CF template", o.storageType)
}
}
func (o *initStorageOpts) newDynamoDBAddon() (*addon.DynamoDB, error) {
props := addon.DynamoDBProps{
StorageProps: &addon.StorageProps{
Name: o.storageName,
},
}
if err := props.BuildPartitionKey(o.partitionKey); err != nil {
return nil, err
}
hasSortKey, err := props.BuildSortKey(o.noSort, o.sortKey)
if err != nil {
return nil, err
}
if hasSortKey {
_, err := props.BuildLocalSecondaryIndex(o.noLSI, o.lsiSorts)
if err != nil {
return nil, err
}
}
return addon.NewDynamoDB(&props), nil
}
func (o *initStorageOpts) newS3Addon() (*addon.S3, error) {
props := &addon.S3Props{
StorageProps: &addon.StorageProps{
Name: o.storageName,
},
}
return addon.NewS3(props), nil
}
func (o *initStorageOpts) RecommendedActions() []string {
newVar := template.ToSnakeCaseFunc(template.EnvVarNameFunc(o.storageName))
svcDeployCmd := fmt.Sprintf("copilot svc deploy --name %s", o.storageSvc)
return []string{
fmt.Sprintf("Update your service code to leverage the injected environment variable %s", color.HighlightCode(newVar)),
fmt.Sprintf("Run %s to deploy your storage resources to your environments.", color.HighlightCode(svcDeployCmd)),
}
}
// BuildStorageInitCmd builds the command and adds it to the CLI.
func BuildStorageInitCmd() *cobra.Command {
vars := initStorageVars{
GlobalOpts: NewGlobalOpts(),
}
cmd := &cobra.Command{
Use: "init",
Short: "Creates a new storage config file in a service's addons directory.",
Long: `Creates a new storage config file in a service's addons directory.
Storage resources are deployed to your service's environments when you run
'copilot svc deploy'. Resource names are injected into your service containers as
environment variables for easy access.`,
Example: `
Create an S3 bucket named "my-bucket" attached to the "frontend" service.
/code $ copilot storage init -n my-bucket -t S3 -s frontend
Create a basic DynamoDB table named "my-table" attached to the "frontend" service with a sort key specified.
/code $ copilot storage init -n my-table -t DynamoDB -s frontend --partition-key Email:S --sort-key UserId:N --no-lsi
Create a DynamoDB table with multiple alternate sort keys.
/code $ copilot storage init -n my-table -t DynamoDB -s frontend --partition-key Email:S --sort-key UserId:N --lsi Points:N --lsi Goodness:N`,
RunE: runCmdE(func(cmd *cobra.Command, args []string) error {
opts, err := newStorageInitOpts(vars)
if err != nil {
return err
}
if err := opts.Validate(); err != nil {
return err
}
if err := opts.Ask(); err != nil {
return err
}
if err := opts.Execute(); err != nil {
return err
}
log.Infoln("Recommended follow-up actions:")
for _, followup := range opts.RecommendedActions() {
log.Infof("- %s\n", followup)
}
return nil
}),
}
cmd.Flags().StringVarP(&vars.storageName, nameFlag, nameFlagShort, "", storageFlagDescription)
cmd.Flags().StringVarP(&vars.storageType, storageTypeFlag, svcTypeFlagShort, "", storageTypeFlagDescription)
cmd.Flags().StringVarP(&vars.storageSvc, svcFlag, svcFlagShort, "", storageServiceFlagDescription)
cmd.Flags().StringVar(&vars.partitionKey, storagePartitionKeyFlag, "", storagePartitionKeyFlagDescription)
cmd.Flags().StringVar(&vars.sortKey, storageSortKeyFlag, "", storageSortKeyFlagDescription)
cmd.Flags().StringArrayVar(&vars.lsiSorts, storageLSIConfigFlag, []string{}, storageLSIConfigFlagDescription)
cmd.Flags().BoolVar(&vars.noLSI, storageNoLSIFlag, false, storageNoLSIFlagDescription)
cmd.Flags().BoolVar(&vars.noSort, storageNoSortFlag, false, storageNoSortFlagDescription)
requiredFlags := pflag.NewFlagSet("Required", pflag.ContinueOnError)
requiredFlags.AddFlag(cmd.Flags().Lookup(nameFlag))
requiredFlags.AddFlag(cmd.Flags().Lookup(storageTypeFlag))
requiredFlags.AddFlag(cmd.Flags().Lookup(svcFlag))
ddbFlags := pflag.NewFlagSet("DynamoDB", pflag.ContinueOnError)
ddbFlags.AddFlag(cmd.Flags().Lookup(storagePartitionKeyFlag))
ddbFlags.AddFlag(cmd.Flags().Lookup(storageSortKeyFlag))
ddbFlags.AddFlag(cmd.Flags().Lookup(storageNoSortFlag))
ddbFlags.AddFlag(cmd.Flags().Lookup(storageLSIConfigFlag))
ddbFlags.AddFlag(cmd.Flags().Lookup(storageNoLSIFlag))
cmd.Annotations = map[string]string{
// The order of the sections we want to display.
"sections": `Required,DynamoDB`,
"Required": requiredFlags.FlagUsages(),
"DynamoDB": ddbFlags.FlagUsages(),
}
cmd.SetUsageTemplate(`{{h1 "Usage"}}{{if .Runnable}}
{{.UseLine}}{{end}}{{$annotations := .Annotations}}{{$sections := split .Annotations.sections ","}}{{if gt (len $sections) 0}}
{{range $i, $sectionName := $sections}}{{h1 (print $sectionName " Flags")}}
{{(index $annotations $sectionName) | trimTrailingWhitespaces}}{{if ne (inc $i) (len $sections)}}
{{end}}{{end}}{{end}}{{if .HasAvailableInheritedFlags}}
{{h1 "Global Flags"}}
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasExample}}
{{h1 "Examples"}}{{code .Example}}{{end}}
`)
return cmd
}
| 1 | 14,687 | Hmm, I thought this was getting used. These are used elsewhere as a cached value (in `svc deploy` it's `o.targetApp`) but I guess since storage doesn't actually need to validate that the app exists, just that there are local services, we never used it. | aws-copilot-cli | go |
@@ -337,6 +337,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
+ // Get the remote host
+ remoteHost, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ remoteHost = r.RemoteAddr
+ }
+
if vh, ok := s.vhosts[host]; ok {
status, _ := vh.stack.ServeHTTP(w, r)
| 1 | // Package server implements a configurable, general-purpose web server.
// It relies on configurations obtained from the adjacent config package
// and can execute middleware as defined by the adjacent middleware package.
package server
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"runtime"
"sync"
"time"
"golang.org/x/net/http2"
)
// Server represents an instance of a server, which serves
// HTTP requests at a particular address (host and port). A
// server is capable of serving numerous virtual hosts on
// the same address and the listener may be stopped for
// graceful termination (POSIX only).
type Server struct {
*http.Server
HTTP2 bool // temporary while http2 is not in std lib (TODO: remove flag when part of std lib)
tls bool // whether this server is serving all HTTPS hosts or not
vhosts map[string]virtualHost // virtual hosts keyed by their address
listener ListenerFile // the listener which is bound to the socket
listenerMu sync.Mutex // protects listener
httpWg sync.WaitGroup // used to wait on outstanding connections
startChan chan struct{} // used to block until server is finished starting
connTimeout time.Duration // the maximum duration of a graceful shutdown
ReqCallback OptionalCallback // if non-nil, is executed at the beginning of every request
}
// ListenerFile represents a listener.
type ListenerFile interface {
net.Listener
File() (*os.File, error)
}
// OptionalCallback is a function that may or may not handle a request.
// It returns whether or not it handled the request. If it handled the
// request, it is presumed that no further request handling should occur.
type OptionalCallback func(http.ResponseWriter, *http.Request) bool
// New creates a new Server which will bind to addr and serve
// the sites/hosts configured in configs. Its listener will
// gracefully close when the server is stopped which will take
// no longer than gracefulTimeout.
//
// This function does not start serving.
//
// Do not re-use a server (start, stop, then start again). We
// could probably add more locking to make this possible, but
// as it stands, you should dispose of a server after stopping it.
// The behavior of serving with a spent server is undefined.
func New(addr string, configs []Config, gracefulTimeout time.Duration) (*Server, error) {
var tls bool
if len(configs) > 0 {
tls = configs[0].TLS.Enabled
}
s := &Server{
Server: &http.Server{
Addr: addr,
// TODO: Make these values configurable?
// ReadTimeout: 2 * time.Minute,
// WriteTimeout: 2 * time.Minute,
// MaxHeaderBytes: 1 << 16,
},
tls: tls,
vhosts: make(map[string]virtualHost),
startChan: make(chan struct{}),
connTimeout: gracefulTimeout,
}
s.Handler = s // this is weird, but whatever
// We have to bound our wg with one increment
// to prevent a "race condition" that is hard-coded
// into sync.WaitGroup.Wait() - basically, an add
// with a positive delta must be guaranteed to
// occur before Wait() is called on the wg.
// In a way, this kind of acts as a safety barrier.
s.httpWg.Add(1)
// Set up each virtualhost
for _, conf := range configs {
if _, exists := s.vhosts[conf.Host]; exists {
return nil, fmt.Errorf("cannot serve %s - host already defined for address %s", conf.Address(), s.Addr)
}
vh := virtualHost{config: conf}
// Build middleware stack
err := vh.buildStack()
if err != nil {
return nil, err
}
s.vhosts[conf.Host] = vh
}
return s, nil
}
// Serve starts the server with an existing listener. It blocks until the
// server stops.
func (s *Server) Serve(ln ListenerFile) error {
err := s.setup()
if err != nil {
defer close(s.startChan) // MUST defer so error is properly reported, same with all cases in this file
return err
}
return s.serve(ln)
}
// ListenAndServe starts the server with a new listener. It blocks until the server stops.
func (s *Server) ListenAndServe() error {
err := s.setup()
if err != nil {
defer close(s.startChan)
return err
}
ln, err := net.Listen("tcp", s.Addr)
if err != nil {
var succeeded bool
if runtime.GOOS == "windows" { // TODO: Limit this to Windows only? (it keeps sockets open after closing listeners)
for i := 0; i < 20; i++ {
time.Sleep(100 * time.Millisecond)
ln, err = net.Listen("tcp", s.Addr)
if err == nil {
succeeded = true
break
}
}
}
if !succeeded {
defer close(s.startChan)
return err
}
}
return s.serve(ln.(*net.TCPListener))
}
// serve prepares s to listen on ln by wrapping ln in a
// tcpKeepAliveListener (if ln is a *net.TCPListener) and
// then in a gracefulListener, so that keep-alive is supported
// as well as graceful shutdown/restart. It also configures
// TLS listener on top of that if applicable.
func (s *Server) serve(ln ListenerFile) error {
if tcpLn, ok := ln.(*net.TCPListener); ok {
ln = tcpKeepAliveListener{TCPListener: tcpLn}
}
s.listenerMu.Lock()
s.listener = newGracefulListener(ln, &s.httpWg)
s.listenerMu.Unlock()
if s.tls {
var tlsConfigs []TLSConfig
for _, vh := range s.vhosts {
tlsConfigs = append(tlsConfigs, vh.config.TLS)
}
return serveTLSWithSNI(s, s.listener, tlsConfigs)
}
close(s.startChan) // unblock anyone waiting for this to start listening
return s.Server.Serve(s.listener)
}
// setup prepares the server s to begin listening; it should be
// called just before the listener announces itself on the network
// and should only be called when the server is just starting up.
func (s *Server) setup() error {
if s.HTTP2 {
// TODO: This call may not be necessary after HTTP/2 is merged into std lib
http2.ConfigureServer(s.Server, nil)
}
// Execute startup functions now
for _, vh := range s.vhosts {
for _, startupFunc := range vh.config.Startup {
err := startupFunc()
if err != nil {
return err
}
}
}
return nil
}
// serveTLSWithSNI serves TLS with Server Name Indication (SNI) support, which allows
// multiple sites (different hostnames) to be served from the same address. It also
// supports client authentication if srv has it enabled. It blocks until s quits.
//
// This method is adapted from the std lib's net/http ServeTLS function, which was written
// by the Go Authors. It has been modified to support multiple certificate/key pairs,
// client authentication, and our custom Server type.
func serveTLSWithSNI(s *Server, ln net.Listener, tlsConfigs []TLSConfig) error {
config := cloneTLSConfig(s.TLSConfig)
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
// Here we diverge from the stdlib a bit by loading multiple certs/key pairs
// then we map the server names to their certs
var err error
config.Certificates = make([]tls.Certificate, len(tlsConfigs))
for i, tlsConfig := range tlsConfigs {
config.Certificates[i], err = tls.LoadX509KeyPair(tlsConfig.Certificate, tlsConfig.Key)
config.Certificates[i].OCSPStaple = tlsConfig.OCSPStaple
if err != nil {
defer close(s.startChan)
return err
}
}
config.BuildNameToCertificate()
// Customize our TLS configuration
config.MinVersion = tlsConfigs[0].ProtocolMinVersion
config.MaxVersion = tlsConfigs[0].ProtocolMaxVersion
config.CipherSuites = tlsConfigs[0].Ciphers
config.PreferServerCipherSuites = tlsConfigs[0].PreferServerCipherSuites
// TLS client authentication, if user enabled it
err = setupClientAuth(tlsConfigs, config)
if err != nil {
defer close(s.startChan)
return err
}
// Create TLS listener - note that we do not replace s.listener
// with this TLS listener; tls.listener is unexported and does
// not implement the File() method we need for graceful restarts
// on POSIX systems.
ln = tls.NewListener(ln, config)
close(s.startChan) // unblock anyone waiting for this to start listening
return s.Server.Serve(ln)
}
// Stop stops the server. It blocks until the server is
// totally stopped. On POSIX systems, it will wait for
// connections to close (up to a max timeout of a few
// seconds); on Windows it will close the listener
// immediately.
func (s *Server) Stop() (err error) {
s.Server.SetKeepAlivesEnabled(false)
if runtime.GOOS != "windows" {
// force connections to close after timeout
done := make(chan struct{})
go func() {
s.httpWg.Done() // decrement our initial increment used as a barrier
s.httpWg.Wait()
close(done)
}()
// Wait for remaining connections to finish or
// force them all to close after timeout
select {
case <-time.After(s.connTimeout):
case <-done:
}
}
// Close the listener now; this stops the server without delay
s.listenerMu.Lock()
if s.listener != nil {
err = s.listener.Close()
}
s.listenerMu.Unlock()
return
}
// WaitUntilStarted blocks until the server s is started, meaning
// that practically the next instruction is to start the server loop.
// It also unblocks if the server encounters an error during startup.
func (s *Server) WaitUntilStarted() {
<-s.startChan
}
// ListenerFd gets a dup'ed file of the listener. If there
// is no underlying file, the return value will be nil. It
// is the caller's responsibility to close the file.
func (s *Server) ListenerFd() *os.File {
s.listenerMu.Lock()
defer s.listenerMu.Unlock()
if s.listener != nil {
file, _ := s.listener.File()
return file
}
return nil
}
// ServeHTTP is the entry point for every request to the address that s
// is bound to. It acts as a multiplexer for the requests hostname as
// defined in the Host header so that the correct virtualhost
// (configuration and middleware stack) will handle the request.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
// In case the user doesn't enable error middleware, we still
// need to make sure that we stay alive up here
if rec := recover(); rec != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError)
}
}()
w.Header().Set("Server", "Caddy")
// Execute the optional request callback if it exists
if s.ReqCallback != nil && s.ReqCallback(w, r) {
return
}
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
host = r.Host // oh well
}
// Try the host as given, or try falling back to 0.0.0.0 (wildcard)
if _, ok := s.vhosts[host]; !ok {
if _, ok2 := s.vhosts["0.0.0.0"]; ok2 {
host = "0.0.0.0"
} else if _, ok2 := s.vhosts[""]; ok2 {
host = ""
}
}
if vh, ok := s.vhosts[host]; ok {
status, _ := vh.stack.ServeHTTP(w, r)
// Fallback error response in case error handling wasn't chained in
if status >= 400 {
DefaultErrorFunc(w, r, status)
}
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "No such host at %s", s.Server.Addr)
log.Printf("[INFO] %s - No such host at %s", host, s.Server.Addr)
}
}
// DefaultErrorFunc responds to an HTTP request with a simple description
// of the specified HTTP status code.
func DefaultErrorFunc(w http.ResponseWriter, r *http.Request, status int) {
w.WriteHeader(status)
fmt.Fprintf(w, "%d %s", status, http.StatusText(status))
}
// setupClientAuth sets up TLS client authentication only if
// any of the TLS configs specified at least one cert file.
func setupClientAuth(tlsConfigs []TLSConfig, config *tls.Config) error {
var clientAuth bool
for _, cfg := range tlsConfigs {
if len(cfg.ClientCerts) > 0 {
clientAuth = true
break
}
}
if clientAuth {
pool := x509.NewCertPool()
for _, cfg := range tlsConfigs {
for _, caFile := range cfg.ClientCerts {
caCrt, err := ioutil.ReadFile(caFile) // Anyone that gets a cert from this CA can connect
if err != nil {
return err
}
if !pool.AppendCertsFromPEM(caCrt) {
return fmt.Errorf("error loading client certificate '%s': no certificates were successfully parsed", caFile)
}
}
}
config.ClientCAs = pool
config.ClientAuth = tls.RequireAndVerifyClientCert
}
return nil
}
// RunFirstStartupFuncs runs all of the server's FirstStartup
// callback functions unless one of them returns an error first.
// It is the caller's responsibility to call this only once and
// at the correct time. The functions here should not be executed
// at restarts or where the user does not explicitly start a new
// instance of the server.
func (s *Server) RunFirstStartupFuncs() error {
for _, vh := range s.vhosts {
for _, f := range vh.config.FirstStartup {
if err := f(); err != nil {
return err
}
}
}
return nil
}
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
//
// Borrowed from the Go standard library.
type tcpKeepAliveListener struct {
*net.TCPListener
}
// Accept accepts the connection with a keep-alive enabled.
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
// File implements ListenerFile; returns the underlying file of the listener.
func (ln tcpKeepAliveListener) File() (*os.File, error) {
return ln.TCPListener.File()
}
// copied from net/http/transport.go
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return &tls.Config{
Rand: cfg.Rand,
Time: cfg.Time,
Certificates: cfg.Certificates,
NameToCertificate: cfg.NameToCertificate,
GetCertificate: cfg.GetCertificate,
RootCAs: cfg.RootCAs,
NextProtos: cfg.NextProtos,
ServerName: cfg.ServerName,
ClientAuth: cfg.ClientAuth,
ClientCAs: cfg.ClientCAs,
InsecureSkipVerify: cfg.InsecureSkipVerify,
CipherSuites: cfg.CipherSuites,
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
SessionTicketsDisabled: cfg.SessionTicketsDisabled,
SessionTicketKey: cfg.SessionTicketKey,
ClientSessionCache: cfg.ClientSessionCache,
MinVersion: cfg.MinVersion,
MaxVersion: cfg.MaxVersion,
CurvePreferences: cfg.CurvePreferences,
}
}
// ShutdownCallbacks executes all the shutdown callbacks
// for all the virtualhosts in servers, and returns all the
// errors generated during their execution. In other words,
// an error executing one shutdown callback does not stop
// execution of others. Only one shutdown callback is executed
// at a time. You must protect the servers that are passed in
// if they are shared across threads.
func ShutdownCallbacks(servers []*Server) []error {
var errs []error
for _, s := range servers {
for _, vhost := range s.vhosts {
for _, shutdownFunc := range vhost.config.Shutdown {
err := shutdownFunc()
if err != nil {
errs = append(errs, err)
}
}
}
}
return errs
}
| 1 | 7,614 | To keep it simple, how would you feel about just using r.RemoteAddr? Since every request comes through here I want it to be as lean as possible. Frankly I'm OK with the port showing up in the log; maybe it'd even be useful to someone. | caddyserver-caddy | go |
@@ -221,7 +221,13 @@ func (p *Protocol) GrantEpochReward(
}
// Reward additional bootstrap bonus
- if epochNum <= a.foundationBonusLastEpoch || (epochNum >= p.foundationBonusP2StartEpoch && epochNum <= p.foundationBonusP2EndEpoch) {
+ var grantFB bool
+ if a.hasFoundationBonusExtension() {
+ grantFB = a.grantFoundationBonus(epochNum)
+ } else {
+ grantFB = epochNum <= a.foundationBonusLastEpoch || (epochNum >= p.cfg.FoundationBonusP2StartEpoch && epochNum <= p.cfg.FoundationBonusP2EndEpoch)
+ }
+ if grantFB {
for i, count := 0, uint64(0); i < len(candidates) && count < a.numDelegatesForFoundationBonus; i++ {
if _, ok := exemptAddrs[candidates[i].Address]; ok {
continue | 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.
package rewarding
import (
"context"
"math/big"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-proto/golang/iotextypes"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/action/protocol"
accountutil "github.com/iotexproject/iotex-core/action/protocol/account/util"
"github.com/iotexproject/iotex-core/action/protocol/poll"
"github.com/iotexproject/iotex-core/action/protocol/rewarding/rewardingpb"
"github.com/iotexproject/iotex-core/action/protocol/rolldpos"
"github.com/iotexproject/iotex-core/pkg/enc"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/state"
)
// rewardHistory is the dummy struct to record a reward. Only key matters.
type rewardHistory struct{}
// Serialize serializes reward history state into bytes
func (b rewardHistory) Serialize() ([]byte, error) {
gen := rewardingpb.RewardHistory{}
return proto.Marshal(&gen)
}
// Deserialize deserializes bytes into reward history state
func (b *rewardHistory) Deserialize(data []byte) error { return nil }
// rewardHistory stores the unclaimed balance of an account
type rewardAccount struct {
balance *big.Int
}
// Serialize serializes account state into bytes
func (a rewardAccount) Serialize() ([]byte, error) {
gen := rewardingpb.Account{
Balance: a.balance.String(),
}
return proto.Marshal(&gen)
}
// Deserialize deserializes bytes into account state
func (a *rewardAccount) Deserialize(data []byte) error {
gen := rewardingpb.Account{}
if err := proto.Unmarshal(data, &gen); err != nil {
return err
}
balance, ok := big.NewInt(0).SetString(gen.Balance, 10)
if !ok {
return errors.New("failed to set reward account balance")
}
a.balance = balance
return nil
}
// GrantBlockReward grants the block reward (token) to the block producer
func (p *Protocol) GrantBlockReward(
ctx context.Context,
sm protocol.StateManager,
) (*action.Log, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
blkCtx := protocol.MustGetBlockCtx(ctx)
if err := p.assertNoRewardYet(ctx, sm, blockRewardHistoryKeyPrefix, blkCtx.BlockHeight); err != nil {
return nil, err
}
producerAddrStr := blkCtx.Producer.String()
rewardAddrStr := ""
pp := poll.FindProtocol(protocol.MustGetRegistry(ctx))
if pp != nil {
candidates, err := pp.Candidates(ctx, sm)
if err != nil {
return nil, err
}
for _, candidate := range candidates {
if candidate.Address == producerAddrStr {
rewardAddrStr = candidate.RewardAddress
break
}
}
}
// If reward address doesn't exist, do nothing
if rewardAddrStr == "" {
log.S().Debugf("Producer %s doesn't have a reward address", producerAddrStr)
return nil, nil
}
rewardAddr, err := address.FromString(rewardAddrStr)
a := admin{}
if _, err := p.state(ctx, sm, adminKey, &a); err != nil {
return nil, err
}
if err := p.updateAvailableBalance(ctx, sm, a.blockReward); err != nil {
return nil, err
}
if err != nil {
return nil, err
}
if err := p.grantToAccount(ctx, sm, rewardAddr, a.blockReward); err != nil {
return nil, err
}
if err := p.updateRewardHistory(ctx, sm, blockRewardHistoryKeyPrefix, blkCtx.BlockHeight); err != nil {
return nil, err
}
rewardLog := rewardingpb.RewardLog{
Type: rewardingpb.RewardLog_BLOCK_REWARD,
Addr: rewardAddrStr,
Amount: a.blockReward.String(),
}
data, err := proto.Marshal(&rewardLog)
if err != nil {
return nil, err
}
return &action.Log{
Address: p.addr.String(),
Topics: nil,
Data: data,
BlockHeight: blkCtx.BlockHeight,
ActionHash: actionCtx.ActionHash,
}, nil
}
// GrantEpochReward grants the epoch reward (token) to all beneficiaries of a epoch
func (p *Protocol) GrantEpochReward(
ctx context.Context,
sm protocol.StateManager,
) ([]*action.Log, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
blkCtx := protocol.MustGetBlockCtx(ctx)
featureWithHeightCtx := protocol.MustGetFeatureWithHeightCtx(ctx)
rp := rolldpos.MustGetProtocol(protocol.MustGetRegistry(ctx))
pp := poll.MustGetProtocol(protocol.MustGetRegistry(ctx))
epochNum := rp.GetEpochNum(blkCtx.BlockHeight)
if err := p.assertNoRewardYet(ctx, sm, epochRewardHistoryKeyPrefix, epochNum); err != nil {
return nil, err
}
if err := p.assertLastBlockInEpoch(blkCtx.BlockHeight, epochNum, rp); err != nil {
return nil, err
}
a := admin{}
if _, err := p.state(ctx, sm, adminKey, &a); err != nil {
return nil, err
}
// Get the delegate list who exempts epoch reward
e := exempt{}
if _, err := p.state(ctx, sm, exemptKey, &e); err != nil {
return nil, err
}
exemptAddrs := make(map[string]interface{})
for _, addr := range e.addrs {
exemptAddrs[addr.String()] = nil
}
var err error
uqdMap := make(map[string]bool)
epochStartHeight := rp.GetEpochHeight(epochNum)
if featureWithHeightCtx.GetUnproductiveDelegates(epochStartHeight) {
// Get unqualified delegate list
uqd, err := pp.CalculateUnproductiveDelegates(ctx, sm)
if err != nil {
return nil, err
}
for _, addr := range uqd {
uqdMap[addr] = true
}
}
candidates, err := poll.MustGetProtocol(protocol.MustGetRegistry(ctx)).Candidates(ctx, sm)
if err != nil {
return nil, err
}
addrs, amounts, err := p.splitEpochReward(epochStartHeight, sm, candidates, a.epochReward, a.numDelegatesForEpochReward, exemptAddrs, uqdMap)
if err != nil {
return nil, err
}
actualTotalReward := big.NewInt(0)
rewardLogs := make([]*action.Log, 0)
for i := range addrs {
// If reward address doesn't exist, do nothing
if addrs[i] == nil {
continue
}
// If 0 epoch reward due to low productivity, do nothing
if amounts[i].Cmp(big.NewInt(0)) == 0 {
continue
}
if err := p.grantToAccount(ctx, sm, addrs[i], amounts[i]); err != nil {
return nil, err
}
rewardLog := rewardingpb.RewardLog{
Type: rewardingpb.RewardLog_EPOCH_REWARD,
Addr: addrs[i].String(),
Amount: amounts[i].String(),
}
data, err := proto.Marshal(&rewardLog)
if err != nil {
return nil, err
}
rewardLogs = append(rewardLogs, &action.Log{
Address: p.addr.String(),
Topics: nil,
Data: data,
BlockHeight: blkCtx.BlockHeight,
ActionHash: actionCtx.ActionHash,
})
actualTotalReward = big.NewInt(0).Add(actualTotalReward, amounts[i])
}
// Reward additional bootstrap bonus
if epochNum <= a.foundationBonusLastEpoch || (epochNum >= p.foundationBonusP2StartEpoch && epochNum <= p.foundationBonusP2EndEpoch) {
for i, count := 0, uint64(0); i < len(candidates) && count < a.numDelegatesForFoundationBonus; i++ {
if _, ok := exemptAddrs[candidates[i].Address]; ok {
continue
}
if candidates[i].Votes.Cmp(big.NewInt(0)) == 0 {
// hard probation
continue
}
count++
// If reward address doesn't exist, do nothing
if candidates[i].RewardAddress == "" {
log.S().Warnf("Candidate %s doesn't have a reward address", candidates[i].Address)
continue
}
rewardAddr, err := address.FromString(candidates[i].RewardAddress)
if err != nil {
return nil, err
}
if err := p.grantToAccount(ctx, sm, rewardAddr, a.foundationBonus); err != nil {
return nil, err
}
rewardLog := rewardingpb.RewardLog{
Type: rewardingpb.RewardLog_FOUNDATION_BONUS,
Addr: candidates[i].RewardAddress,
Amount: a.foundationBonus.String(),
}
data, err := proto.Marshal(&rewardLog)
if err != nil {
return nil, err
}
rewardLogs = append(rewardLogs, &action.Log{
Address: p.addr.String(),
Topics: nil,
Data: data,
BlockHeight: blkCtx.BlockHeight,
ActionHash: actionCtx.ActionHash,
})
actualTotalReward = big.NewInt(0).Add(actualTotalReward, a.foundationBonus)
}
}
// Update actual reward
if err := p.updateAvailableBalance(ctx, sm, actualTotalReward); err != nil {
return nil, err
}
if err := p.updateRewardHistory(ctx, sm, epochRewardHistoryKeyPrefix, epochNum); err != nil {
return nil, err
}
return rewardLogs, nil
}
// Claim claims the token from the rewarding fund
func (p *Protocol) Claim(
ctx context.Context,
sm protocol.StateManager,
amount *big.Int,
) (*action.TransactionLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
if err := p.assertAmount(amount); err != nil {
return nil, err
}
if err := p.updateTotalBalance(ctx, sm, amount); err != nil {
return nil, err
}
if err := p.claimFromAccount(ctx, sm, actionCtx.Caller, amount); err != nil {
return nil, err
}
return &action.TransactionLog{
Type: iotextypes.TransactionLogType_CLAIM_FROM_REWARDING_FUND,
Sender: address.RewardingPoolAddr,
Recipient: actionCtx.Caller.String(),
Amount: amount,
}, nil
}
// UnclaimedBalance returns unclaimed balance of a given address
func (p *Protocol) UnclaimedBalance(
ctx context.Context,
sm protocol.StateReader,
addr address.Address,
) (*big.Int, uint64, error) {
acc := rewardAccount{}
accKey := append(adminKey, addr.Bytes()...)
height, err := p.state(ctx, sm, accKey, &acc)
if err == nil {
return acc.balance, height, nil
}
if errors.Cause(err) == state.ErrStateNotExist {
return big.NewInt(0), height, nil
}
return nil, height, err
}
func (p *Protocol) updateTotalBalance(ctx context.Context, sm protocol.StateManager, amount *big.Int) error {
f := fund{}
if _, err := p.state(ctx, sm, fundKey, &f); err != nil {
return err
}
totalBalance := big.NewInt(0).Sub(f.totalBalance, amount)
if totalBalance.Cmp(big.NewInt(0)) < 0 {
return errors.New("no enough total balance")
}
f.totalBalance = totalBalance
return p.putState(ctx, sm, fundKey, &f)
}
func (p *Protocol) updateAvailableBalance(ctx context.Context, sm protocol.StateManager, amount *big.Int) error {
f := fund{}
if _, err := p.state(ctx, sm, fundKey, &f); err != nil {
return err
}
availableBalance := big.NewInt(0).Sub(f.unclaimedBalance, amount)
if availableBalance.Cmp(big.NewInt(0)) < 0 {
return errors.New("no enough available balance")
}
f.unclaimedBalance = availableBalance
return p.putState(ctx, sm, fundKey, &f)
}
func (p *Protocol) grantToAccount(ctx context.Context, sm protocol.StateManager, addr address.Address, amount *big.Int) error {
acc := rewardAccount{}
accKey := append(adminKey, addr.Bytes()...)
_, fromLegacy, err := p.stateCheckLegacy(ctx, sm, accKey, &acc)
if err != nil {
if errors.Cause(err) != state.ErrStateNotExist {
return err
}
acc = rewardAccount{
balance: big.NewInt(0),
}
} else {
// entry exist
// check if from legacy, and we have started using v2, delete v1
if fromLegacy && useV2Storage(ctx) {
if err := p.deleteStateV1(sm, accKey); err != nil {
return err
}
}
}
acc.balance = big.NewInt(0).Add(acc.balance, amount)
return p.putState(ctx, sm, accKey, &acc)
}
func (p *Protocol) claimFromAccount(ctx context.Context, sm protocol.StateManager, addr address.Address, amount *big.Int) error {
// Update reward account
acc := rewardAccount{}
accKey := append(adminKey, addr.Bytes()...)
_, fromLegacy, err := p.stateCheckLegacy(ctx, sm, accKey, &acc)
if err != nil {
return err
}
balance := big.NewInt(0).Sub(acc.balance, amount)
if balance.Cmp(big.NewInt(0)) < 0 {
return errors.New("no enough available balance")
}
// TODO: we may want to delete the account when the unclaimed balance becomes 0
acc.balance = balance
if err := p.putState(ctx, sm, accKey, &acc); err != nil {
return err
}
if fromLegacy && useV2Storage(ctx) {
if err := p.deleteStateV1(sm, accKey); err != nil {
return err
}
}
// Update primary account
primAcc, err := accountutil.LoadOrCreateAccount(sm, addr.String())
if err != nil {
return err
}
primAcc.Balance = big.NewInt(0).Add(primAcc.Balance, amount)
return accountutil.StoreAccount(sm, addr, primAcc)
}
func (p *Protocol) updateRewardHistory(ctx context.Context, sm protocol.StateManager, prefix []byte, index uint64) error {
var indexBytes [8]byte
enc.MachineEndian.PutUint64(indexBytes[:], index)
return p.putState(ctx, sm, append(prefix, indexBytes[:]...), &rewardHistory{})
}
func (p *Protocol) splitEpochReward(
epochStartHeight uint64,
sm protocol.StateManager,
candidates []*state.Candidate,
totalAmount *big.Int,
numDelegatesForEpochReward uint64,
exemptAddrs map[string]interface{},
uqd map[string]bool,
) ([]address.Address, []*big.Int, error) {
filteredCandidates := make([]*state.Candidate, 0)
for _, candidate := range candidates {
if _, ok := exemptAddrs[candidate.Address]; ok {
continue
}
filteredCandidates = append(filteredCandidates, candidate)
}
candidates = filteredCandidates
if len(candidates) == 0 {
return nil, nil, nil
}
// We at most allow numDelegatesForEpochReward delegates to get the epoch reward
if uint64(len(candidates)) > numDelegatesForEpochReward {
candidates = candidates[:numDelegatesForEpochReward]
}
totalWeight := big.NewInt(0)
rewardAddrs := make([]address.Address, 0)
for _, candidate := range candidates {
var rewardAddr address.Address
var err error
if candidate.RewardAddress != "" {
rewardAddr, err = address.FromString(candidate.RewardAddress)
if err != nil {
return nil, nil, err
}
} else {
log.S().Warnf("Candidate %s doesn't have a reward address", candidate.Address)
}
rewardAddrs = append(rewardAddrs, rewardAddr)
totalWeight = big.NewInt(0).Add(totalWeight, candidate.Votes)
}
amounts := make([]*big.Int, 0)
var amountPerAddr *big.Int
for _, candidate := range candidates {
if totalWeight.Cmp(big.NewInt(0)) == 0 {
amounts = append(amounts, big.NewInt(0))
continue
}
if _, ok := uqd[candidate.Address]; ok {
// Before Easter, if not qualified, skip the epoch reward
amounts = append(amounts, big.NewInt(0))
continue
}
amountPerAddr = big.NewInt(0).Div(big.NewInt(0).Mul(totalAmount, candidate.Votes), totalWeight)
amounts = append(amounts, amountPerAddr)
}
return rewardAddrs, amounts, nil
}
func (p *Protocol) assertNoRewardYet(ctx context.Context, sm protocol.StateManager, prefix []byte, index uint64) error {
history := rewardHistory{}
var indexBytes [8]byte
enc.MachineEndian.PutUint64(indexBytes[:], index)
_, err := p.state(ctx, sm, append(prefix, indexBytes[:]...), &history)
if err == nil {
return errors.Errorf("reward history already exists on index %d", index)
}
if errors.Cause(err) != state.ErrStateNotExist {
return err
}
return nil
}
func (p *Protocol) assertLastBlockInEpoch(blkHeight uint64, epochNum uint64, rp *rolldpos.Protocol) error {
lastBlkHeight := rp.GetEpochLastBlockHeight(epochNum)
if blkHeight != lastBlkHeight {
return errors.Errorf("current block %d is not the last block of epoch %d", blkHeight, epochNum)
}
return nil
}
| 1 | 23,731 | grant bonus depends on both `admin{}` stored in statedb, and `P2Start/End` in local struct, which is kind of weird at Kamchatka height, we add the bonus Start/End epoch into `admin{}`, so it solely depends on `admin{}` stored in statedb | iotexproject-iotex-core | go |
@@ -222,8 +222,7 @@ class RandomFlip(object):
flipped[..., 1::4] = h - bboxes[..., 3::4]
flipped[..., 3::4] = h - bboxes[..., 1::4]
else:
- raise ValueError(
- 'Invalid flipping direction "{}"'.format(direction))
+ raise ValueError(f'Invalid flipping direction "{direction}"')
return flipped
def __call__(self, results): | 1 | import inspect
import mmcv
import numpy as np
from numpy import random
from mmdet.core import PolygonMasks
from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps
from ..builder import PIPELINES
try:
from imagecorruptions import corrupt
except ImportError:
corrupt = None
try:
import albumentations
from albumentations import Compose
except ImportError:
albumentations = None
Compose = None
@PIPELINES.register_module
class Resize(object):
"""Resize images & bbox & mask.
This transform resizes the input image to some scale. Bboxes and masks are
then resized with the same scale factor. If the input dict contains the key
"scale", then the scale in the input dict is used, otherwise the specified
scale in the init method is used.
`img_scale` can either be a tuple (single-scale) or a list of tuple
(multi-scale). There are 3 multiscale modes:
- `ratio_range` is not None: randomly sample a ratio from the ratio range
and multiply it with the image scale.
- `ratio_range` is None and `multiscale_mode` == "range": randomly sample a
scale from the a range.
- `ratio_range` is None and `multiscale_mode` == "value": randomly sample a
scale from multiple scales.
Args:
img_scale (tuple or list[tuple]): Images scales for resizing.
multiscale_mode (str): Either "range" or "value".
ratio_range (tuple[float]): (min_ratio, max_ratio)
keep_ratio (bool): Whether to keep the aspect ratio when resizing the
image.
"""
def __init__(self,
img_scale=None,
multiscale_mode='range',
ratio_range=None,
keep_ratio=True):
if img_scale is None:
self.img_scale = None
else:
if isinstance(img_scale, list):
self.img_scale = img_scale
else:
self.img_scale = [img_scale]
assert mmcv.is_list_of(self.img_scale, tuple)
if ratio_range is not None:
# mode 1: given a scale and a range of image ratio
assert len(self.img_scale) == 1
else:
# mode 2: given multiple scales or a range of scales
assert multiscale_mode in ['value', 'range']
self.multiscale_mode = multiscale_mode
self.ratio_range = ratio_range
self.keep_ratio = keep_ratio
@staticmethod
def random_select(img_scales):
assert mmcv.is_list_of(img_scales, tuple)
scale_idx = np.random.randint(len(img_scales))
img_scale = img_scales[scale_idx]
return img_scale, scale_idx
@staticmethod
def random_sample(img_scales):
assert mmcv.is_list_of(img_scales, tuple) and len(img_scales) == 2
img_scale_long = [max(s) for s in img_scales]
img_scale_short = [min(s) for s in img_scales]
long_edge = np.random.randint(
min(img_scale_long),
max(img_scale_long) + 1)
short_edge = np.random.randint(
min(img_scale_short),
max(img_scale_short) + 1)
img_scale = (long_edge, short_edge)
return img_scale, None
@staticmethod
def random_sample_ratio(img_scale, ratio_range):
assert isinstance(img_scale, tuple) and len(img_scale) == 2
min_ratio, max_ratio = ratio_range
assert min_ratio <= max_ratio
ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio
scale = int(img_scale[0] * ratio), int(img_scale[1] * ratio)
return scale, None
def _random_scale(self, results):
if self.ratio_range is not None:
scale, scale_idx = self.random_sample_ratio(
self.img_scale[0], self.ratio_range)
elif len(self.img_scale) == 1:
scale, scale_idx = self.img_scale[0], 0
elif self.multiscale_mode == 'range':
scale, scale_idx = self.random_sample(self.img_scale)
elif self.multiscale_mode == 'value':
scale, scale_idx = self.random_select(self.img_scale)
else:
raise NotImplementedError
results['scale'] = scale
results['scale_idx'] = scale_idx
def _resize_img(self, results):
if self.keep_ratio:
img, scale_factor = mmcv.imrescale(
results['img'], results['scale'], return_scale=True)
# the w_scale and h_scale has minor difference
# a real fix should be done in the mmcv.imrescale in the future
new_h, new_w = img.shape[:2]
h, w = results['img'].shape[:2]
w_scale = new_w / w
h_scale = new_h / h
else:
img, w_scale, h_scale = mmcv.imresize(
results['img'], results['scale'], return_scale=True)
scale_factor = np.array([w_scale, h_scale, w_scale, h_scale],
dtype=np.float32)
results['img'] = img
results['img_shape'] = img.shape
results['pad_shape'] = img.shape # in case that there is no padding
results['scale_factor'] = scale_factor
results['keep_ratio'] = self.keep_ratio
def _resize_bboxes(self, results):
img_shape = results['img_shape']
for key in results.get('bbox_fields', []):
bboxes = results[key] * results['scale_factor']
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
results[key] = bboxes
def _resize_masks(self, results):
for key in results.get('mask_fields', []):
if results[key] is None:
continue
if self.keep_ratio:
results[key] = results[key].rescale(results['scale'])
else:
results[key] = results[key].resize(results['img_shape'][:2])
def _resize_seg(self, results):
for key in results.get('seg_fields', []):
if self.keep_ratio:
gt_seg = mmcv.imrescale(
results[key], results['scale'], interpolation='nearest')
else:
gt_seg = mmcv.imresize(
results[key], results['scale'], interpolation='nearest')
results['gt_semantic_seg'] = gt_seg
def __call__(self, results):
if 'scale' not in results:
self._random_scale(results)
self._resize_img(results)
self._resize_bboxes(results)
self._resize_masks(results)
self._resize_seg(results)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += ('(img_scale={}, multiscale_mode={}, ratio_range={}, '
'keep_ratio={})').format(self.img_scale,
self.multiscale_mode,
self.ratio_range,
self.keep_ratio)
return repr_str
@PIPELINES.register_module
class RandomFlip(object):
"""Flip the image & bbox & mask.
If the input dict contains the key "flip", then the flag will be used,
otherwise it will be randomly decided by a ratio specified in the init
method.
Args:
flip_ratio (float, optional): The flipping probability.
"""
def __init__(self, flip_ratio=None, direction='horizontal'):
self.flip_ratio = flip_ratio
self.direction = direction
if flip_ratio is not None:
assert flip_ratio >= 0 and flip_ratio <= 1
assert direction in ['horizontal', 'vertical']
def bbox_flip(self, bboxes, img_shape, direction):
"""Flip bboxes horizontally.
Args:
bboxes(ndarray): shape (..., 4*k)
img_shape(tuple): (height, width)
"""
assert bboxes.shape[-1] % 4 == 0
flipped = bboxes.copy()
if direction == 'horizontal':
w = img_shape[1]
flipped[..., 0::4] = w - bboxes[..., 2::4]
flipped[..., 2::4] = w - bboxes[..., 0::4]
elif direction == 'vertical':
h = img_shape[0]
flipped[..., 1::4] = h - bboxes[..., 3::4]
flipped[..., 3::4] = h - bboxes[..., 1::4]
else:
raise ValueError(
'Invalid flipping direction "{}"'.format(direction))
return flipped
def __call__(self, results):
if 'flip' not in results:
flip = True if np.random.rand() < self.flip_ratio else False
results['flip'] = flip
if 'flip_direction' not in results:
results['flip_direction'] = self.direction
if results['flip']:
# flip image
results['img'] = mmcv.imflip(
results['img'], direction=results['flip_direction'])
# flip bboxes
for key in results.get('bbox_fields', []):
results[key] = self.bbox_flip(results[key],
results['img_shape'],
results['flip_direction'])
# flip masks
for key in results.get('mask_fields', []):
results[key] = results[key].flip(results['flip_direction'])
# flip segs
for key in results.get('seg_fields', []):
results[key] = mmcv.imflip(
results[key], direction=results['flip_direction'])
return results
def __repr__(self):
return self.__class__.__name__ + '(flip_ratio={})'.format(
self.flip_ratio)
@PIPELINES.register_module
class Pad(object):
"""Pad the image & mask.
There are two padding modes: (1) pad to a fixed size and (2) pad to the
minimum size that is divisible by some number.
Args:
size (tuple, optional): Fixed padding size.
size_divisor (int, optional): The divisor of padded size.
pad_val (float, optional): Padding value, 0 by default.
"""
def __init__(self, size=None, size_divisor=None, pad_val=0):
self.size = size
self.size_divisor = size_divisor
self.pad_val = pad_val
# only one of size and size_divisor should be valid
assert size is not None or size_divisor is not None
assert size is None or size_divisor is None
def _pad_img(self, results):
if self.size is not None:
padded_img = mmcv.impad(results['img'], self.size, self.pad_val)
elif self.size_divisor is not None:
padded_img = mmcv.impad_to_multiple(
results['img'], self.size_divisor, pad_val=self.pad_val)
results['img'] = padded_img
results['pad_shape'] = padded_img.shape
results['pad_fixed_size'] = self.size
results['pad_size_divisor'] = self.size_divisor
def _pad_masks(self, results):
pad_shape = results['pad_shape'][:2]
for key in results.get('mask_fields', []):
results[key] = results[key].pad(
pad_shape[:2], pad_val=self.pad_val)
def _pad_seg(self, results):
for key in results.get('seg_fields', []):
results[key] = mmcv.impad(results[key], results['pad_shape'][:2])
def __call__(self, results):
self._pad_img(results)
self._pad_masks(results)
self._pad_seg(results)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += '(size={}, size_divisor={}, pad_val={})'.format(
self.size, self.size_divisor, self.pad_val)
return repr_str
@PIPELINES.register_module
class Normalize(object):
"""Normalize the image.
Args:
mean (sequence): Mean values of 3 channels.
std (sequence): Std values of 3 channels.
to_rgb (bool): Whether to convert the image from BGR to RGB,
default is true.
"""
def __init__(self, mean, std, to_rgb=True):
self.mean = np.array(mean, dtype=np.float32)
self.std = np.array(std, dtype=np.float32)
self.to_rgb = to_rgb
def __call__(self, results):
results['img'] = mmcv.imnormalize(results['img'], self.mean, self.std,
self.to_rgb)
results['img_norm_cfg'] = dict(
mean=self.mean, std=self.std, to_rgb=self.to_rgb)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += '(mean={}, std={}, to_rgb={})'.format(
self.mean, self.std, self.to_rgb)
return repr_str
@PIPELINES.register_module
class RandomCrop(object):
"""Random crop the image & bboxes & masks.
Args:
crop_size (tuple): Expected size after cropping, (h, w).
"""
def __init__(self, crop_size):
self.crop_size = crop_size
def __call__(self, results):
img = results['img']
margin_h = max(img.shape[0] - self.crop_size[0], 0)
margin_w = max(img.shape[1] - self.crop_size[1], 0)
offset_h = np.random.randint(0, margin_h + 1)
offset_w = np.random.randint(0, margin_w + 1)
crop_y1, crop_y2 = offset_h, offset_h + self.crop_size[0]
crop_x1, crop_x2 = offset_w, offset_w + self.crop_size[1]
# crop the image
img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]
img_shape = img.shape
results['img'] = img
results['img_shape'] = img_shape
# crop bboxes accordingly and clip to the image boundary
for key in results.get('bbox_fields', []):
bbox_offset = np.array([offset_w, offset_h, offset_w, offset_h],
dtype=np.float32)
bboxes = results[key] - bbox_offset
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
results[key] = bboxes
# crop semantic seg
for key in results.get('seg_fields', []):
results[key] = results[key][crop_y1:crop_y2, crop_x1:crop_x2]
# filter out the gt bboxes that are completely cropped
if 'gt_bboxes' in results:
gt_bboxes = results['gt_bboxes']
valid_inds = (gt_bboxes[:, 2] > gt_bboxes[:, 0]) & (
gt_bboxes[:, 3] > gt_bboxes[:, 1])
# if no gt bbox remains after cropping, just skip this image
if not np.any(valid_inds):
return None
results['gt_bboxes'] = gt_bboxes[valid_inds, :]
if 'gt_labels' in results:
results['gt_labels'] = results['gt_labels'][valid_inds]
# filter and crop the masks
if 'gt_masks' in results:
results['gt_masks'] = results['gt_masks'].crop(
np.asarray([crop_x1, crop_y1, crop_x2, crop_y2]))
return results
def __repr__(self):
return self.__class__.__name__ + '(crop_size={})'.format(
self.crop_size)
@PIPELINES.register_module
class SegRescale(object):
"""Rescale semantic segmentation maps.
Args:
scale_factor (float): The scale factor of the final output.
"""
def __init__(self, scale_factor=1):
self.scale_factor = scale_factor
def __call__(self, results):
for key in results.get('seg_fields', []):
if self.scale_factor != 1:
results[key] = mmcv.imrescale(
results[key], self.scale_factor, interpolation='nearest')
return results
def __repr__(self):
return self.__class__.__name__ + '(scale_factor={})'.format(
self.scale_factor)
@PIPELINES.register_module
class PhotoMetricDistortion(object):
"""Apply photometric distortion to image sequentially, every transformation
is applied with a probability of 0.5. The position of random contrast is in
second or second to last.
1. random brightness
2. random contrast (mode 0)
3. convert color from BGR to HSV
4. random saturation
5. random hue
6. convert color from HSV to BGR
7. random contrast (mode 1)
8. randomly swap channels
Args:
brightness_delta (int): delta of brightness.
contrast_range (tuple): range of contrast.
saturation_range (tuple): range of saturation.
hue_delta (int): delta of hue.
"""
def __init__(self,
brightness_delta=32,
contrast_range=(0.5, 1.5),
saturation_range=(0.5, 1.5),
hue_delta=18):
self.brightness_delta = brightness_delta
self.contrast_lower, self.contrast_upper = contrast_range
self.saturation_lower, self.saturation_upper = saturation_range
self.hue_delta = hue_delta
def __call__(self, results):
img = results['img']
assert img.dtype == np.float32, \
'PhotoMetricDistortion needs the input image of dtype np.float32,'\
' please set "to_float32=True" in "LoadImageFromFile" pipeline'
# random brightness
if random.randint(2):
delta = random.uniform(-self.brightness_delta,
self.brightness_delta)
img += delta
# mode == 0 --> do random contrast first
# mode == 1 --> do random contrast last
mode = random.randint(2)
if mode == 1:
if random.randint(2):
alpha = random.uniform(self.contrast_lower,
self.contrast_upper)
img *= alpha
# convert color from BGR to HSV
img = mmcv.bgr2hsv(img)
# random saturation
if random.randint(2):
img[..., 1] *= random.uniform(self.saturation_lower,
self.saturation_upper)
# random hue
if random.randint(2):
img[..., 0] += random.uniform(-self.hue_delta, self.hue_delta)
img[..., 0][img[..., 0] > 360] -= 360
img[..., 0][img[..., 0] < 0] += 360
# convert color from HSV to BGR
img = mmcv.hsv2bgr(img)
# random contrast
if mode == 0:
if random.randint(2):
alpha = random.uniform(self.contrast_lower,
self.contrast_upper)
img *= alpha
# randomly swap channels
if random.randint(2):
img = img[..., random.permutation(3)]
results['img'] = img
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += ('(brightness_delta={}, contrast_range={}, '
'saturation_range={}, hue_delta={})').format(
self.brightness_delta,
(self.contrast_lower, self.contrast_upper),
(self.saturation_lower, self.saturation_upper),
self.hue_delta)
return repr_str
@PIPELINES.register_module
class Expand(object):
"""Random expand the image & bboxes.
Randomly place the original image on a canvas of 'ratio' x original image
size filled with mean values. The ratio is in the range of ratio_range.
Args:
mean (tuple): mean value of dataset.
to_rgb (bool): if need to convert the order of mean to align with RGB.
ratio_range (tuple): range of expand ratio.
prob (float): probability of applying this transformation
"""
def __init__(self,
mean=(0, 0, 0),
to_rgb=True,
ratio_range=(1, 4),
seg_ignore_label=None,
prob=0.5):
self.to_rgb = to_rgb
self.ratio_range = ratio_range
if to_rgb:
self.mean = mean[::-1]
else:
self.mean = mean
self.min_ratio, self.max_ratio = ratio_range
self.seg_ignore_label = seg_ignore_label
self.prob = prob
def __call__(self, results):
if random.uniform(0, 1) > self.prob:
return results
img, boxes = [results[k] for k in ('img', 'gt_bboxes')]
h, w, c = img.shape
ratio = random.uniform(self.min_ratio, self.max_ratio)
expand_img = np.full((int(h * ratio), int(w * ratio), c),
self.mean).astype(img.dtype)
left = int(random.uniform(0, w * ratio - w))
top = int(random.uniform(0, h * ratio - h))
expand_img[top:top + h, left:left + w] = img
boxes = boxes + np.tile((left, top), 2).astype(boxes.dtype)
results['img'] = expand_img
results['gt_bboxes'] = boxes
if 'gt_masks' in results:
results['gt_masks'] = results['gt_masks'].expand(
int(h * ratio), int(w * ratio), top, left)
# not tested
if 'gt_semantic_seg' in results:
assert self.seg_ignore_label is not None
gt_seg = results['gt_semantic_seg']
expand_gt_seg = np.full((int(h * ratio), int(w * ratio)),
self.seg_ignore_label).astype(gt_seg.dtype)
expand_gt_seg[top:top + h, left:left + w] = gt_seg
results['gt_semantic_seg'] = expand_gt_seg
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += '(mean={}, to_rgb={}, ratio_range={}, ' \
'seg_ignore_label={})'.format(
self.mean, self.to_rgb, self.ratio_range,
self.seg_ignore_label)
return repr_str
@PIPELINES.register_module
class MinIoURandomCrop(object):
"""Random crop the image & bboxes, the cropped patches have minimum IoU
requirement with original image & bboxes, the IoU threshold is randomly
selected from min_ious.
Args:
min_ious (tuple): minimum IoU threshold for all intersections with
bounding boxes
min_crop_size (float): minimum crop's size (i.e. h,w := a*h, a*w,
where a >= min_crop_size).
"""
def __init__(self, min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3):
# 1: return ori img
self.min_ious = min_ious
self.sample_mode = (1, *min_ious, 0)
self.min_crop_size = min_crop_size
def __call__(self, results):
img, boxes, labels = [
results[k] for k in ('img', 'gt_bboxes', 'gt_labels')
]
h, w, c = img.shape
while True:
mode = random.choice(self.sample_mode)
if mode == 1:
return results
min_iou = mode
for i in range(50):
new_w = random.uniform(self.min_crop_size * w, w)
new_h = random.uniform(self.min_crop_size * h, h)
# h / w in [0.5, 2]
if new_h / new_w < 0.5 or new_h / new_w > 2:
continue
left = random.uniform(w - new_w)
top = random.uniform(h - new_h)
patch = np.array(
(int(left), int(top), int(left + new_w), int(top + new_h)))
overlaps = bbox_overlaps(
patch.reshape(-1, 4), boxes.reshape(-1, 4)).reshape(-1)
if len(overlaps) > 0 and overlaps.min() < min_iou:
continue
# center of boxes should inside the crop img
# only adjust boxes and instance masks when the gt is not empty
if len(overlaps) > 0:
# adjust boxes
center = (boxes[:, :2] + boxes[:, 2:]) / 2
mask = ((center[:, 0] > patch[0]) *
(center[:, 1] > patch[1]) *
(center[:, 0] < patch[2]) *
(center[:, 1] < patch[3]))
if not mask.any():
continue
boxes = boxes[mask]
labels = labels[mask]
boxes[:, 2:] = boxes[:, 2:].clip(max=patch[2:])
boxes[:, :2] = boxes[:, :2].clip(min=patch[:2])
boxes -= np.tile(patch[:2], 2)
results['gt_bboxes'] = boxes
results['gt_labels'] = labels
if 'gt_masks' in results:
results['gt_masks'] = results['gt_masks'][
mask.nonzero()[0]].crop(patch)
# adjust the img no matter whether the gt is empty before crop
img = img[patch[1]:patch[3], patch[0]:patch[2]]
results['img'] = img
# not tested
if 'gt_semantic_seg' in results:
results['gt_semantic_seg'] = results['gt_semantic_seg'][
patch[1]:patch[3], patch[0]:patch[2]]
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += '(min_ious={}, min_crop_size={})'.format(
self.min_ious, self.min_crop_size)
return repr_str
@PIPELINES.register_module
class Corrupt(object):
def __init__(self, corruption, severity=1):
self.corruption = corruption
self.severity = severity
def __call__(self, results):
if corrupt is None:
raise RuntimeError('imagecorruptions is not installed')
results['img'] = corrupt(
results['img'].astype(np.uint8),
corruption_name=self.corruption,
severity=self.severity)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += '(corruption={}, severity={})'.format(
self.corruption, self.severity)
return repr_str
@PIPELINES.register_module
class Albu(object):
def __init__(self,
transforms,
bbox_params=None,
keymap=None,
update_pad_shape=False,
skip_img_without_anno=False):
"""
Adds custom transformations from Albumentations lib.
Please, visit `https://albumentations.readthedocs.io`
to get more information.
transforms (list): list of albu transformations
bbox_params (dict): bbox_params for albumentation `Compose`
keymap (dict): contains {'input key':'albumentation-style key'}
skip_img_without_anno (bool): whether to skip the image
if no ann left after aug
"""
if Compose is None:
raise RuntimeError('albumentations is not installed')
self.transforms = transforms
self.filter_lost_elements = False
self.update_pad_shape = update_pad_shape
self.skip_img_without_anno = skip_img_without_anno
# A simple workaround to remove masks without boxes
if (isinstance(bbox_params, dict) and 'label_fields' in bbox_params
and 'filter_lost_elements' in bbox_params):
self.filter_lost_elements = True
self.origin_label_fields = bbox_params['label_fields']
bbox_params['label_fields'] = ['idx_mapper']
del bbox_params['filter_lost_elements']
self.bbox_params = (
self.albu_builder(bbox_params) if bbox_params else None)
self.aug = Compose([self.albu_builder(t) for t in self.transforms],
bbox_params=self.bbox_params)
if not keymap:
self.keymap_to_albu = {
'img': 'image',
'gt_masks': 'masks',
'gt_bboxes': 'bboxes'
}
else:
self.keymap_to_albu = keymap
self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()}
def albu_builder(self, cfg):
"""Import a module from albumentations.
Inherits some of `build_from_cfg` logic.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
Returns:
obj: The constructed object.
"""
assert isinstance(cfg, dict) and 'type' in cfg
args = cfg.copy()
obj_type = args.pop('type')
if mmcv.is_str(obj_type):
if albumentations is None:
raise RuntimeError('albumentations is not installed')
obj_cls = getattr(albumentations, obj_type)
elif inspect.isclass(obj_type):
obj_cls = obj_type
else:
raise TypeError(
'type must be a str or valid type, but got {}'.format(
type(obj_type)))
if 'transforms' in args:
args['transforms'] = [
self.albu_builder(transform)
for transform in args['transforms']
]
return obj_cls(**args)
@staticmethod
def mapper(d, keymap):
"""
Dictionary mapper.
Renames keys according to keymap provided.
Args:
d (dict): old dict
keymap (dict): {'old_key':'new_key'}
Returns:
dict: new dict.
"""
updated_dict = {}
for k, v in zip(d.keys(), d.values()):
new_k = keymap.get(k, k)
updated_dict[new_k] = d[k]
return updated_dict
def __call__(self, results):
# dict to albumentations format
results = self.mapper(results, self.keymap_to_albu)
if 'bboxes' in results:
# to list of boxes
if isinstance(results['bboxes'], np.ndarray):
results['bboxes'] = [x for x in results['bboxes']]
# add pseudo-field for filtration
if self.filter_lost_elements:
results['idx_mapper'] = np.arange(len(results['bboxes']))
# TODO: Support mask structure in albu
if 'masks' in results:
if isinstance(results['masks'], PolygonMasks):
raise NotImplementedError(
'Albu only supports BitMap masks now')
ori_masks = results['masks']
results['masks'] = results['masks'].masks
results = self.aug(**results)
if 'bboxes' in results:
if isinstance(results['bboxes'], list):
results['bboxes'] = np.array(
results['bboxes'], dtype=np.float32)
results['bboxes'] = results['bboxes'].reshape(-1, 4)
# filter label_fields
if self.filter_lost_elements:
for label in self.origin_label_fields:
results[label] = np.array(
[results[label][i] for i in results['idx_mapper']])
if 'masks' in results:
results['masks'] = np.array(
[results['masks'][i] for i in results['idx_mapper']])
results['masks'] = ori_masks.__class__(
results['masks'], results['image'].shape[0],
results['image'].shape[1])
if (not len(results['idx_mapper'])
and self.skip_img_without_anno):
return None
if 'gt_labels' in results:
if isinstance(results['gt_labels'], list):
results['gt_labels'] = np.array(results['gt_labels'])
results['gt_labels'] = results['gt_labels'].astype(np.int64)
# back to the original format
results = self.mapper(results, self.keymap_back)
# update final shape
if self.update_pad_shape:
results['pad_shape'] = results['img'].shape
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += '(transforms={})'.format(self.transforms)
return repr_str
| 1 | 19,260 | Use single quote to wrap the str. | open-mmlab-mmdetection | py |
@@ -100,7 +100,7 @@ public enum JsonRpcError {
"The permissioning whitelist configuration file is out of sync. The changes have been applied, but not persisted to disk"),
WHITELIST_RELOAD_ERROR(
-32000,
- "Error reloading permissions file. Please use perm_getAccountsWhitelist and perm_getNodesWhitelist to review the current state of the whitelists"),
+ "Error reloading permissions file. Please use perm_getAccountsWhitelist and perm_getNodesAllowlist to review the current state of the whitelists"),
PERMISSIONING_NOT_ENABLED(-32000, "Node/Account whitelisting has not been enabled"),
NON_PERMITTED_NODE_CANNOT_BE_ADDED_AS_A_PEER(-32000, "Cannot add a non-permitted node as a peer"),
| 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.ethereum.api.jsonrpc.internal.response;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum JsonRpcError {
// Standard errors
PARSE_ERROR(-32700, "Parse error"),
INVALID_REQUEST(-32600, "Invalid Request"),
METHOD_NOT_FOUND(-32601, "Method not found"),
INVALID_PARAMS(-32602, "Invalid params"),
INTERNAL_ERROR(-32603, "Internal error"),
METHOD_NOT_ENABLED(-32604, "Method not enabled"),
// eth_sendTransaction specific error message
ETH_SEND_TX_NOT_AVAILABLE(
-32604,
"The method eth_sendTransaction is not supported. Use eth_sendRawTransaction to send a signed transaction to Besu."),
ETH_SEND_TX_ALREADY_KNOWN(-32000, "Known transaction"),
ETH_SEND_TX_REPLACEMENT_UNDERPRICED(-32000, "Replacement transaction underpriced"),
// P2P related errors
P2P_DISABLED(-32000, "P2P has been disabled. This functionality is not available"),
P2P_NETWORK_NOT_RUNNING(-32000, "P2P network is not running"),
// Filter & Subscription Errors
FILTER_NOT_FOUND(-32000, "Filter not found"),
LOGS_FILTER_NOT_FOUND(-32000, "Logs filter not found"),
SUBSCRIPTION_NOT_FOUND(-32000, "Subscription not found"),
NO_MINING_WORK_FOUND(-32000, "No mining work available yet"),
// Transaction validation failures
NONCE_TOO_LOW(-32001, "Nonce too low"),
INVALID_TRANSACTION_SIGNATURE(-32002, "Invalid signature"),
INTRINSIC_GAS_EXCEEDS_LIMIT(-32003, "Intrinsic gas exceeds gas limit"),
TRANSACTION_UPFRONT_COST_EXCEEDS_BALANCE(-32004, "Upfront cost exceeds account balance"),
EXCEEDS_BLOCK_GAS_LIMIT(-32005, "Transaction gas limit exceeds block gas limit"),
INCORRECT_NONCE(-32006, "Incorrect nonce"),
TX_SENDER_NOT_AUTHORIZED(-32007, "Sender account not authorized to send transactions"),
CHAIN_HEAD_WORLD_STATE_NOT_AVAILABLE(-32008, "Initial sync is still in progress"),
GAS_PRICE_TOO_LOW(-32009, "Gas price below configured minimum gas price"),
WRONG_CHAIN_ID(-32000, "Wrong chainId"),
REPLAY_PROTECTED_SIGNATURES_NOT_SUPPORTED(-32000, "ChainId not supported"),
// Miner failures
COINBASE_NOT_SET(-32010, "Coinbase not set. Unable to start mining without a coinbase"),
NO_HASHES_PER_SECOND(-32011, "No hashes being generated by the current node"),
// Wallet errors
COINBASE_NOT_SPECIFIED(-32000, "Coinbase must be explicitly specified"),
// Account errors
NO_ACCOUNT_FOUND(-32000, "Account not found"),
// Worldstate errors
WORLD_STATE_UNAVAILABLE(-32000, "World state unavailable"),
// Debug failures
PARENT_BLOCK_NOT_FOUND(-32000, "Parent block not found"),
// Permissioning/Account whitelist errors
ACCOUNT_WHITELIST_NOT_ENABLED(-32000, "Account whitelisting has not been enabled"),
ACCOUNT_WHITELIST_EMPTY_ENTRY(-32000, "Request contains an empty list of accounts"),
ACCOUNT_WHITELIST_INVALID_ENTRY(-32000, "Request contains an invalid account"),
ACCOUNT_WHITELIST_DUPLICATED_ENTRY(-32000, "Request contains duplicate accounts"),
ACCOUNT_WHITELIST_EXISTING_ENTRY(-32000, "Cannot add an existing account to whitelist"),
ACCOUNT_WHITELIST_ABSENT_ENTRY(-32000, "Cannot remove an absent account from whitelist"),
// Permissioning/Node whitelist errors
NODE_WHITELIST_NOT_ENABLED(-32000, "Node whitelisting has not been enabled"),
NODE_WHITELIST_EMPTY_ENTRY(-32000, "Request contains an empty list of nodes"),
NODE_WHITELIST_INVALID_ENTRY(-32000, "Request contains an invalid node"),
NODE_WHITELIST_DUPLICATED_ENTRY(-32000, "Request contains duplicate nodes"),
NODE_WHITELIST_EXISTING_ENTRY(-32000, "Cannot add an existing node to whitelist"),
NODE_WHITELIST_MISSING_ENTRY(-32000, "Cannot remove an absent node from whitelist"),
NODE_WHITELIST_FIXED_NODE_CANNOT_BE_REMOVED(
-32000, "Cannot remove a fixed node (bootnode or static node) from whitelist"),
// Permissioning/persistence errors
WHITELIST_PERSIST_FAILURE(
-32000, "Unable to persist changes to whitelist configuration file. Changes reverted"),
WHITELIST_FILE_SYNC(
-32000,
"The permissioning whitelist configuration file is out of sync. The changes have been applied, but not persisted to disk"),
WHITELIST_RELOAD_ERROR(
-32000,
"Error reloading permissions file. Please use perm_getAccountsWhitelist and perm_getNodesWhitelist to review the current state of the whitelists"),
PERMISSIONING_NOT_ENABLED(-32000, "Node/Account whitelisting has not been enabled"),
NON_PERMITTED_NODE_CANNOT_BE_ADDED_AS_A_PEER(-32000, "Cannot add a non-permitted node as a peer"),
// Permissioning/Authorization errors
UNAUTHORIZED(-40100, "Unauthorized"),
// Private transaction errors
ENCLAVE_ERROR(-50100, "Error communicating with enclave"),
UNIMPLEMENTED_PRIVATE_TRANSACTION_TYPE(-50100, "Unimplemented private transaction type"),
PRIVACY_NOT_ENABLED(-50100, "Privacy is not enabled"),
CREATE_PRIVACY_GROUP_ERROR(-50100, "Error creating privacy group"),
DELETE_PRIVACY_GROUP_ERROR(-50100, "Error deleting privacy group"),
FIND_PRIVACY_GROUP_ERROR(-50100, "Error finding privacy group"),
FIND_ON_CHAIN_PRIVACY_GROUP_ERROR(-50100, "Error finding on-chain privacy group"),
VALUE_NOT_ZERO(-50100, "We cannot transfer ether in a private transaction yet."),
DECODE_ERROR(-50100, "Unable to decode the private signed raw transaction"),
GET_PRIVATE_TRANSACTION_NONCE_ERROR(-50100, "Unable to determine nonce for account in group."),
OFFCHAIN_PRIVACY_GROUP_DOES_NOT_EXIST(-50100, "Offchain Privacy group does not exist."),
ONCCHAIN_PRIVACY_GROUP_DOES_NOT_EXIST(-50100, "Onchain Privacy group does not exist."),
ONCHAIN_PRIVACY_GROUP_NOT_ENABLED(-50100, "Onchain privacy groups not enabled."),
OFFCHAIN_PRIVACY_GROUP_NOT_ENABLED(
-50100, "Offchain privacy group can't be used with Onchain privacy groups enabled."),
ONCHAIN_PRIVACY_GROUP_ID_NOT_AVAILABLE(
-50100, "Private transactions to on-chain privacy groups must use privacyGroupId"),
PRIVATE_FROM_DOES_NOT_MATCH_ENCLAVE_PUBLIC_KEY(
-50100, "Private from does not match enclave public key"),
PMT_FAILED_INTRINSIC_GAS_EXCEEDS_LIMIT(
-50100,
"Private Marker Transaction failed due to intrinsic gas exeeding the limit. Gas limit used from the Private Transaction."),
CANT_CONNECT_TO_LOCAL_PEER(-32100, "Cannot add local node as peer."),
// Invalid input errors
ENODE_ID_INVALID(
-32000,
"Invalid node ID: node ID must have exactly 128 hexadecimal characters and should not include any '0x' hex prefix."),
// Enclave errors
NODE_MISSING_PEER_URL(-50200, "NodeMissingPeerUrl"),
NODE_PUSHING_TO_PEER(-50200, "NodePushingToPeer"),
NODE_PROPAGATING_TO_ALL_PEERS(-50200, "NodePropagatingToAllPeers"),
NO_SENDER_KEY(-50200, "NoSenderKey"),
INVALID_PAYLOAD(-50200, "InvalidPayload"),
ENCLAVE_CREATE_KEY_PAIR(-50200, "EnclaveCreateKeyPair"),
ENCLAVE_DECODE_PUBLIC_KEY(-50200, "EnclaveDecodePublicKey"),
ENCLAVE_DECRYPT_WRONG_PRIVATE_KEY(-50200, "EnclaveDecryptWrongPrivateKey"),
ENCLAVE_ENCRYPT_COMBINE_KEYS(-50200, "EnclaveEncryptCombineKeys"),
ENCLAVE_MISSING_PRIVATE_KEY_PASSWORD(-50200, "EnclaveMissingPrivateKeyPasswords"),
ENCLAVE_NO_MATCHING_PRIVATE_KEY(-50200, "EnclaveNoMatchingPrivateKey"),
ENCLAVE_NOT_PAYLOAD_OWNER(-50200, "EnclaveNotPayloadOwner"),
ENCLAVE_UNSUPPORTED_PRIVATE_KEY_TYPE(-50200, "EnclaveUnsupportedPrivateKeyType"),
ENCLAVE_STORAGE_DECRYPT(-50200, "EnclaveStorageDecrypt"),
ENCLAVE_PRIVACY_GROUP_CREATION(-50200, "EnclavePrivacyGroupIdCreation"),
ENCLAVE_PAYLOAD_NOT_FOUND(-50200, "EnclavePayloadNotFound"),
CREATE_GROUP_INCLUDE_SELF(-50200, "CreatePrivacyGroupShouldIncludeSelf"),
/** Storing privacy group issue */
ENCLAVE_UNABLE_STORE_PRIVACY_GROUP(-50200, "PrivacyGroupNotStored"),
ENCLAVE_UNABLE_DELETE_PRIVACY_GROUP(-50200, "PrivacyGroupNotDeleted"),
ENCLAVE_UNABLE_PUSH_DELETE_PRIVACY_GROUP(-50200, "PrivacyGroupNotPushed"),
ENCLAVE_PRIVACY_GROUP_MISSING(-50200, "PrivacyGroupNotFound"),
ENCLAVE_PRIVACY_QUERY_ERROR(-50200, "PrivacyGroupQueryError"),
ENCLAVE_KEYS_CANNOT_DECRYPT_PAYLOAD(-50200, "EnclaveKeysCannotDecryptPayload"),
METHOD_UNIMPLEMENTED(-50200, "MethodUnimplemented"),
/** Plugins error */
PLUGIN_NOT_FOUND(-60000, "Plugin not found");
private final int code;
private final String message;
JsonRpcError(final int code, final String message) {
this.code = code;
this.message = message;
}
@JsonGetter("code")
public int getCode() {
return code;
}
@JsonGetter("message")
public String getMessage() {
return message;
}
@JsonCreator
public static JsonRpcError fromJson(
@JsonProperty("code") final int code, @JsonProperty("message") final String message) {
for (final JsonRpcError error : JsonRpcError.values()) {
if (error.code == code && error.message.equals(message)) {
return error;
}
}
return null;
}
}
| 1 | 22,893 | Is the plan to rename this later? | hyperledger-besu | java |
@@ -340,7 +340,9 @@ class ChoiceAuth extends AbstractBase
return false;
}
- if (!in_array($this->strategy, $this->strategies)) {
+ if ('Email' !== $this->strategy
+ && !in_array($this->strategy, $this->strategies)
+ ) {
throw new InvalidArgumentException("Illegal setting: {$this->strategy}");
}
$authenticator = $this->getPluginManager()->get($this->strategy); | 1 | <?php
/**
* MultiAuth Authentication plugin
*
* PHP version 7
*
* Copyright (C) Villanova University 2010.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Authentication
* @author Anna Headley <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:authentication_handlers Wiki
*/
namespace VuFind\Auth;
use VuFind\Db\Row\User;
use VuFind\Exception\Auth as AuthException;
use Zend\Http\PhpEnvironment\Request;
/**
* ChoiceAuth Authentication plugin
*
* This module enables a user to choose between two authentication methods.
* choices are presented side-by-side and one is manually selected.
*
* See config.ini for more details
*
* @category VuFind
* @package Authentication
* @author Anna Headley <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:authentication_handlers Wiki
*/
class ChoiceAuth extends AbstractBase
{
/**
* Authentication strategies to present
*
* @var array
*/
protected $strategies = [];
/**
* Auth strategy selected by user
*
* @var string
*/
protected $strategy;
/**
* Plugin manager for obtaining other authentication objects
*
* @var PluginManager
*/
protected $manager;
/**
* Session container
*
* @var \Zend\Session\Container
*/
protected $session;
/**
* Constructor
*
* @param \Zend\Session\Container $container Session container for retaining
* user choices.
*/
public function __construct(\Zend\Session\Container $container)
{
// Set up session container and load cached strategy (if found):
$this->session = $container;
$this->strategy = isset($this->session->auth_method)
? $this->session->auth_method : false;
}
/**
* Validate configuration parameters. This is a support method for getConfig(),
* so the configuration MUST be accessed using $this->config; do not call
* $this->getConfig() from within this method!
*
* @throws AuthException
* @return void
*/
protected function validateConfig()
{
if (!isset($this->config->ChoiceAuth->choice_order)
|| !strlen($this->config->ChoiceAuth->choice_order)
) {
throw new AuthException(
"One or more ChoiceAuth parameters are missing. " .
"Check your config.ini!"
);
}
}
/**
* Set configuration; throw an exception if it is invalid.
*
* @param \Zend\Config\Config $config Configuration to set
*
* @throws AuthException
* @return void
*/
public function setConfig($config)
{
parent::setConfig($config);
$this->strategies = array_map(
'trim', explode(',', $this->getConfig()->ChoiceAuth->choice_order)
);
}
/**
* Inspect the user's request prior to processing a login request; this is
* essentially an event hook which most auth modules can ignore. See
* ChoiceAuth for a use case example.
*
* @param \Zend\Http\PhpEnvironment\Request $request Request object.
*
* @throws AuthException
* @return void
*/
public function preLoginCheck($request)
{
$this->setStrategyFromRequest($request);
}
/**
* Reset any internal status; this is essentially an event hook which most auth
* modules can ignore. See ChoiceAuth for a use case example.
*
* @return void
*/
public function resetState()
{
$this->strategy = false;
}
/**
* Attempt to authenticate the current user. Throws exception if login fails.
*
* @param Request $request Request object containing account credentials.
*
* @throws AuthException
* @return User Object representing logged-in user.
*/
public function authenticate($request)
{
try {
return $this->proxyUserLoad($request, 'authenticate', func_get_args());
} catch (AuthException $e) {
// If an exception was thrown during login, we need to clear the
// stored strategy to ensure that we display the full ChoiceAuth
// form rather than the form for only the method that the user
// attempted to use.
$this->strategy = false;
throw $e;
}
}
/**
* Create a new user account from the request.
*
* @param Request $request Request object containing new account details.
*
* @throws AuthException
* @return User New user row.
*/
public function create($request)
{
return $this->proxyUserLoad($request, 'create', func_get_args());
}
/**
* Set the manager for loading other authentication plugins.
*
* @param PluginManager $manager Plugin manager
*
* @return void
*/
public function setPluginManager(PluginManager $manager)
{
$this->manager = $manager;
}
/**
* Get the manager for loading other authentication plugins.
*
* @throws \Exception
* @return PluginManager
*/
public function getPluginManager()
{
if (null === $this->manager) {
throw new \Exception('Plugin manager missing.');
}
return $this->manager;
}
/**
* Return an array of authentication options allowed by this class.
*
* @return array
*/
public function getSelectableAuthOptions()
{
return $this->strategies;
}
/**
* If an authentication strategy has been selected, return the active option.
* If not, return false.
*
* @return bool|string
*/
public function getSelectedAuthOption()
{
return $this->strategy;
}
/**
* Perform cleanup at logout time.
*
* @param string $url URL to redirect user to after logging out.
*
* @throws InvalidArgumentException
* @return string Redirect URL (usually same as $url, but modified in
* some authentication modules).
*/
public function logout($url)
{
// clear user's login choice, if necessary:
if (isset($this->session->auth_method)) {
unset($this->session->auth_method);
}
// If we have a selected strategy, proxy the appropriate class; otherwise,
// perform default behavior of returning unmodified URL:
try {
return $this->strategy
? $this->proxyAuthMethod('logout', func_get_args()) : $url;
} catch (InvalidArgumentException $e) {
// If we're in an invalid state (due to an illegal login method),
// we should just clear everything out so the user can try again.
$this->strategy = false;
return false;
}
}
/**
* Get the URL to establish a session (needed when the internal VuFind login
* form is inadequate). Returns false when no session initiator is needed.
*
* @param string $target Full URL where external authentication strategy should
* send user after login (some drivers may override this).
*
* @return bool|string
*/
public function getSessionInitiator($target)
{
return $this->proxyAuthMethod('getSessionInitiator', func_get_args());
}
/**
* Does this authentication method support password changing
*
* @return bool
*/
public function supportsPasswordChange()
{
return $this->proxyAuthMethod('supportsPasswordChange', func_get_args());
}
/**
* Does this authentication method support password recovery
*
* @return bool
*/
public function supportsPasswordRecovery()
{
return $this->proxyAuthMethod('supportsPasswordRecovery', func_get_args());
}
/**
* Password policy for a new password (e.g. minLength, maxLength)
*
* @return array
*/
public function getPasswordPolicy()
{
return $this->proxyAuthMethod('getPasswordPolicy', func_get_args());
}
/**
* Update a user's password from the request.
*
* @param Request $request Request object containing password change details.
*
* @throws AuthException
* @return User New user row.
*/
public function updatePassword($request)
{
// When a user is recovering a forgotten password, there may be an
// auth method included in the request since we haven't set an active
// strategy yet -- thus we should check for it.
$this->setStrategyFromRequest($request);
return $this->proxyAuthMethod('updatePassword', func_get_args());
}
/**
* Proxy auth method; a helper function to be called like:
* return $this->proxyAuthMethod(METHOD, func_get_args());
*
* @param string $method the method to proxy
* @param array $params array of params to pass
*
* @throws AuthException
* @return mixed
*/
protected function proxyAuthMethod($method, $params)
{
// If no strategy is found, we can't do anything -- return false.
if (!$this->strategy) {
return false;
}
if (!in_array($this->strategy, $this->strategies)) {
throw new InvalidArgumentException("Illegal setting: {$this->strategy}");
}
$authenticator = $this->getPluginManager()->get($this->strategy);
$authenticator->setConfig($this->getConfig());
if (!is_callable([$authenticator, $method])) {
throw new AuthException($this->strategy . "has no method $method");
}
return call_user_func_array([$authenticator, $method], $params);
}
/**
* Proxy auth method that checks the request for an active method and then
* loads a User object from the database (e.g. authenticate or create).
*
* @param Request $request Request object to check.
* @param string $method the method to proxy
* @param array $params array of params to pass
*
* @throws AuthException
* @return mixed
*/
protected function proxyUserLoad($request, $method, $params)
{
$this->setStrategyFromRequest($request);
$user = $this->proxyAuthMethod($method, $params);
if (!$user) {
throw new AuthException('Unexpected return value');
}
$this->session->auth_method = $this->strategy;
return $user;
}
/**
* Set the active strategy based on the auth_method value in the request,
* if found.
*
* @param Request $request Request object to check.
*
* @return void
*/
protected function setStrategyFromRequest($request)
{
// Set new strategy; fall back to old one if there is a problem:
$defaultStrategy = $this->strategy;
$this->strategy = trim($request->getPost()->get('auth_method'));
if (empty($this->strategy)) {
$this->strategy = trim($request->getQuery()->get('auth_method'));
}
if (empty($this->strategy)) {
$this->strategy = $defaultStrategy;
if (empty($this->strategy)) {
throw new AuthException('authentication_error_technical');
}
}
}
/**
* Validate the credentials in the provided request, but do not change the state
* of the current logged-in user. Return true for valid credentials, false
* otherwise.
*
* @param \Zend\Http\PhpEnvironment\Request $request Request object containing
* account credentials.
*
* @throws AuthException
* @return bool
*/
public function validateCredentials($request)
{
try {
// In this instance we are checking credentials but do not wish to
// change the state of the current object. Thus, we use proxyAuthMethod()
// here instead of proxyUserLoad().
$user = $this->proxyAuthMethod('authenticate', func_get_args());
} catch (AuthException $e) {
return false;
}
return isset($user) && $user instanceof User;
}
}
| 1 | 27,939 | Is there a reason why we need a special case for Email at this point? Is the idea that other methods can turn into Email even if it's not configured as a top-level option? | vufind-org-vufind | php |
@@ -130,6 +130,9 @@ func makeJournalServer(
bcache BlockCache, dirtyBcache DirtyBlockCache, bserver BlockServer,
mdOps MDOps, onBranchChange branchChangeListener,
onMDFlush mdFlushListener, diskLimiter diskLimiter) *JournalServer {
+ if len(dir) == 0 {
+ panic("dir unexpectedly empty")
+ }
jServer := JournalServer{
config: config,
log: log, | 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 (
"fmt"
"path/filepath"
"sync"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/ioutil"
"github.com/keybase/kbfs/kbfscrypto"
"github.com/keybase/kbfs/tlf"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
type journalServerConfig struct {
EnableAuto bool
}
// JournalServerStatus represents the overall status of the
// JournalServer for display in diagnostics. It is suitable for
// encoding directly as JSON.
type JournalServerStatus struct {
RootDir string
Version int
CurrentUID keybase1.UID
CurrentVerifyingKey kbfscrypto.VerifyingKey
EnableAuto bool
JournalCount int
// The byte counters below are signed because
// os.FileInfo.Size() is signed.
StoredBytes int64
UnflushedBytes int64
UnflushedPaths []string
}
// branchChangeListener describes a caller that will get updates via
// the onTLFBranchChange method call when the journal branch changes
// for the given TlfID. If a new branch has been created, the given
// BranchID will be something other than NullBranchID. If the current
// branch was pruned, it will be NullBranchID. If the implementer
// will be accessing the journal, it must do so from another goroutine
// to avoid deadlocks.
type branchChangeListener interface {
onTLFBranchChange(tlf.ID, BranchID)
}
// mdFlushListener describes a caller that will ge updates via the
// onMDFlush metod when an MD is flushed. If the implementer will be
// accessing the journal, it must do so from another goroutine to
// avoid deadlocks.
type mdFlushListener interface {
onMDFlush(tlf.ID, BranchID, MetadataRevision)
}
// diskLimiter is an interface for limiting disk usage. A simple
// implementation would use a semaphore initialized with the maximum
// disk usage, but a more sophisticated implementation would apply
// backpressure on Acquire.
type diskLimiter interface {
// Acquire is called before an operation that would take up n
// bytes of disk space. It may block, but must return
// immediately with a (possibly-wrapped) ctx.Err() if ctx is
// cancelled. The (possibly-updated) number of bytes available
// (which can be negative) must be returned, even if the error
// is non-nil.
Acquire(ctx context.Context, n int64) (int64, error)
// ForceAcquire is called when initializing a TLF journal with
// that journal's current disk usage. The updated number of
// bytes available (which can be negative) must be returned.
ForceAcquire(n int64) int64
// Release is called after an operation that has freed up n
// bytes of disk space. It is also called when shutting down a
// TLF journal. The updated number of bytes available (which
// can be negative) must be returned.
Release(n int64) int64
}
// TODO: JournalServer isn't really a server, although it can create
// objects that act as servers. Rename to JournalManager.
// JournalServer is the server that handles write journals. It
// interposes itself in front of BlockServer and MDOps. It uses MDOps
// instead of MDServer because it has to potentially modify the
// RootMetadata passed in, and by the time it hits MDServer it's
// already too late. However, this assumes that all MD ops go through
// MDOps.
//
// The maximum number of characters added to the root dir by a journal
// server journal is 108: 51 for the TLF journal, and 57 for
// everything else.
//
// /v1/de...-...(53 characters total)...ff(/tlf journal)
type JournalServer struct {
config Config
log logger.Logger
deferLog logger.Logger
dir string
delegateBlockCache BlockCache
delegateDirtyBlockCache DirtyBlockCache
delegateBlockServer BlockServer
delegateMDOps MDOps
onBranchChange branchChangeListener
onMDFlush mdFlushListener
diskLimiter diskLimiter
// Protects all fields below.
lock sync.RWMutex
currentUID keybase1.UID
currentVerifyingKey kbfscrypto.VerifyingKey
tlfJournals map[tlf.ID]*tlfJournal
dirtyOps uint
dirtyOpsDone *sync.Cond
serverConfig journalServerConfig
}
func makeJournalServer(
config Config, log logger.Logger, dir string,
bcache BlockCache, dirtyBcache DirtyBlockCache, bserver BlockServer,
mdOps MDOps, onBranchChange branchChangeListener,
onMDFlush mdFlushListener, diskLimiter diskLimiter) *JournalServer {
jServer := JournalServer{
config: config,
log: log,
deferLog: log.CloneWithAddedDepth(1),
dir: dir,
delegateBlockCache: bcache,
delegateDirtyBlockCache: dirtyBcache,
delegateBlockServer: bserver,
delegateMDOps: mdOps,
onBranchChange: onBranchChange,
onMDFlush: onMDFlush,
tlfJournals: make(map[tlf.ID]*tlfJournal),
diskLimiter: diskLimiter,
}
jServer.dirtyOpsDone = sync.NewCond(&jServer.lock)
return &jServer
}
func (j *JournalServer) rootPath() string {
return filepath.Join(j.dir, "v1")
}
func (j *JournalServer) configPath() string {
return filepath.Join(j.rootPath(), "config.json")
}
func (j *JournalServer) readConfig() error {
return ioutil.DeserializeFromJSONFile(j.configPath(), &j.serverConfig)
}
func (j *JournalServer) writeConfig() error {
return ioutil.SerializeToJSONFile(j.serverConfig, j.configPath())
}
func (j *JournalServer) tlfJournalPathLocked(tlfID tlf.ID) string {
if j.currentVerifyingKey == (kbfscrypto.VerifyingKey{}) {
panic("currentVerifyingKey is zero")
}
// We need to generate a unique path for each (UID, device,
// TLF) tuple. Verifying keys (which are unique to a device)
// are globally unique, so no need to have the uid in the
// path. Furthermore, everything after the first two bytes
// (four characters) is randomly generated, so taking the
// first 36 characters of the verifying key gives us 16 random
// bytes (since the first two bytes encode version/type) or
// 128 random bits, which means that the expected number of
// devices generated before getting a collision in the first
// part of the path is 2^64 (see
// https://en.wikipedia.org/wiki/Birthday_problem#Cast_as_a_collision_problem
// ).
//
// By similar reasoning, for a single device, taking the first
// 16 characters of the TLF ID gives us 64 random bits, which
// means that the expected number of TLFs associated to that
// device before getting a collision in the second part of the
// path is 2^32.
shortDeviceIDStr := j.currentVerifyingKey.String()[:36]
shortTlfIDStr := tlfID.String()[:16]
dir := fmt.Sprintf("%s-%s", shortDeviceIDStr, shortTlfIDStr)
return filepath.Join(j.rootPath(), dir)
}
func (j *JournalServer) getTLFJournal(tlfID tlf.ID) (*tlfJournal, bool) {
getJournalFn := func() (*tlfJournal, bool, bool) {
j.lock.RLock()
defer j.lock.RUnlock()
tlfJournal, ok := j.tlfJournals[tlfID]
return tlfJournal, j.serverConfig.EnableAuto, ok
}
tlfJournal, enableAuto, ok := getJournalFn()
if !ok && enableAuto {
ctx := context.TODO() // plumb through from callers
j.log.CDebugf(ctx, "Enabling a new journal for %s", tlfID)
err := j.Enable(ctx, tlfID, TLFJournalBackgroundWorkEnabled)
if err != nil {
j.log.CWarningf(ctx, "Couldn't enable journal for %s: %+v", tlfID, err)
return nil, false
}
tlfJournal, _, ok = getJournalFn()
}
return tlfJournal, ok
}
func (j *JournalServer) hasTLFJournal(tlfID tlf.ID) bool {
j.lock.RLock()
defer j.lock.RUnlock()
_, ok := j.tlfJournals[tlfID]
return ok
}
// EnableExistingJournals turns on the write journal for all TLFs for
// the given (UID, device) tuple (with the device identified by its
// verifying key) with an existing journal. Any returned error means
// that the JournalServer remains in the same state as it was before.
//
// Once this is called, this must not be called again until
// shutdownExistingJournals is called.
func (j *JournalServer) EnableExistingJournals(
ctx context.Context, currentUID keybase1.UID,
currentVerifyingKey kbfscrypto.VerifyingKey,
bws TLFJournalBackgroundWorkStatus) (err error) {
j.log.CDebugf(ctx, "Enabling existing journals (%s)", bws)
defer func() {
if err != nil {
j.deferLog.CDebugf(ctx,
"Error when enabling existing journals: %+v",
err)
}
}()
j.lock.Lock()
defer j.lock.Unlock()
err = j.readConfig()
switch {
case ioutil.IsNotExist(err):
// Config file doesn't exist, so write it.
err := j.writeConfig()
if err != nil {
return err
}
case err != nil:
return err
}
if j.currentUID != keybase1.UID("") {
return errors.Errorf("Trying to set current UID from %s to %s",
j.currentUID, currentUID)
}
if j.currentVerifyingKey != (kbfscrypto.VerifyingKey{}) {
return errors.Errorf(
"Trying to set current verifying key from %s to %s",
j.currentVerifyingKey, currentVerifyingKey)
}
if currentUID == keybase1.UID("") {
return errors.New("Current UID is empty")
}
if currentVerifyingKey == (kbfscrypto.VerifyingKey{}) {
return errors.New("Current verifying key is empty")
}
// Need to set it here since tlfJournalPathLocked and
// enableLocked depend on it.
j.currentUID = currentUID
j.currentVerifyingKey = currentVerifyingKey
enableSucceeded := false
defer func() {
// Revert to a clean state if the enable doesn't
// succeed, either due to a panic or error.
if !enableSucceeded {
j.shutdownExistingJournalsLocked(ctx)
}
}()
fileInfos, err := ioutil.ReadDir(j.rootPath())
if ioutil.IsNotExist(err) {
enableSucceeded = true
return nil
} else if err != nil {
return err
}
for _, fi := range fileInfos {
name := fi.Name()
if !fi.IsDir() {
j.log.CDebugf(ctx, "Skipping file %q", name)
continue
}
dir := filepath.Join(j.rootPath(), name)
uid, key, tlfID, err := readTLFJournalInfoFile(dir)
if err != nil {
j.log.CDebugf(
ctx, "Skipping non-TLF dir %q: %+v", name, err)
continue
}
if uid != currentUID {
j.log.CDebugf(
ctx, "Skipping dir %q due to mismatched UID %s",
name, uid)
continue
}
if key != currentVerifyingKey {
j.log.CDebugf(
ctx, "Skipping dir %q due to mismatched key %s",
name, uid)
continue
}
expectedDir := j.tlfJournalPathLocked(tlfID)
if dir != expectedDir {
j.log.CDebugf(
ctx, "Skipping misnamed dir %q; expected %q",
dir, expectedDir)
continue
}
// Allow enable even if dirty, since any dirty writes
// in flight are most likely for another user.
err = j.enableLocked(ctx, tlfID, bws, true)
if err != nil {
// Don't treat per-TLF errors as fatal.
j.log.CWarningf(
ctx, "Error when enabling existing journal for %s: %+v",
tlfID, err)
continue
}
}
enableSucceeded = true
return nil
}
func (j *JournalServer) enableLocked(
ctx context.Context, tlfID tlf.ID, bws TLFJournalBackgroundWorkStatus,
allowEnableIfDirty bool) (err error) {
j.log.CDebugf(ctx, "Enabling journal for %s (%s)", tlfID, bws)
defer func() {
if err != nil {
j.deferLog.CDebugf(ctx,
"Error when enabling journal for %s: %+v",
tlfID, err)
}
}()
if j.currentUID == keybase1.UID("") {
return errors.New("Current UID is empty")
}
if j.currentVerifyingKey == (kbfscrypto.VerifyingKey{}) {
return errors.New("Current verifying key is empty")
}
if tlfJournal, ok := j.tlfJournals[tlfID]; ok {
return tlfJournal.enable()
}
err = func() error {
if j.dirtyOps > 0 {
return errors.Errorf("Can't enable journal for %s while there "+
"are outstanding dirty ops", tlfID)
}
if j.delegateDirtyBlockCache.IsAnyDirty(tlfID) {
return errors.Errorf("Can't enable journal for %s while there "+
"are any dirty blocks outstanding", tlfID)
}
return nil
}()
if err != nil {
if !allowEnableIfDirty {
return err
}
j.log.CWarningf(ctx,
"Got ignorable error on journal enable, and proceeding anyway: %+v", err)
}
tlfDir := j.tlfJournalPathLocked(tlfID)
tlfJournal, err := makeTLFJournal(
ctx, j.currentUID, j.currentVerifyingKey, tlfDir,
tlfID, tlfJournalConfigAdapter{j.config}, j.delegateBlockServer,
bws, nil, j.onBranchChange, j.onMDFlush, j.diskLimiter)
if err != nil {
return err
}
j.tlfJournals[tlfID] = tlfJournal
return nil
}
// Enable turns on the write journal for the given TLF.
func (j *JournalServer) Enable(ctx context.Context, tlfID tlf.ID,
bws TLFJournalBackgroundWorkStatus) error {
j.lock.Lock()
defer j.lock.Unlock()
return j.enableLocked(ctx, tlfID, bws, false)
}
// EnableAuto turns on the write journal for all TLFs, even new ones,
// persistently.
func (j *JournalServer) EnableAuto(ctx context.Context) error {
j.lock.Lock()
defer j.lock.Unlock()
if j.serverConfig.EnableAuto {
// Nothing to do.
return nil
}
j.log.CDebugf(ctx, "Enabling auto-journaling")
j.serverConfig.EnableAuto = true
return j.writeConfig()
}
// DisableAuto turns off automatic write journal for any
// newly-accessed TLFs. Existing journaled TLFs need to be disabled
// manually.
func (j *JournalServer) DisableAuto(ctx context.Context) error {
j.lock.Lock()
defer j.lock.Unlock()
if !j.serverConfig.EnableAuto {
// Nothing to do.
return nil
}
j.log.CDebugf(ctx, "Disabling auto-journaling")
j.serverConfig.EnableAuto = false
return j.writeConfig()
}
func (j *JournalServer) dirtyOpStart(tlfID tlf.ID) {
j.lock.Lock()
defer j.lock.Unlock()
j.dirtyOps++
}
func (j *JournalServer) dirtyOpEnd(tlfID tlf.ID) {
j.lock.Lock()
defer j.lock.Unlock()
if j.dirtyOps == 0 {
panic("Trying to end a dirty op when count is 0")
}
j.dirtyOps--
if j.dirtyOps == 0 {
j.dirtyOpsDone.Broadcast()
}
}
// PauseBackgroundWork pauses the background work goroutine, if it's
// not already paused.
func (j *JournalServer) PauseBackgroundWork(ctx context.Context, tlfID tlf.ID) {
j.log.CDebugf(ctx, "Signaling pause for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID); ok {
tlfJournal.pauseBackgroundWork()
return
}
j.log.CDebugf(ctx,
"Could not find journal for %s; dropping pause signal",
tlfID)
}
// ResumeBackgroundWork resumes the background work goroutine, if it's
// not already resumed.
func (j *JournalServer) ResumeBackgroundWork(ctx context.Context, tlfID tlf.ID) {
j.log.CDebugf(ctx, "Signaling resume for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID); ok {
tlfJournal.resumeBackgroundWork()
return
}
j.log.CDebugf(ctx,
"Could not find journal for %s; dropping resume signal",
tlfID)
}
// Flush flushes the write journal for the given TLF.
func (j *JournalServer) Flush(ctx context.Context, tlfID tlf.ID) (err error) {
j.log.CDebugf(ctx, "Flushing journal for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID); ok {
return tlfJournal.flush(ctx)
}
j.log.CDebugf(ctx, "Journal not enabled for %s", tlfID)
return nil
}
// Wait blocks until the write journal has finished flushing
// everything. It is essentially the same as Flush() when the journal
// is enabled and unpaused, except that it is safe to cancel the
// context without leaving the journal in a partially-flushed state.
func (j *JournalServer) Wait(ctx context.Context, tlfID tlf.ID) (err error) {
j.log.CDebugf(ctx, "Waiting on journal for %s", tlfID)
if tlfJournal, ok := j.getTLFJournal(tlfID); ok {
return tlfJournal.wait(ctx)
}
j.log.CDebugf(ctx, "Journal not enabled for %s", tlfID)
return nil
}
// Disable turns off the write journal for the given TLF.
func (j *JournalServer) Disable(ctx context.Context, tlfID tlf.ID) (
wasEnabled bool, err error) {
j.log.CDebugf(ctx, "Disabling journal for %s", tlfID)
defer func() {
if err != nil {
j.deferLog.CDebugf(ctx,
"Error when disabling journal for %s: %+v",
tlfID, err)
}
}()
j.lock.Lock()
defer j.lock.Unlock()
tlfJournal, ok := j.tlfJournals[tlfID]
if !ok {
j.log.CDebugf(ctx, "Journal already existed for %s", tlfID)
return false, nil
}
if j.dirtyOps > 0 {
return false, errors.Errorf("Can't disable journal for %s while there "+
"are outstanding dirty ops", tlfID)
}
if j.delegateDirtyBlockCache.IsAnyDirty(tlfID) {
return false, errors.Errorf("Can't disable journal for %s while there "+
"are any dirty blocks outstanding", tlfID)
}
// Disable the journal. Note that we don't bother deleting the
// journal from j.tlfJournals, to avoid cases where something
// keeps it around doing background work or re-enables it, at the
// same time JournalServer creates a new journal for the same TLF.
wasEnabled, err = tlfJournal.disable()
if err != nil {
return false, err
}
if wasEnabled {
j.log.CDebugf(ctx, "Disabled journal for %s", tlfID)
}
return wasEnabled, nil
}
func (j *JournalServer) blockCache() journalBlockCache {
return journalBlockCache{j, j.delegateBlockCache}
}
func (j *JournalServer) dirtyBlockCache(
journalCache DirtyBlockCache) journalDirtyBlockCache {
return journalDirtyBlockCache{j, j.delegateDirtyBlockCache, journalCache}
}
func (j *JournalServer) blockServer() journalBlockServer {
return journalBlockServer{j, j.delegateBlockServer, false}
}
func (j *JournalServer) mdOps() journalMDOps {
return journalMDOps{j.delegateMDOps, j}
}
// Status returns a JournalServerStatus object suitable for
// diagnostics. It also returns a list of TLF IDs which have journals
// enabled.
func (j *JournalServer) Status(
ctx context.Context) (JournalServerStatus, []tlf.ID) {
j.lock.RLock()
defer j.lock.RUnlock()
var totalStoredBytes, totalUnflushedBytes int64
tlfIDs := make([]tlf.ID, 0, len(j.tlfJournals))
for _, tlfJournal := range j.tlfJournals {
storedBytes, unflushedBytes, err := tlfJournal.getByteCounts()
if err != nil {
j.log.CWarningf(ctx,
"Couldn't calculate stored/unflushed bytes for %s: %+v",
tlfJournal.tlfID, err)
}
totalStoredBytes += storedBytes
totalUnflushedBytes += unflushedBytes
tlfIDs = append(tlfIDs, tlfJournal.tlfID)
}
return JournalServerStatus{
RootDir: j.rootPath(),
Version: 1,
CurrentUID: j.currentUID,
CurrentVerifyingKey: j.currentVerifyingKey,
EnableAuto: j.serverConfig.EnableAuto,
JournalCount: len(tlfIDs),
StoredBytes: totalStoredBytes,
UnflushedBytes: totalUnflushedBytes,
}, tlfIDs
}
// JournalStatus returns a TLFServerStatus object for the given TLF
// suitable for diagnostics.
func (j *JournalServer) JournalStatus(tlfID tlf.ID) (
TLFJournalStatus, error) {
tlfJournal, ok := j.getTLFJournal(tlfID)
if !ok {
return TLFJournalStatus{},
errors.Errorf("Journal not enabled for %s", tlfID)
}
return tlfJournal.getJournalStatus()
}
// JournalStatusWithPaths returns a TLFServerStatus object for the
// given TLF suitable for diagnostics, including paths for all the
// unflushed entries.
func (j *JournalServer) JournalStatusWithPaths(ctx context.Context,
tlfID tlf.ID, cpp chainsPathPopulator) (TLFJournalStatus, error) {
tlfJournal, ok := j.getTLFJournal(tlfID)
if !ok {
return TLFJournalStatus{},
errors.Errorf("Journal not enabled for %s", tlfID)
}
return tlfJournal.getJournalStatusWithPaths(ctx, cpp)
}
// shutdownExistingJournalsLocked shuts down all write journals, sets
// the current UID and verifying key to zero, and returns once all
// shutdowns are complete. It is safe to call multiple times in a row,
// and once this is called, EnableExistingJournals may be called
// again.
func (j *JournalServer) shutdownExistingJournalsLocked(ctx context.Context) {
for j.dirtyOps > 0 {
j.log.CDebugf(ctx,
"Waiting for %d dirty ops before shutting down existing journals...", j.dirtyOps)
j.dirtyOpsDone.Wait()
}
j.log.CDebugf(ctx, "Shutting down existing journals")
for _, tlfJournal := range j.tlfJournals {
tlfJournal.shutdown()
}
j.tlfJournals = make(map[tlf.ID]*tlfJournal)
j.currentUID = keybase1.UID("")
j.currentVerifyingKey = kbfscrypto.VerifyingKey{}
}
// shutdownExistingJournals shuts down all write journals, sets the
// current UID and verifying key to zero, and returns once all
// shutdowns are complete. It is safe to call multiple times in a row,
// and once this is called, EnableExistingJournals may be called
// again.
func (j *JournalServer) shutdownExistingJournals(ctx context.Context) {
j.lock.Lock()
defer j.lock.Unlock()
j.shutdownExistingJournalsLocked(ctx)
}
func (j *JournalServer) shutdown() {
j.log.CDebugf(context.Background(), "Shutting down journal")
j.lock.Lock()
defer j.lock.Unlock()
for _, tlfJournal := range j.tlfJournals {
tlfJournal.shutdown()
}
// Leave all the tlfJournals in j.tlfJournals, so that any
// access to them errors out instead of mutating the journal.
}
| 1 | 15,546 | This wording is a bit ambiguos, I first thought it meant the directory has no entries in it. maybe "dir" -> "dir string"? | keybase-kbfs | go |
@@ -53,6 +53,9 @@ namespace Kokkos {
namespace Experimental {
bool HPX::m_hpx_initialized = false;
+bool HPX::m_was_initialized = false;
+bool HPX::m_was_finalized = false;
+
std::atomic<uint32_t> HPX::m_next_instance_id{1};
#if defined(KOKKOS_ENABLE_HPX_ASYNC_DISPATCH)
std::atomic<uint32_t> HPX::m_active_parallel_region_count{0}; | 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 ([email protected])
//
// ************************************************************************
//@HEADER
*/
#include <Kokkos_Core.hpp>
#ifdef KOKKOS_ENABLE_HPX
#include <Kokkos_HPX.hpp>
#include <hpx/util/yield_while.hpp>
namespace Kokkos {
namespace Experimental {
bool HPX::m_hpx_initialized = false;
std::atomic<uint32_t> HPX::m_next_instance_id{1};
#if defined(KOKKOS_ENABLE_HPX_ASYNC_DISPATCH)
std::atomic<uint32_t> HPX::m_active_parallel_region_count{0};
HPX::instance_data HPX::m_global_instance_data;
#else
Kokkos::Impl::thread_buffer HPX::m_global_buffer;
#endif
int HPX::concurrency() {
hpx::runtime *rt = hpx::get_runtime_ptr();
if (rt == nullptr) {
return hpx::threads::hardware_concurrency();
} else {
if (hpx::threads::get_self_ptr() == nullptr) {
return hpx::resource::get_thread_pool(0).get_os_thread_count();
} else {
return hpx::this_thread::get_pool()->get_os_thread_count();
}
}
}
void HPX::impl_initialize(int thread_count) {
hpx::runtime *rt = hpx::get_runtime_ptr();
if (rt == nullptr) {
std::vector<std::string> config = {
"hpx.os_threads=" + std::to_string(thread_count),
#ifdef KOKKOS_ENABLE_DEBUG
"--hpx:attach-debugger=exception",
#endif
};
int argc_hpx = 1;
char name[] = "kokkos_hpx";
char *argv_hpx[] = {name, nullptr};
hpx::start(nullptr, argc_hpx, argv_hpx, config);
#if HPX_VERSION_FULL < 0x010400
// This has been fixed in HPX 1.4.0.
//
// NOTE: Wait for runtime to start. hpx::start returns as soon as
// possible, meaning some operations are not allowed immediately
// after hpx::start. Notably, hpx::stop needs state_running. This
// needs to be fixed in HPX itself.
// Get runtime pointer again after it has been started.
rt = hpx::get_runtime_ptr();
hpx::util::yield_while(
[rt]() { return rt->get_state() < hpx::state_running; });
#endif
m_hpx_initialized = true;
}
}
void HPX::impl_initialize() {
hpx::runtime *rt = hpx::get_runtime_ptr();
if (rt == nullptr) {
std::vector<std::string> config = {
#ifdef KOKKOS_ENABLE_DEBUG
"--hpx:attach-debugger=exception",
#endif
};
int argc_hpx = 1;
char name[] = "kokkos_hpx";
char *argv_hpx[] = {name, nullptr};
hpx::start(nullptr, argc_hpx, argv_hpx, config);
// NOTE: Wait for runtime to start. hpx::start returns as soon as
// possible, meaning some operations are not allowed immediately
// after hpx::start. Notably, hpx::stop needs state_running. This
// needs to be fixed in HPX itself.
// Get runtime pointer again after it has been started.
rt = hpx::get_runtime_ptr();
hpx::util::yield_while(
[rt]() { return rt->get_state() < hpx::state_running; });
m_hpx_initialized = true;
}
}
bool HPX::impl_is_initialized() noexcept {
hpx::runtime *rt = hpx::get_runtime_ptr();
return rt != nullptr;
}
void HPX::impl_finalize() {
if (m_hpx_initialized) {
hpx::runtime *rt = hpx::get_runtime_ptr();
if (rt != nullptr) {
hpx::apply([]() { hpx::finalize(); });
hpx::stop();
} else {
Kokkos::abort(
"Kokkos::Experimental::HPX::impl_finalize: Kokkos started "
"HPX but something else already stopped HPX\n");
}
}
}
} // namespace Experimental
namespace Impl {
int g_hpx_space_factory_initialized =
initialize_space_factory<HPXSpaceInitializer>("060_HPX");
void HPXSpaceInitializer::initialize(const InitArguments &args) {
const int num_threads = args.num_threads;
if (std::is_same<Kokkos::Experimental::HPX,
Kokkos::DefaultExecutionSpace>::value ||
std::is_same<Kokkos::Experimental::HPX,
Kokkos::HostSpace::execution_space>::value) {
if (num_threads > 0) {
Kokkos::Experimental::HPX::impl_initialize(num_threads);
} else {
Kokkos::Experimental::HPX::impl_initialize();
}
// std::cout << "Kokkos::initialize() fyi: HPX enabled and initialized" <<
// std::endl ;
} else {
// std::cout << "Kokkos::initialize() fyi: HPX enabled but not initialized"
// << std::endl ;
}
}
void HPXSpaceInitializer::finalize(const bool all_spaces) {
if (std::is_same<Kokkos::Experimental::HPX,
Kokkos::DefaultExecutionSpace>::value ||
std::is_same<Kokkos::Experimental::HPX,
Kokkos::HostSpace::execution_space>::value ||
all_spaces) {
if (Kokkos::Experimental::HPX::impl_is_initialized())
Kokkos::Experimental::HPX::impl_finalize();
}
}
void HPXSpaceInitializer::fence() { Kokkos::Experimental::HPX().fence(); }
void HPXSpaceInitializer::fence(const std::string &name) {
Kokkos::Experimental::HPX().fence(name);
}
void HPXSpaceInitializer::print_configuration(std::ostream &msg,
const bool detail) {
msg << "HPX Execution Space:" << std::endl;
msg << " KOKKOS_ENABLE_HPX: ";
msg << "yes" << std::endl;
msg << "\nHPX Runtime Configuration:" << std::endl;
Kokkos::Experimental::HPX::print_configuration(msg, detail);
}
} // namespace Impl
} // namespace Kokkos
#else
void KOKKOS_CORE_SRC_IMPL_HPX_PREVENT_LINK_ERROR() {}
#endif //#ifdef KOKKOS_ENABLE_HPX
| 1 | 30,630 | Why do we need both `HPX::m_hpx_initialized` and `HPX:: m_was_initialized`? | kokkos-kokkos | cpp |
@@ -108,8 +108,8 @@ func NewMetadata(
}
versionToClusterName[info.InitialFailoverVersion] = clusterName
- if info.Enabled && (len(info.RPCName) == 0 || len(info.RPCAddress) == 0) {
- panic(fmt.Sprintf("Cluster %v: rpc name / address is empty", clusterName))
+ if info.Enabled && info.RPCAddress == "" {
+ panic(fmt.Sprintf("Cluster %v: RPCAddress is empty", clusterName))
}
}
| 1 | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice 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.
//go:generate mockgen -copyright_file ../../LICENSE -package $GOPACKAGE -source $GOFILE -destination metadata_mock.go
package cluster
import (
"fmt"
"go.temporal.io/server/common"
"go.temporal.io/server/common/config"
"go.temporal.io/server/common/log"
)
type (
// Metadata provides information about clusters
Metadata interface {
// IsGlobalNamespaceEnabled whether the global namespace is enabled,
// this attr should be discarded when cross DC is made public
IsGlobalNamespaceEnabled() bool
// IsMasterCluster whether current cluster is master cluster
IsMasterCluster() bool
// GetNextFailoverVersion return the next failover version for namespace failover
GetNextFailoverVersion(string, int64) int64
// IsVersionFromSameCluster return true if 2 version are used for the same cluster
IsVersionFromSameCluster(version1 int64, version2 int64) bool
// GetMasterClusterName return the master cluster name
GetMasterClusterName() string
// GetCurrentClusterName return the current cluster name
GetCurrentClusterName() string
// GetAllClusterInfo return the all cluster name -> corresponding info
GetAllClusterInfo() map[string]config.ClusterInformation
// ClusterNameForFailoverVersion return the corresponding cluster name for a given failover version
ClusterNameForFailoverVersion(failoverVersion int64) string
}
metadataImpl struct {
logger log.Logger
// EnableGlobalNamespace whether the global namespace is enabled,
enableGlobalNamespace bool
// failoverVersionIncrement is the increment of each cluster's version when failover happen
failoverVersionIncrement int64
// masterClusterName is the name of the master cluster, only the master cluster can register / update namespace
// all clusters can do namespace failover
masterClusterName string
// currentClusterName is the name of the current cluster
currentClusterName string
// clusterInfo contains all cluster name -> corresponding information
clusterInfo map[string]config.ClusterInformation
// versionToClusterName contains all initial version -> corresponding cluster name
versionToClusterName map[int64]string
}
)
// NewMetadata create a new instance of Metadata
func NewMetadata(
logger log.Logger,
enableGlobalNamespace bool,
failoverVersionIncrement int64,
masterClusterName string,
currentClusterName string,
clusterInfo map[string]config.ClusterInformation,
) Metadata {
if len(clusterInfo) == 0 {
panic("Empty cluster information")
} else if len(masterClusterName) == 0 {
panic("Master cluster name is empty")
} else if len(currentClusterName) == 0 {
panic("Current cluster name is empty")
} else if failoverVersionIncrement == 0 {
panic("Version increment is 0")
}
versionToClusterName := make(map[int64]string)
for clusterName, info := range clusterInfo {
if failoverVersionIncrement <= info.InitialFailoverVersion || info.InitialFailoverVersion <= 0 {
panic(fmt.Sprintf(
"Version increment %v is smaller than initial version: %v.",
failoverVersionIncrement,
info.InitialFailoverVersion,
))
}
if len(clusterName) == 0 {
panic("Cluster name in all cluster names is empty")
}
versionToClusterName[info.InitialFailoverVersion] = clusterName
if info.Enabled && (len(info.RPCName) == 0 || len(info.RPCAddress) == 0) {
panic(fmt.Sprintf("Cluster %v: rpc name / address is empty", clusterName))
}
}
if _, ok := clusterInfo[currentClusterName]; !ok {
panic("Current cluster is not specified in cluster info")
}
if _, ok := clusterInfo[masterClusterName]; !ok {
panic("Master cluster is not specified in cluster info")
}
if len(versionToClusterName) != len(clusterInfo) {
panic("Cluster info initial versions have duplicates")
}
return &metadataImpl{
logger: logger,
enableGlobalNamespace: enableGlobalNamespace,
failoverVersionIncrement: failoverVersionIncrement,
masterClusterName: masterClusterName,
currentClusterName: currentClusterName,
clusterInfo: clusterInfo,
versionToClusterName: versionToClusterName,
}
}
// IsGlobalNamespaceEnabled whether the global namespace is enabled,
// this attr should be discarded when cross DC is made public
func (metadata *metadataImpl) IsGlobalNamespaceEnabled() bool {
return metadata.enableGlobalNamespace
}
// GetNextFailoverVersion return the next failover version based on input
func (metadata *metadataImpl) GetNextFailoverVersion(cluster string, currentFailoverVersion int64) int64 {
info, ok := metadata.clusterInfo[cluster]
if !ok {
panic(fmt.Sprintf(
"Unknown cluster name: %v with given cluster initial failover version map: %v.",
cluster,
metadata.clusterInfo,
))
}
failoverVersion := currentFailoverVersion/metadata.failoverVersionIncrement*metadata.failoverVersionIncrement + info.InitialFailoverVersion
if failoverVersion < currentFailoverVersion {
return failoverVersion + metadata.failoverVersionIncrement
}
return failoverVersion
}
// IsVersionFromSameCluster return true if 2 version are used for the same cluster
func (metadata *metadataImpl) IsVersionFromSameCluster(version1 int64, version2 int64) bool {
return (version1-version2)%metadata.failoverVersionIncrement == 0
}
func (metadata *metadataImpl) IsMasterCluster() bool {
return metadata.masterClusterName == metadata.currentClusterName
}
// GetMasterClusterName return the master cluster name
func (metadata *metadataImpl) GetMasterClusterName() string {
return metadata.masterClusterName
}
// GetCurrentClusterName return the current cluster name
func (metadata *metadataImpl) GetCurrentClusterName() string {
return metadata.currentClusterName
}
// GetAllClusterInfo return the all cluster name -> corresponding information
func (metadata *metadataImpl) GetAllClusterInfo() map[string]config.ClusterInformation {
return metadata.clusterInfo
}
// ClusterNameForFailoverVersion return the corresponding cluster name for a given failover version
func (metadata *metadataImpl) ClusterNameForFailoverVersion(failoverVersion int64) string {
if failoverVersion == common.EmptyVersion {
return metadata.currentClusterName
}
initialFailoverVersion := failoverVersion % metadata.failoverVersionIncrement
// Failover version starts with 1. Zero is an invalid value for failover version
if initialFailoverVersion == common.EmptyVersion {
initialFailoverVersion = metadata.failoverVersionIncrement
}
clusterName, ok := metadata.versionToClusterName[initialFailoverVersion]
if !ok {
panic(fmt.Sprintf(
"Unknown initial failover version %v with given cluster initial failover version map: %v and failover version increment %v.",
initialFailoverVersion,
metadata.clusterInfo,
metadata.failoverVersionIncrement,
))
}
return clusterName
}
| 1 | 11,465 | also check RPCName? | temporalio-temporal | go |
@@ -76,9 +76,11 @@ import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserSer
import org.springframework.security.oauth2.client.web.server.AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.server.OAuth2AuthorizationCodeGrantWebFilter;
import org.springframework.security.oauth2.client.web.server.OAuth2AuthorizationRequestRedirectWebFilter;
+import org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationCodeAuthenticationTokenConverter;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
+import org.springframework.security.oauth2.client.web.server.WebSessionOAuth2ServerAuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.server.authentication.OAuth2LoginAuthenticationWebFilter;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.oidc.user.OidcUser; | 1 | /*
* Copyright 2002-2019 the original author or 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 org.springframework.security.config.web.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.server.WebSessionOAuth2ServerAuthorizationRequestRepository;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.DelegatingReactiveAuthenticationManager;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver;
import org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager;
import org.springframework.security.authorization.AuthorityReactiveAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeReactiveAuthenticationManager;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginReactiveAuthenticationManager;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.WebClientReactiveAuthorizationCodeTokenResponseClient;
import org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.userinfo.DefaultReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.web.server.AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.server.OAuth2AuthorizationCodeGrantWebFilter;
import org.springframework.security.oauth2.client.web.server.OAuth2AuthorizationRequestRedirectWebFilter;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationCodeAuthenticationTokenConverter;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.server.authentication.OAuth2LoginAuthenticationWebFilter;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtReactiveAuthenticationManager;
import org.springframework.security.oauth2.server.resource.authentication.OpaqueTokenReactiveAuthenticationManager;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.oauth2.server.resource.introspection.NimbusReactiveOpaqueTokenIntrospector;
import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
import org.springframework.security.oauth2.server.resource.web.access.server.BearerTokenServerAccessDeniedHandler;
import org.springframework.security.oauth2.server.resource.web.server.BearerTokenServerAuthenticationEntryPoint;
import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor;
import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;
import org.springframework.security.web.server.DelegatingServerAuthenticationEntryPoint;
import org.springframework.security.web.server.MatcherSecurityWebFilterChain;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.AnonymousAuthenticationWebFilter;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.ReactivePreAuthenticatedAuthenticationManager;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationFailureHandler;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.authentication.ServerFormLoginAuthenticationConverter;
import org.springframework.security.web.server.authentication.ServerHttpBasicAuthenticationConverter;
import org.springframework.security.web.server.authentication.ServerX509AuthenticationConverter;
import org.springframework.security.web.server.authentication.logout.DelegatingServerLogoutHandler;
import org.springframework.security.web.server.authentication.logout.LogoutWebFilter;
import org.springframework.security.web.server.authentication.logout.SecurityContextServerLogoutHandler;
import org.springframework.security.web.server.authentication.logout.ServerLogoutHandler;
import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.security.web.server.authorization.AuthorizationWebFilter;
import org.springframework.security.web.server.authorization.DelegatingReactiveAuthorizationManager;
import org.springframework.security.web.server.authorization.ExceptionTranslationWebFilter;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.security.web.server.authorization.ServerWebExchangeDelegatingServerAccessDeniedHandler;
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository;
import org.springframework.security.web.server.context.ReactorContextWebFilter;
import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository;
import org.springframework.security.web.server.csrf.CsrfServerLogoutHandler;
import org.springframework.security.web.server.csrf.CsrfWebFilter;
import org.springframework.security.web.server.csrf.ServerCsrfTokenRepository;
import org.springframework.security.web.server.csrf.WebSessionServerCsrfTokenRepository;
import org.springframework.security.web.server.header.CacheControlServerHttpHeadersWriter;
import org.springframework.security.web.server.header.CompositeServerHttpHeadersWriter;
import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter;
import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter;
import org.springframework.security.web.server.header.FeaturePolicyServerHttpHeadersWriter;
import org.springframework.security.web.server.header.HttpHeaderWriterWebFilter;
import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter;
import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy;
import org.springframework.security.web.server.header.ServerHttpHeadersWriter;
import org.springframework.security.web.server.header.StrictTransportSecurityServerHttpHeadersWriter;
import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter;
import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter;
import org.springframework.security.web.server.savedrequest.NoOpServerRequestCache;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.security.web.server.savedrequest.ServerRequestCacheWebFilter;
import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache;
import org.springframework.security.web.server.transport.HttpsRedirectWebFilter;
import org.springframework.security.web.server.ui.LoginPageGeneratingWebFilter;
import org.springframework.security.web.server.ui.LogoutPageGeneratingWebFilter;
import org.springframework.security.web.server.util.matcher.AndServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.MediaTypeServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.NegatedServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.OrServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsProcessor;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.DefaultCorsProcessor;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import static org.springframework.security.web.server.DelegatingServerAuthenticationEntryPoint.DelegateEntry;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.match;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.notMatch;
/**
* A {@link ServerHttpSecurity} is similar to Spring Security's {@code HttpSecurity} but for WebFlux.
* It allows configuring web based security for specific http requests. By default it will be applied
* to all requests, but can be restricted using {@link #securityMatcher(ServerWebExchangeMatcher)} or
* other similar methods.
*
* A minimal configuration can be found below:
*
* <pre class="code">
* @EnableWebFluxSecurity
* public class MyMinimalSecurityConfiguration {
*
* @Bean
* public MapReactiveUserDetailsService userDetailsService() {
* UserDetails user = User.withDefaultPasswordEncoder()
* .username("user")
* .password("password")
* .roles("USER")
* .build();
* return new MapReactiveUserDetailsService(user);
* }
* }
*
* Below is the same as our minimal configuration, but explicitly declaring the
* {@code ServerHttpSecurity}.
*
* <pre class="code">
* @EnableWebFluxSecurity
* public class MyExplicitSecurityConfiguration {
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* .authorizeExchange()
* .anyExchange().authenticated()
* .and()
* .httpBasic().and()
* .formLogin();
* return http.build();
* }
*
* @Bean
* public MapReactiveUserDetailsService userDetailsService() {
* UserDetails user = User.withDefaultPasswordEncoder()
* .username("user")
* .password("password")
* .roles("USER")
* .build();
* return new MapReactiveUserDetailsService(user);
* }
* }
*
* @author Rob Winch
* @author Vedran Pavic
* @author Rafiullah Hamedy
* @author Eddú Meléndez
* @author Joe Grandja
* @since 5.0
*/
public class ServerHttpSecurity {
private ServerWebExchangeMatcher securityMatcher = ServerWebExchangeMatchers.anyExchange();
private AuthorizeExchangeSpec authorizeExchange;
private HttpsRedirectSpec httpsRedirectSpec;
private HeaderSpec headers = new HeaderSpec();
private CsrfSpec csrf = new CsrfSpec();
private CorsSpec cors = new CorsSpec();
private ExceptionHandlingSpec exceptionHandling = new ExceptionHandlingSpec();
private HttpBasicSpec httpBasic;
private X509Spec x509;
private final RequestCacheSpec requestCache = new RequestCacheSpec();
private FormLoginSpec formLogin;
private OAuth2LoginSpec oauth2Login;
private OAuth2ResourceServerSpec resourceServer;
private OAuth2ClientSpec client;
private LogoutSpec logout = new LogoutSpec();
private LoginPageSpec loginPage = new LoginPageSpec();
private ReactiveAuthenticationManager authenticationManager;
private ServerSecurityContextRepository securityContextRepository;
private ServerAuthenticationEntryPoint authenticationEntryPoint;
private List<DelegateEntry> defaultEntryPoints = new ArrayList<>();
private ServerAccessDeniedHandler accessDeniedHandler;
private List<ServerWebExchangeDelegatingServerAccessDeniedHandler.DelegateEntry>
defaultAccessDeniedHandlers = new ArrayList<>();
private List<WebFilter> webFilters = new ArrayList<>();
private ApplicationContext context;
private Throwable built;
private AnonymousSpec anonymous;
/**
* The ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
*
* @param matcher the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
* Default is all requests.
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity securityMatcher(ServerWebExchangeMatcher matcher) {
Assert.notNull(matcher, "matcher cannot be null");
this.securityMatcher = matcher;
return this;
}
/**
* Adds a {@link WebFilter} at a specific position.
* @param webFilter the {@link WebFilter} to add
* @param order the place to insert the {@link WebFilter}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity addFilterAt(WebFilter webFilter, SecurityWebFiltersOrder order) {
this.webFilters.add(new OrderedWebFilter(webFilter, order.getOrder()));
return this;
}
/**
* Adds a {@link WebFilter} before specific position.
* @param webFilter the {@link WebFilter} to add
* @param order the place before which to insert the {@link WebFilter}
* @return the {@link ServerHttpSecurity} to continue configuring
* @since 5.2.0
* @author Ankur Pathak
*/
public ServerHttpSecurity addFilterBefore(WebFilter webFilter, SecurityWebFiltersOrder order) {
this.webFilters.add(new OrderedWebFilter(webFilter, order.getOrder() - 1));
return this;
}
/**
* Adds a {@link WebFilter} after specific position.
* @param webFilter the {@link WebFilter} to add
* @param order the place after which to insert the {@link WebFilter}
* @return the {@link ServerHttpSecurity} to continue configuring
* @since 5.2.0
* @author Ankur Pathak
*/
public ServerHttpSecurity addFilterAfter(WebFilter webFilter, SecurityWebFiltersOrder order) {
this.webFilters.add(new OrderedWebFilter(webFilter, order.getOrder() + 1));
return this;
}
/**
* Gets the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
* @return the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
*/
private ServerWebExchangeMatcher getSecurityMatcher() {
return this.securityMatcher;
}
/**
* The strategy used with {@code ReactorContextWebFilter}. It does impact how the {@code SecurityContext} is
* saved which is configured on a per {@link AuthenticationWebFilter} basis.
* @param securityContextRepository the repository to use
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity securityContextRepository(ServerSecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
return this;
}
/**
* Configures HTTPS redirection rules. If the default is used:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .redirectToHttps();
* return http.build();
* }
* </pre>
*
* Then all non-HTTPS requests will be redirected to HTTPS.
*
* Typically, all requests should be HTTPS; however, the focus for redirection can also be narrowed:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .redirectToHttps()
* .httpsRedirectWhen(serverWebExchange ->
* serverWebExchange.getRequest().getHeaders().containsKey("X-Requires-Https"))
* return http.build();
* }
* </pre>
*
* @return the {@link HttpsRedirectSpec} to customize
*/
public HttpsRedirectSpec redirectToHttps() {
this.httpsRedirectSpec = new HttpsRedirectSpec();
return this.httpsRedirectSpec;
}
/**
* Configures HTTPS redirection rules. If the default is used:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .redirectToHttps(withDefaults());
* return http.build();
* }
* </pre>
*
* Then all non-HTTPS requests will be redirected to HTTPS.
*
* Typically, all requests should be HTTPS; however, the focus for redirection can also be narrowed:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .redirectToHttps(redirectToHttps ->
* redirectToHttps
* .httpsRedirectWhen(serverWebExchange ->
* serverWebExchange.getRequest().getHeaders().containsKey("X-Requires-Https"))
* );
* return http.build();
* }
* </pre>
*
* @param httpsRedirectCustomizer the {@link Customizer} to provide more options for
* the {@link HttpsRedirectSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity redirectToHttps(Customizer<HttpsRedirectSpec> httpsRedirectCustomizer) {
this.httpsRedirectSpec = new HttpsRedirectSpec();
httpsRedirectCustomizer.customize(this.httpsRedirectSpec);
return this;
}
/**
* Configures <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet">CSRF Protection</a>
* which is enabled by default. You can disable it using:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .csrf().disabled();
* return http.build();
* }
* </pre>
*
* Additional configuration options can be seen below:
*
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .csrf()
* // Handle CSRF failures
* .accessDeniedHandler(accessDeniedHandler)
* // Custom persistence of CSRF Token
* .csrfTokenRepository(csrfTokenRepository)
* // custom matching when CSRF protection is enabled
* .requireCsrfProtectionMatcher(matcher);
* return http.build();
* }
* </pre>
*
* @return the {@link CsrfSpec} to customize
*/
public CsrfSpec csrf() {
if (this.csrf == null) {
this.csrf = new CsrfSpec();
}
return this.csrf;
}
/**
* Configures <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet">CSRF Protection</a>
* which is enabled by default. You can disable it using:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .csrf(csrf ->
* csrf.disabled()
* );
* return http.build();
* }
* </pre>
*
* Additional configuration options can be seen below:
*
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .csrf(csrf ->
* csrf
* // Handle CSRF failures
* .accessDeniedHandler(accessDeniedHandler)
* // Custom persistence of CSRF Token
* .csrfTokenRepository(csrfTokenRepository)
* // custom matching when CSRF protection is enabled
* .requireCsrfProtectionMatcher(matcher)
* );
* return http.build();
* }
* </pre>
*
* @param csrfCustomizer the {@link Customizer} to provide more options for
* the {@link CsrfSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity csrf(Customizer<CsrfSpec> csrfCustomizer) {
if (this.csrf == null) {
this.csrf = new CsrfSpec();
}
csrfCustomizer.customize(this.csrf);
return this;
}
/**
* Configures CORS headers. By default if a {@link CorsConfigurationSource} Bean is found, it will be used
* to create a {@link CorsWebFilter}. If {@link CorsSpec#configurationSource(CorsConfigurationSource)} is invoked
* it will be used instead. If neither has been configured, the Cors configuration will do nothing.
* @return the {@link CorsSpec} to customize
*/
public CorsSpec cors() {
if (this.cors == null) {
this.cors = new CorsSpec();
}
return this.cors;
}
/**
* Configures CORS headers. By default if a {@link CorsConfigurationSource} Bean is found, it will be used
* to create a {@link CorsWebFilter}. If {@link CorsSpec#configurationSource(CorsConfigurationSource)} is invoked
* it will be used instead. If neither has been configured, the Cors configuration will do nothing.
*
* @param corsCustomizer the {@link Customizer} to provide more options for
* the {@link CorsSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity cors(Customizer<CorsSpec> corsCustomizer) {
if (this.cors == null) {
this.cors = new CorsSpec();
}
corsCustomizer.customize(this.cors);
return this;
}
/**
* Enables and Configures anonymous authentication. Anonymous Authentication is disabled by default.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .anonymous().key("key")
* .authorities("ROLE_ANONYMOUS");
* return http.build();
* }
* </pre>
* @return the {@link AnonymousSpec} to customize
* @since 5.2.0
* @author Ankur Pathak
*/
public AnonymousSpec anonymous(){
if (this.anonymous == null) {
this.anonymous = new AnonymousSpec();
}
return this.anonymous;
}
/**
* Enables and Configures anonymous authentication. Anonymous Authentication is disabled by default.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .anonymous(anonymous ->
* anonymous
* .key("key")
* .authorities("ROLE_ANONYMOUS")
* );
* return http.build();
* }
* </pre>
*
* @param anonymousCustomizer the {@link Customizer} to provide more options for
* the {@link AnonymousSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity anonymous(Customizer<AnonymousSpec> anonymousCustomizer) {
if (this.anonymous == null) {
this.anonymous = new AnonymousSpec();
}
anonymousCustomizer.customize(this.anonymous);
return this;
}
/**
* Configures CORS support within Spring Security. This ensures that the {@link CorsWebFilter} is place in the
* correct order.
*/
public class CorsSpec {
private CorsWebFilter corsFilter;
/**
* Configures the {@link CorsConfigurationSource} to be used
* @param source the source to use
* @return the {@link CorsSpec} for additional configuration
*/
public CorsSpec configurationSource(CorsConfigurationSource source) {
this.corsFilter = new CorsWebFilter(source);
return this;
}
/**
* Disables CORS support within Spring Security.
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.cors = null;
return ServerHttpSecurity.this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
CorsWebFilter corsFilter = getCorsFilter();
if (corsFilter != null) {
http.addFilterAt(this.corsFilter, SecurityWebFiltersOrder.CORS);
}
}
private CorsWebFilter getCorsFilter() {
if (this.corsFilter != null) {
return this.corsFilter;
}
CorsConfigurationSource source = getBeanOrNull(CorsConfigurationSource.class);
if (source == null) {
return null;
}
CorsProcessor processor = getBeanOrNull(CorsProcessor.class);
if (processor == null) {
processor = new DefaultCorsProcessor();
}
this.corsFilter = new CorsWebFilter(source, processor);
return this.corsFilter;
}
private CorsSpec() {}
}
/**
* Configures HTTP Basic authentication. An example configuration is provided below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .httpBasic()
* // used for authenticating the credentials
* .authenticationManager(authenticationManager)
* // Custom persistence of the authentication
* .securityContextRepository(securityContextRepository);
* return http.build();
* }
* </pre>
*
* @return the {@link HttpBasicSpec} to customize
*/
public HttpBasicSpec httpBasic() {
if (this.httpBasic == null) {
this.httpBasic = new HttpBasicSpec();
}
return this.httpBasic;
}
/**
* Configures HTTP Basic authentication. An example configuration is provided below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .httpBasic(httpBasic ->
* httpBasic
* // used for authenticating the credentials
* .authenticationManager(authenticationManager)
* // Custom persistence of the authentication
* .securityContextRepository(securityContextRepository)
* );
* return http.build();
* }
* </pre>
*
* @param httpBasicCustomizer the {@link Customizer} to provide more options for
* the {@link HttpBasicSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity httpBasic(Customizer<HttpBasicSpec> httpBasicCustomizer) {
if (this.httpBasic == null) {
this.httpBasic = new HttpBasicSpec();
}
httpBasicCustomizer.customize(this.httpBasic);
return this;
}
/**
* Configures form based authentication. An example configuration is provided below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .formLogin()
* // used for authenticating the credentials
* .authenticationManager(authenticationManager)
* // Custom persistence of the authentication
* .securityContextRepository(securityContextRepository)
* // expect a log in page at "/authenticate"
* // a POST "/authenticate" is where authentication occurs
* // error page at "/authenticate?error"
* .loginPage("/authenticate");
* return http.build();
* }
* </pre>
*
* @return the {@link FormLoginSpec} to customize
*/
public FormLoginSpec formLogin() {
if (this.formLogin == null) {
this.formLogin = new FormLoginSpec();
}
return this.formLogin;
}
/**
* Configures form based authentication. An example configuration is provided below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .formLogin(formLogin ->
* formLogin
* // used for authenticating the credentials
* .authenticationManager(authenticationManager)
* // Custom persistence of the authentication
* .securityContextRepository(securityContextRepository)
* // expect a log in page at "/authenticate"
* // a POST "/authenticate" is where authentication occurs
* // error page at "/authenticate?error"
* .loginPage("/authenticate")
* );
* return http.build();
* }
* </pre>
*
* @param formLoginCustomizer the {@link Customizer} to provide more options for
* the {@link FormLoginSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity formLogin(Customizer<FormLoginSpec> formLoginCustomizer) {
if (this.formLogin == null) {
this.formLogin = new FormLoginSpec();
}
formLoginCustomizer.customize(this.formLogin);
return this;
}
/**
* Configures x509 authentication using a certificate provided by a client.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* .x509()
* .authenticationManager(authenticationManager)
* .principalExtractor(principalExtractor);
* return http.build();
* }
* </pre>
*
* Note that if extractor is not specified, {@link SubjectDnX509PrincipalExtractor} will be used.
* If authenticationManager is not specified, {@link ReactivePreAuthenticatedAuthenticationManager} will be used.
*
* @return the {@link X509Spec} to customize
* @author Alexey Nesterov
* @since 5.2
*/
public X509Spec x509() {
if (this.x509 == null) {
this.x509 = new X509Spec();
}
return this.x509;
}
/**
* Configures x509 authentication using a certificate provided by a client.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* .x509(x509 ->
* x509
* .authenticationManager(authenticationManager)
* .principalExtractor(principalExtractor)
* );
* return http.build();
* }
* </pre>
*
* Note that if extractor is not specified, {@link SubjectDnX509PrincipalExtractor} will be used.
* If authenticationManager is not specified, {@link ReactivePreAuthenticatedAuthenticationManager} will be used.
*
* @since 5.2
* @param x509Customizer the {@link Customizer} to provide more options for
* the {@link X509Spec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity x509(Customizer<X509Spec> x509Customizer) {
if (this.x509 == null) {
this.x509 = new X509Spec();
}
x509Customizer.customize(this.x509);
return this;
}
/**
* Configures X509 authentication
*
* @author Alexey Nesterov
* @since 5.2
* @see #x509()
*/
public class X509Spec {
private X509PrincipalExtractor principalExtractor;
private ReactiveAuthenticationManager authenticationManager;
public X509Spec principalExtractor(X509PrincipalExtractor principalExtractor) {
this.principalExtractor = principalExtractor;
return this;
}
public X509Spec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
ReactiveAuthenticationManager authenticationManager = getAuthenticationManager();
X509PrincipalExtractor principalExtractor = getPrincipalExtractor();
AuthenticationWebFilter filter = new AuthenticationWebFilter(authenticationManager);
filter.setServerAuthenticationConverter(new ServerX509AuthenticationConverter(principalExtractor));
http.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION);
}
private X509PrincipalExtractor getPrincipalExtractor() {
if (this.principalExtractor != null) {
return this.principalExtractor;
}
return new SubjectDnX509PrincipalExtractor();
}
private ReactiveAuthenticationManager getAuthenticationManager() {
if (this.authenticationManager != null) {
return this.authenticationManager;
}
ReactiveUserDetailsService userDetailsService = getBean(ReactiveUserDetailsService.class);
ReactivePreAuthenticatedAuthenticationManager authenticationManager = new ReactivePreAuthenticatedAuthenticationManager(userDetailsService);
return authenticationManager;
}
private X509Spec() {
}
}
/**
* Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .oauth2Login()
* .authenticationConverter(authenticationConverter)
* .authenticationManager(manager);
* return http.build();
* }
* </pre>
*
*
* @return the {@link OAuth2LoginSpec} to customize
*/
public OAuth2LoginSpec oauth2Login() {
if (this.oauth2Login == null) {
this.oauth2Login = new OAuth2LoginSpec();
}
return this.oauth2Login;
}
/**
* Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .oauth2Login(oauth2Login ->
* oauth2Login
* .authenticationConverter(authenticationConverter)
* .authenticationManager(manager)
* );
* return http.build();
* }
* </pre>
*
* @param oauth2LoginCustomizer the {@link Customizer} to provide more options for
* the {@link OAuth2LoginSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity oauth2Login(Customizer<OAuth2LoginSpec> oauth2LoginCustomizer) {
if (this.oauth2Login == null) {
this.oauth2Login = new OAuth2LoginSpec();
}
oauth2LoginCustomizer.customize(this.oauth2Login);
return this;
}
public class OAuth2LoginSpec {
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
private ReactiveAuthenticationManager authenticationManager;
private ServerSecurityContextRepository securityContextRepository;
private ServerAuthenticationConverter authenticationConverter;
private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver;
private ServerWebExchangeMatcher authenticationMatcher;
private ServerAuthenticationSuccessHandler authenticationSuccessHandler = new RedirectServerAuthenticationSuccessHandler();
private ServerAuthenticationFailureHandler authenticationFailureHandler;
/**
* Configures the {@link ReactiveAuthenticationManager} to use. The default is
* {@link OAuth2AuthorizationCodeReactiveAuthenticationManager}
* @param authenticationManager the manager to use
* @return the {@link OAuth2LoginSpec} to customize
*/
public OAuth2LoginSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
/**
* The {@link ServerSecurityContextRepository} used to save the {@code Authentication}. Defaults to
* {@link WebSessionServerSecurityContextRepository}.
*
* @since 5.2
* @param securityContextRepository the repository to use
* @return the {@link OAuth2LoginSpec} to continue configuring
*/
public OAuth2LoginSpec securityContextRepository(ServerSecurityContextRepository securityContextRepository) {
this.securityContextRepository = securityContextRepository;
return this;
}
/**
* The {@link ServerAuthenticationSuccessHandler} used after authentication success. Defaults to
* {@link RedirectServerAuthenticationSuccessHandler} redirecting to "/".
*
* @since 5.2
* @param authenticationSuccessHandler the success handler to use
* @return the {@link OAuth2LoginSpec} to customize
*/
public OAuth2LoginSpec authenticationSuccessHandler(ServerAuthenticationSuccessHandler authenticationSuccessHandler) {
Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");
this.authenticationSuccessHandler = authenticationSuccessHandler;
return this;
}
/**
* The {@link ServerAuthenticationFailureHandler} used after authentication failure.
* Defaults to {@link RedirectServerAuthenticationFailureHandler} redirecting to "/login?error".
*
* @since 5.2
* @param authenticationFailureHandler the failure handler to use
* @return the {@link OAuth2LoginSpec} to customize
*/
public OAuth2LoginSpec authenticationFailureHandler(ServerAuthenticationFailureHandler authenticationFailureHandler) {
Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null");
this.authenticationFailureHandler = authenticationFailureHandler;
return this;
}
/**
* Gets the {@link ReactiveAuthenticationManager} to use. First tries an explicitly configured manager, and
* defaults to {@link OAuth2AuthorizationCodeReactiveAuthenticationManager}
*
* @return the {@link ReactiveAuthenticationManager} to use
*/
private ReactiveAuthenticationManager getAuthenticationManager() {
if (this.authenticationManager == null) {
this.authenticationManager = createDefault();
}
return this.authenticationManager;
}
private ReactiveAuthenticationManager createDefault() {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> client = getAccessTokenResponseClient();
ReactiveAuthenticationManager result = new OAuth2LoginReactiveAuthenticationManager(client, getOauth2UserService());
boolean oidcAuthenticationProviderEnabled = ClassUtils.isPresent(
"org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader());
if (oidcAuthenticationProviderEnabled) {
OidcAuthorizationCodeReactiveAuthenticationManager oidc =
new OidcAuthorizationCodeReactiveAuthenticationManager(client, getOidcUserService());
ResolvableType type = ResolvableType.forClassWithGenerics(
ReactiveJwtDecoderFactory.class, ClientRegistration.class);
ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = getBeanOrNull(type);
if (jwtDecoderFactory != null) {
oidc.setJwtDecoderFactory(jwtDecoderFactory);
}
result = new DelegatingReactiveAuthenticationManager(oidc, result);
}
return result;
}
/**
* Sets the converter to use
* @param authenticationConverter the converter to use
* @return the {@link OAuth2LoginSpec} to customize
*/
public OAuth2LoginSpec authenticationConverter(ServerAuthenticationConverter authenticationConverter) {
this.authenticationConverter = authenticationConverter;
return this;
}
private ServerAuthenticationConverter getAuthenticationConverter(ReactiveClientRegistrationRepository clientRegistrationRepository) {
if (this.authenticationConverter == null) {
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter authenticationConverter = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(clientRegistrationRepository);
authenticationConverter.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
this.authenticationConverter = authenticationConverter;
}
return this.authenticationConverter;
}
public OAuth2LoginSpec clientRegistrationRepository(ReactiveClientRegistrationRepository clientRegistrationRepository) {
this.clientRegistrationRepository = clientRegistrationRepository;
return this;
}
public OAuth2LoginSpec authorizedClientService(ReactiveOAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientRepository = new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);
return this;
}
public OAuth2LoginSpec authorizedClientRepository(ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
this.authorizedClientRepository = authorizedClientRepository;
return this;
}
/**
* Sets the repository to use for storing {@link OAuth2AuthorizationRequest}'s.
*
* @since 5.2
* @param authorizationRequestRepository the repository to use for storing {@link OAuth2AuthorizationRequest}'s
* @return the {@link OAuth2LoginSpec} for further configuration
*/
public OAuth2LoginSpec authorizationRequestRepository(
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
this.authorizationRequestRepository = authorizationRequestRepository;
return this;
}
/**
* Sets the resolver used for resolving {@link OAuth2AuthorizationRequest}'s.
*
* @since 5.2
* @param authorizationRequestResolver the resolver used for resolving {@link OAuth2AuthorizationRequest}'s
* @return the {@link OAuth2LoginSpec} for further configuration
*/
public OAuth2LoginSpec authorizationRequestResolver(ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver) {
this.authorizationRequestResolver = authorizationRequestResolver;
return this;
}
/**
* Sets the {@link ServerWebExchangeMatcher matcher} used for determining if the request is an authentication request.
*
* @since 5.2
* @param authenticationMatcher the {@link ServerWebExchangeMatcher matcher} used for determining if the request is an authentication request
* @return the {@link OAuth2LoginSpec} for further configuration
*/
public OAuth2LoginSpec authenticationMatcher(ServerWebExchangeMatcher authenticationMatcher) {
this.authenticationMatcher = authenticationMatcher;
return this;
}
private ServerWebExchangeMatcher getAuthenticationMatcher() {
if (this.authenticationMatcher == null) {
this.authenticationMatcher = createAttemptAuthenticationRequestMatcher();
}
return this.authenticationMatcher;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
ReactiveClientRegistrationRepository clientRegistrationRepository = getClientRegistrationRepository();
ServerOAuth2AuthorizedClientRepository authorizedClientRepository = getAuthorizedClientRepository();
OAuth2AuthorizationRequestRedirectWebFilter oauthRedirectFilter = getRedirectWebFilter();
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository =
getAuthorizationRequestRepository();
oauthRedirectFilter.setAuthorizationRequestRepository(authorizationRequestRepository);
oauthRedirectFilter.setRequestCache(http.requestCache.requestCache);
ReactiveAuthenticationManager manager = getAuthenticationManager();
AuthenticationWebFilter authenticationFilter = new OAuth2LoginAuthenticationWebFilter(manager, authorizedClientRepository);
authenticationFilter.setRequiresAuthenticationMatcher(getAuthenticationMatcher());
authenticationFilter.setServerAuthenticationConverter(getAuthenticationConverter(clientRegistrationRepository));
authenticationFilter.setAuthenticationSuccessHandler(this.authenticationSuccessHandler);
authenticationFilter.setAuthenticationFailureHandler(getAuthenticationFailureHandler());
authenticationFilter.setSecurityContextRepository(this.securityContextRepository);
MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(
MediaType.TEXT_HTML);
htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
Map<String, String> urlToText = http.oauth2Login.getLinks();
if (urlToText.size() == 1) {
http.defaultEntryPoints.add(new DelegateEntry(htmlMatcher, new RedirectServerAuthenticationEntryPoint(urlToText.keySet().iterator().next())));
} else {
http.defaultEntryPoints.add(new DelegateEntry(htmlMatcher, new RedirectServerAuthenticationEntryPoint("/login")));
}
http.addFilterAt(oauthRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION);
}
private ServerAuthenticationFailureHandler getAuthenticationFailureHandler() {
if (this.authenticationFailureHandler == null) {
this.authenticationFailureHandler = new RedirectServerAuthenticationFailureHandler("/login?error");
}
return this.authenticationFailureHandler;
}
private ServerWebExchangeMatcher createAttemptAuthenticationRequestMatcher() {
return new PathPatternParserServerWebExchangeMatcher("/login/oauth2/code/{registrationId}");
}
private ReactiveOAuth2UserService<OidcUserRequest, OidcUser> getOidcUserService() {
ResolvableType type = ResolvableType.forClassWithGenerics(ReactiveOAuth2UserService.class, OidcUserRequest.class, OidcUser.class);
ReactiveOAuth2UserService<OidcUserRequest, OidcUser> bean = getBeanOrNull(type);
if (bean == null) {
return new OidcReactiveOAuth2UserService();
}
return bean;
}
private ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> getOauth2UserService() {
ResolvableType type = ResolvableType.forClassWithGenerics(ReactiveOAuth2UserService.class, OAuth2UserRequest.class, OAuth2User.class);
ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> bean = getBeanOrNull(type);
if (bean == null) {
return new DefaultReactiveOAuth2UserService();
}
return bean;
}
private Map<String, String> getLinks() {
Iterable<ClientRegistration> registrations = getBeanOrNull(ResolvableType.forClassWithGenerics(Iterable.class, ClientRegistration.class));
if (registrations == null) {
return Collections.emptyMap();
}
Map<String, String> result = new HashMap<>();
registrations.iterator().forEachRemaining(r -> result.put("/oauth2/authorization/" + r.getRegistrationId(), r.getClientName()));
return result;
}
private ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> getAccessTokenResponseClient() {
ResolvableType type = ResolvableType.forClassWithGenerics(ReactiveOAuth2AccessTokenResponseClient.class, OAuth2AuthorizationCodeGrantRequest.class);
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> bean = getBeanOrNull(type);
if (bean == null) {
return new WebClientReactiveAuthorizationCodeTokenResponseClient();
}
return bean;
}
private ReactiveClientRegistrationRepository getClientRegistrationRepository() {
if (this.clientRegistrationRepository == null) {
this.clientRegistrationRepository = getBeanOrNull(ReactiveClientRegistrationRepository.class);
}
return this.clientRegistrationRepository;
}
private OAuth2AuthorizationRequestRedirectWebFilter getRedirectWebFilter() {
OAuth2AuthorizationRequestRedirectWebFilter oauthRedirectFilter;
if (this.authorizationRequestResolver == null) {
oauthRedirectFilter = new OAuth2AuthorizationRequestRedirectWebFilter(getClientRegistrationRepository());
} else {
oauthRedirectFilter = new OAuth2AuthorizationRequestRedirectWebFilter(this.authorizationRequestResolver);
}
return oauthRedirectFilter;
}
private ServerOAuth2AuthorizedClientRepository getAuthorizedClientRepository() {
ServerOAuth2AuthorizedClientRepository result = this.authorizedClientRepository;
if (result == null) {
result = getBeanOrNull(ServerOAuth2AuthorizedClientRepository.class);
}
if (result == null) {
ReactiveOAuth2AuthorizedClientService authorizedClientService = getAuthorizedClientService();
if (authorizedClientService != null) {
result = new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(
authorizedClientService);
}
}
return result;
}
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> getAuthorizationRequestRepository() {
if (this.authorizationRequestRepository == null) {
this.authorizationRequestRepository = new WebSessionOAuth2ServerAuthorizationRequestRepository();
}
return this.authorizationRequestRepository;
}
private ReactiveOAuth2AuthorizedClientService getAuthorizedClientService() {
ReactiveOAuth2AuthorizedClientService service = getBeanOrNull(ReactiveOAuth2AuthorizedClientService.class);
if (service == null) {
service = new InMemoryReactiveOAuth2AuthorizedClientService(getClientRegistrationRepository());
}
return service;
}
private OAuth2LoginSpec() {}
}
/**
* Configures the OAuth2 client.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .oauth2Client()
* .clientRegistrationRepository(clientRegistrationRepository)
* .authorizedClientRepository(authorizedClientRepository);
* return http.build();
* }
* </pre>
*
*
* @return the {@link OAuth2ClientSpec} to customize
*/
public OAuth2ClientSpec oauth2Client() {
if (this.client == null) {
this.client = new OAuth2ClientSpec();
}
return this.client;
}
/**
* Configures the OAuth2 client.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .oauth2Client(oauth2Client ->
* oauth2Client
* .clientRegistrationRepository(clientRegistrationRepository)
* .authorizedClientRepository(authorizedClientRepository)
* );
* return http.build();
* }
* </pre>
*
* @param oauth2ClientCustomizer the {@link Customizer} to provide more options for
* the {@link OAuth2ClientSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity oauth2Client(Customizer<OAuth2ClientSpec> oauth2ClientCustomizer) {
if (this.client == null) {
this.client = new OAuth2ClientSpec();
}
oauth2ClientCustomizer.customize(this.client);
return this;
}
public class OAuth2ClientSpec {
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private ServerAuthenticationConverter authenticationConverter;
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ReactiveAuthenticationManager authenticationManager;
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
/**
* Sets the converter to use
* @param authenticationConverter the converter to use
* @return the {@link OAuth2ClientSpec} to customize
*/
public OAuth2ClientSpec authenticationConverter(ServerAuthenticationConverter authenticationConverter) {
this.authenticationConverter = authenticationConverter;
return this;
}
private ServerAuthenticationConverter getAuthenticationConverter() {
if (this.authenticationConverter == null) {
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter authenticationConverter =
new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(getClientRegistrationRepository());
authenticationConverter.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
this.authenticationConverter = authenticationConverter;
}
return this.authenticationConverter;
}
/**
* Configures the {@link ReactiveAuthenticationManager} to use. The default is
* {@link OAuth2AuthorizationCodeReactiveAuthenticationManager}
* @param authenticationManager the manager to use
* @return the {@link OAuth2ClientSpec} to customize
*/
public OAuth2ClientSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
/**
* Gets the {@link ReactiveAuthenticationManager} to use. First tries an explicitly configured manager, and
* defaults to {@link OAuth2AuthorizationCodeReactiveAuthenticationManager}
*
* @return the {@link ReactiveAuthenticationManager} to use
*/
private ReactiveAuthenticationManager getAuthenticationManager() {
if (this.authenticationManager == null) {
this.authenticationManager = new OAuth2AuthorizationCodeReactiveAuthenticationManager(new WebClientReactiveAuthorizationCodeTokenResponseClient());
}
return this.authenticationManager;
}
/**
* Configures the {@link ReactiveClientRegistrationRepository}. Default is to look the value up as a Bean.
* @param clientRegistrationRepository the repository to use
* @return the {@link OAuth2ClientSpec} to customize
*/
public OAuth2ClientSpec clientRegistrationRepository(ReactiveClientRegistrationRepository clientRegistrationRepository) {
this.clientRegistrationRepository = clientRegistrationRepository;
return this;
}
/**
* Configures the {@link ReactiveClientRegistrationRepository}. Default is to look the value up as a Bean.
* @param authorizedClientRepository the repository to use
* @return the {@link OAuth2ClientSpec} to customize
*/
public OAuth2ClientSpec authorizedClientRepository(ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
this.authorizedClientRepository = authorizedClientRepository;
return this;
}
/**
* Sets the repository to use for storing {@link OAuth2AuthorizationRequest}'s.
*
* @since 5.2
* @param authorizationRequestRepository the repository to use for storing {@link OAuth2AuthorizationRequest}'s
* @return the {@link OAuth2ClientSpec} to customize
*/
public OAuth2ClientSpec authorizationRequestRepository(
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
this.authorizationRequestRepository = authorizationRequestRepository;
return this;
}
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> getAuthorizationRequestRepository() {
if (this.authorizationRequestRepository == null) {
this.authorizationRequestRepository = new WebSessionOAuth2ServerAuthorizationRequestRepository();
}
return this.authorizationRequestRepository;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
ReactiveClientRegistrationRepository clientRegistrationRepository = getClientRegistrationRepository();
ServerOAuth2AuthorizedClientRepository authorizedClientRepository = getAuthorizedClientRepository();
ServerAuthenticationConverter authenticationConverter = getAuthenticationConverter();
ReactiveAuthenticationManager authenticationManager = getAuthenticationManager();
OAuth2AuthorizationCodeGrantWebFilter codeGrantWebFilter = new OAuth2AuthorizationCodeGrantWebFilter(
authenticationManager, authenticationConverter, authorizedClientRepository);
codeGrantWebFilter.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
OAuth2AuthorizationRequestRedirectWebFilter oauthRedirectFilter = new OAuth2AuthorizationRequestRedirectWebFilter(
clientRegistrationRepository);
oauthRedirectFilter.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
http.addFilterAt(codeGrantWebFilter, SecurityWebFiltersOrder.OAUTH2_AUTHORIZATION_CODE);
http.addFilterAt(oauthRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
}
private ReactiveClientRegistrationRepository getClientRegistrationRepository() {
if (this.clientRegistrationRepository != null) {
return this.clientRegistrationRepository;
}
return getBeanOrNull(ReactiveClientRegistrationRepository.class);
}
private ServerOAuth2AuthorizedClientRepository getAuthorizedClientRepository() {
if (this.authorizedClientRepository != null) {
return this.authorizedClientRepository;
}
ServerOAuth2AuthorizedClientRepository result = getBeanOrNull(ServerOAuth2AuthorizedClientRepository.class);
if (result == null) {
ReactiveOAuth2AuthorizedClientService authorizedClientService = getAuthorizedClientService();
if (authorizedClientService != null) {
result = new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(
authorizedClientService);
}
}
return result;
}
private ReactiveOAuth2AuthorizedClientService getAuthorizedClientService() {
ReactiveOAuth2AuthorizedClientService service = getBeanOrNull(ReactiveOAuth2AuthorizedClientService.class);
if (service == null) {
service = new InMemoryReactiveOAuth2AuthorizedClientService(getClientRegistrationRepository());
}
return service;
}
private OAuth2ClientSpec() {}
}
/**
* Configures OAuth 2.0 Resource Server support.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .oauth2ResourceServer()
* .jwt()
* .publicKey(publicKey());
* return http.build();
* }
* </pre>
*
* @return the {@link OAuth2ResourceServerSpec} to customize
*/
public OAuth2ResourceServerSpec oauth2ResourceServer() {
if (this.resourceServer == null) {
this.resourceServer = new OAuth2ResourceServerSpec();
}
return this.resourceServer;
}
/**
* Configures OAuth 2.0 Resource Server support.
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .oauth2ResourceServer(oauth2ResourceServer ->
* oauth2ResourceServer
* .jwt(jwt ->
* jwt
* .publicKey(publicKey())
* )
* );
* return http.build();
* }
* </pre>
*
* @param oauth2ResourceServerCustomizer the {@link Customizer} to provide more options for
* the {@link OAuth2ResourceServerSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity oauth2ResourceServer(Customizer<OAuth2ResourceServerSpec> oauth2ResourceServerCustomizer) {
if (this.resourceServer == null) {
this.resourceServer = new OAuth2ResourceServerSpec();
}
oauth2ResourceServerCustomizer.customize(this.resourceServer);
return this;
}
/**
* Configures OAuth2 Resource Server Support
*/
public class OAuth2ResourceServerSpec {
private ServerAuthenticationEntryPoint entryPoint = new BearerTokenServerAuthenticationEntryPoint();
private ServerAccessDeniedHandler accessDeniedHandler = new BearerTokenServerAccessDeniedHandler();
private ServerAuthenticationConverter bearerTokenConverter = new ServerBearerTokenAuthenticationConverter();
private BearerTokenServerWebExchangeMatcher bearerTokenServerWebExchangeMatcher =
new BearerTokenServerWebExchangeMatcher();
private JwtSpec jwt;
private OpaqueTokenSpec opaqueToken;
private ReactiveAuthenticationManagerResolver<ServerHttpRequest> authenticationManagerResolver;
/**
* Configures the {@link ServerAccessDeniedHandler} to use for requests authenticating with
* <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer Token</a>s.
* requests.
*
* @param accessDeniedHandler the {@link ServerAccessDeniedHandler} to use
* @return the {@link OAuth2ResourceServerSpec} for additional configuration
* @since 5.2
*/
public OAuth2ResourceServerSpec accessDeniedHandler(ServerAccessDeniedHandler accessDeniedHandler) {
Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
this.accessDeniedHandler = accessDeniedHandler;
return this;
}
/**
* Configures the {@link ServerAuthenticationEntryPoint} to use for requests authenticating with
* <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer Token</a>s.
*
* @param entryPoint the {@link ServerAuthenticationEntryPoint} to use
* @return the {@link OAuth2ResourceServerSpec} for additional configuration
* @since 5.2
*/
public OAuth2ResourceServerSpec authenticationEntryPoint(ServerAuthenticationEntryPoint entryPoint) {
Assert.notNull(entryPoint, "entryPoint cannot be null");
this.entryPoint = entryPoint;
return this;
}
/**
* Configures the {@link ServerAuthenticationConverter} to use for requests authenticating with
* <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer Token</a>s.
*
* @param bearerTokenConverter The {@link ServerAuthenticationConverter} to use
* @return The {@link OAuth2ResourceServerSpec} for additional configuration
* @since 5.2
*/
public OAuth2ResourceServerSpec bearerTokenConverter(ServerAuthenticationConverter bearerTokenConverter) {
Assert.notNull(bearerTokenConverter, "bearerTokenConverter cannot be null");
this.bearerTokenConverter = bearerTokenConverter;
return this;
}
/**
* Configures the {@link ReactiveAuthenticationManagerResolver}
*
* @param authenticationManagerResolver the {@link ReactiveAuthenticationManagerResolver}
* @return the {@link OAuth2ResourceServerSpec} for additional configuration
* @since 5.2
*/
public OAuth2ResourceServerSpec authenticationManagerResolver(
ReactiveAuthenticationManagerResolver<ServerHttpRequest> authenticationManagerResolver) {
Assert.notNull(authenticationManagerResolver, "authenticationManagerResolver cannot be null");
this.authenticationManagerResolver = authenticationManagerResolver;
return this;
}
/**
* Enables JWT Resource Server support.
*
* @return the {@link JwtSpec} for additional configuration
*/
public JwtSpec jwt() {
if (this.jwt == null) {
this.jwt = new JwtSpec();
}
return this.jwt;
}
/**
* Enables JWT Resource Server support.
*
* @param jwtCustomizer the {@link Customizer} to provide more options for
* the {@link JwtSpec}
* @return the {@link OAuth2ResourceServerSpec} to customize
*/
public OAuth2ResourceServerSpec jwt(Customizer<JwtSpec> jwtCustomizer) {
if (this.jwt == null) {
this.jwt = new JwtSpec();
}
jwtCustomizer.customize(this.jwt);
return this;
}
/**
* Enables Opaque Token Resource Server support.
*
* @return the {@link OpaqueTokenSpec} for additional configuration
*/
public OpaqueTokenSpec opaqueToken() {
if (this.opaqueToken == null) {
this.opaqueToken = new OpaqueTokenSpec();
}
return this.opaqueToken;
}
/**
* Enables Opaque Token Resource Server support.
*
* @param opaqueTokenCustomizer the {@link Customizer} to provide more options for
* the {@link OpaqueTokenSpec}
* @return the {@link OAuth2ResourceServerSpec} to customize
*/
public OAuth2ResourceServerSpec opaqueToken(Customizer<OpaqueTokenSpec> opaqueTokenCustomizer) {
if (this.opaqueToken == null) {
this.opaqueToken = new OpaqueTokenSpec();
}
opaqueTokenCustomizer.customize(this.opaqueToken);
return this;
}
protected void configure(ServerHttpSecurity http) {
this.bearerTokenServerWebExchangeMatcher
.setBearerTokenConverter(this.bearerTokenConverter);
registerDefaultAccessDeniedHandler(http);
registerDefaultAuthenticationEntryPoint(http);
registerDefaultCsrfOverride(http);
validateConfiguration();
if (this.authenticationManagerResolver != null) {
AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(this.authenticationManagerResolver);
oauth2.setServerAuthenticationConverter(bearerTokenConverter);
oauth2.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint));
http.addFilterAt(oauth2, SecurityWebFiltersOrder.AUTHENTICATION);
} else if (this.jwt != null) {
this.jwt.configure(http);
} else if (this.opaqueToken != null) {
this.opaqueToken.configure(http);
}
}
private void validateConfiguration() {
if (this.authenticationManagerResolver == null) {
if (this.jwt == null && this.opaqueToken == null) {
throw new IllegalStateException("Jwt and Opaque Token are the only supported formats for bearer tokens " +
"in Spring Security and neither was found. Make sure to configure JWT " +
"via http.oauth2ResourceServer().jwt() or Opaque Tokens via " +
"http.oauth2ResourceServer().opaqueToken().");
}
if (this.jwt != null && this.opaqueToken != null) {
throw new IllegalStateException("Spring Security only supports JWTs or Opaque Tokens, not both at the " +
"same time.");
}
} else {
if (this.jwt != null || this.opaqueToken != null) {
throw new IllegalStateException("If an authenticationManagerResolver() is configured, then it takes " +
"precedence over any jwt() or opaqueToken() configuration.");
}
}
}
private void registerDefaultAccessDeniedHandler(ServerHttpSecurity http) {
if ( http.exceptionHandling != null ) {
http.defaultAccessDeniedHandlers.add(
new ServerWebExchangeDelegatingServerAccessDeniedHandler.DelegateEntry(
this.bearerTokenServerWebExchangeMatcher,
OAuth2ResourceServerSpec.this.accessDeniedHandler
)
);
}
}
private void registerDefaultAuthenticationEntryPoint(ServerHttpSecurity http) {
if (http.exceptionHandling != null) {
http.defaultEntryPoints.add(
new DelegateEntry(
this.bearerTokenServerWebExchangeMatcher,
OAuth2ResourceServerSpec.this.entryPoint
)
);
}
}
private void registerDefaultCsrfOverride(ServerHttpSecurity http) {
if ( http.csrf != null && !http.csrf.specifiedRequireCsrfProtectionMatcher ) {
http
.csrf()
.requireCsrfProtectionMatcher(
new AndServerWebExchangeMatcher(
CsrfWebFilter.DEFAULT_CSRF_MATCHER,
new NegatedServerWebExchangeMatcher(
this.bearerTokenServerWebExchangeMatcher)));
}
}
private class BearerTokenServerWebExchangeMatcher implements ServerWebExchangeMatcher {
ServerAuthenticationConverter bearerTokenConverter;
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return this.bearerTokenConverter.convert(exchange)
.flatMap(this::nullAuthentication)
.onErrorResume(e -> notMatch());
}
public void setBearerTokenConverter(ServerAuthenticationConverter bearerTokenConverter) {
Assert.notNull(bearerTokenConverter, "bearerTokenConverter cannot be null");
this.bearerTokenConverter = bearerTokenConverter;
}
private Mono<MatchResult> nullAuthentication(Authentication authentication) {
return authentication == null ? notMatch() : match();
}
}
/**
* Configures JWT Resource Server Support
*/
public class JwtSpec {
private ReactiveAuthenticationManager authenticationManager;
private ReactiveJwtDecoder jwtDecoder;
private Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter
= new ReactiveJwtAuthenticationConverterAdapter(new JwtAuthenticationConverter());
/**
* Configures the {@link ReactiveAuthenticationManager} to use
* @param authenticationManager the authentication manager to use
* @return the {@code JwtSpec} for additional configuration
*/
public JwtSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
this.authenticationManager = authenticationManager;
return this;
}
/**
* Configures the {@link Converter} to use for converting a {@link Jwt} into
* an {@link AbstractAuthenticationToken}.
*
* @param jwtAuthenticationConverter the converter to use
* @return the {@code JwtSpec} for additional configuration
* @since 5.1.1
*/
public JwtSpec jwtAuthenticationConverter
(Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter) {
Assert.notNull(jwtAuthenticationConverter, "jwtAuthenticationConverter cannot be null");
this.jwtAuthenticationConverter = jwtAuthenticationConverter;
return this;
}
/**
* Configures the {@link ReactiveJwtDecoder} to use
* @param jwtDecoder the decoder to use
* @return the {@code JwtSpec} for additional configuration
*/
public JwtSpec jwtDecoder(ReactiveJwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
return this;
}
/**
* Configures a {@link ReactiveJwtDecoder} that leverages the provided {@link RSAPublicKey}
*
* @param publicKey the public key to use.
* @return the {@code JwtSpec} for additional configuration
*/
public JwtSpec publicKey(RSAPublicKey publicKey) {
this.jwtDecoder = new NimbusReactiveJwtDecoder(publicKey);
return this;
}
/**
* Configures a {@link ReactiveJwtDecoder} using
* <a target="_blank" href="https://tools.ietf.org/html/rfc7517">JSON Web Key (JWK)</a> URL
* @param jwkSetUri the URL to use.
* @return the {@code JwtSpec} for additional configuration
*/
public JwtSpec jwkSetUri(String jwkSetUri) {
this.jwtDecoder = new NimbusReactiveJwtDecoder(jwkSetUri);
return this;
}
public OAuth2ResourceServerSpec and() {
return OAuth2ResourceServerSpec.this;
}
protected void configure(ServerHttpSecurity http) {
ReactiveAuthenticationManager authenticationManager = getAuthenticationManager();
AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(authenticationManager);
oauth2.setServerAuthenticationConverter(bearerTokenConverter);
oauth2.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint));
http
.addFilterAt(oauth2, SecurityWebFiltersOrder.AUTHENTICATION);
}
protected ReactiveJwtDecoder getJwtDecoder() {
if (this.jwtDecoder == null) {
return getBean(ReactiveJwtDecoder.class);
}
return this.jwtDecoder;
}
protected Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>>
getJwtAuthenticationConverter() {
return this.jwtAuthenticationConverter;
}
private ReactiveAuthenticationManager getAuthenticationManager() {
if (this.authenticationManager != null) {
return this.authenticationManager;
}
ReactiveJwtDecoder jwtDecoder = getJwtDecoder();
Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter =
getJwtAuthenticationConverter();
JwtReactiveAuthenticationManager authenticationManager =
new JwtReactiveAuthenticationManager(jwtDecoder);
authenticationManager.setJwtAuthenticationConverter(jwtAuthenticationConverter);
return authenticationManager;
}
}
/**
* Configures Opaque Token Resource Server support
*
* @author Josh Cummings
* @since 5.2
*/
public class OpaqueTokenSpec {
private String introspectionUri;
private String clientId;
private String clientSecret;
private Supplier<ReactiveOpaqueTokenIntrospector> introspector;
/**
* Configures the URI of the Introspection endpoint
* @param introspectionUri The URI of the Introspection endpoint
* @return the {@code OpaqueTokenSpec} for additional configuration
*/
public OpaqueTokenSpec introspectionUri(String introspectionUri) {
Assert.hasText(introspectionUri, "introspectionUri cannot be empty");
this.introspectionUri = introspectionUri;
this.introspector = () ->
new NimbusReactiveOpaqueTokenIntrospector(
this.introspectionUri, this.clientId, this.clientSecret);
return this;
}
/**
* Configures the credentials for Introspection endpoint
* @param clientId The clientId part of the credentials
* @param clientSecret The clientSecret part of the credentials
* @return the {@code OpaqueTokenSpec} for additional configuration
*/
public OpaqueTokenSpec introspectionClientCredentials(String clientId, String clientSecret) {
Assert.hasText(clientId, "clientId cannot be empty");
Assert.notNull(clientSecret, "clientSecret cannot be null");
this.clientId = clientId;
this.clientSecret = clientSecret;
this.introspector = () ->
new NimbusReactiveOpaqueTokenIntrospector(
this.introspectionUri, this.clientId, this.clientSecret);
return this;
}
public OpaqueTokenSpec introspector(ReactiveOpaqueTokenIntrospector introspector) {
Assert.notNull(introspector, "introspector cannot be null");
this.introspector = () -> introspector;
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public OAuth2ResourceServerSpec and() {
return OAuth2ResourceServerSpec.this;
}
protected ReactiveAuthenticationManager getAuthenticationManager() {
return new OpaqueTokenReactiveAuthenticationManager(getIntrospector());
}
protected ReactiveOpaqueTokenIntrospector getIntrospector() {
if (this.introspector != null) {
return this.introspector.get();
}
return getBean(ReactiveOpaqueTokenIntrospector.class);
}
protected void configure(ServerHttpSecurity http) {
ReactiveAuthenticationManager authenticationManager = getAuthenticationManager();
AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(authenticationManager);
oauth2.setServerAuthenticationConverter(bearerTokenConverter);
oauth2.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint));
http.addFilterAt(oauth2, SecurityWebFiltersOrder.AUTHENTICATION);
}
private OpaqueTokenSpec() {}
}
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
}
/**
* Configures HTTP Response Headers. The default headers are:
*
* <pre>
* Cache-Control: no-cache, no-store, max-age=0, must-revalidate
* Pragma: no-cache
* Expires: 0
* X-Content-Type-Options: nosniff
* Strict-Transport-Security: max-age=31536000 ; includeSubDomains
* X-Frame-Options: DENY
* X-XSS-Protection: 1; mode=block
* </pre>
*
* such that "Strict-Transport-Security" is only added on secure requests.
*
* An example configuration is provided below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .headers()
* // customize frame options to be same origin
* .frameOptions()
* .mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)
* .and()
* // disable cache control
* .cache().disable();
* return http.build();
* }
* </pre>
*
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec headers() {
if (this.headers == null) {
this.headers = new HeaderSpec();
}
return this.headers;
}
/**
* Configures HTTP Response Headers. The default headers are:
*
* <pre>
* Cache-Control: no-cache, no-store, max-age=0, must-revalidate
* Pragma: no-cache
* Expires: 0
* X-Content-Type-Options: nosniff
* Strict-Transport-Security: max-age=31536000 ; includeSubDomains
* X-Frame-Options: DENY
* X-XSS-Protection: 1; mode=block
* </pre>
*
* such that "Strict-Transport-Security" is only added on secure requests.
*
* An example configuration is provided below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .headers(headers ->
* headers
* // customize frame options to be same origin
* .frameOptions(frameOptions ->
* frameOptions
* .mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)
* )
* // disable cache control
* .cache(cache ->
* cache
* .disable()
* )
* );
* return http.build();
* }
* </pre>
*
* @param headerCustomizer the {@link Customizer} to provide more options for
* the {@link HeaderSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity headers(Customizer<HeaderSpec> headerCustomizer) {
if (this.headers == null) {
this.headers = new HeaderSpec();
}
headerCustomizer.customize(this.headers);
return this;
}
/**
* Configures exception handling (i.e. handles when authentication is requested). An example configuration can
* be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .exceptionHandling()
* // customize how to request for authentication
* .authenticationEntryPoint(entryPoint);
* return http.build();
* }
* </pre>
*
* @return the {@link ExceptionHandlingSpec} to customize
*/
public ExceptionHandlingSpec exceptionHandling() {
if (this.exceptionHandling == null) {
this.exceptionHandling = new ExceptionHandlingSpec();
}
return this.exceptionHandling;
}
/**
* Configures exception handling (i.e. handles when authentication is requested). An example configuration can
* be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .exceptionHandling(exceptionHandling ->
* exceptionHandling
* // customize how to request for authentication
* .authenticationEntryPoint(entryPoint)
* );
* return http.build();
* }
* </pre>
*
* @param exceptionHandlingCustomizer the {@link Customizer} to provide more options for
* the {@link ExceptionHandlingSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity exceptionHandling(Customizer<ExceptionHandlingSpec> exceptionHandlingCustomizer) {
if (this.exceptionHandling == null) {
this.exceptionHandling = new ExceptionHandlingSpec();
}
exceptionHandlingCustomizer.customize(this.exceptionHandling);
return this;
}
/**
* Configures authorization. An example configuration can be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .authorizeExchange()
* // any URL that starts with /admin/ requires the role "ROLE_ADMIN"
* .pathMatchers("/admin/**").hasRole("ADMIN")
* // a POST to /users requires the role "USER_POST"
* .pathMatchers(HttpMethod.POST, "/users").hasAuthority("USER_POST")
* // a request to /users/{username} requires the current authentication's username
* // to be equal to the {username}
* .pathMatchers("/users/{username}").access((authentication, context) ->
* authentication
* .map(Authentication::getName)
* .map(username -> username.equals(context.getVariables().get("username")))
* .map(AuthorizationDecision::new)
* )
* // allows providing a custom matching strategy that requires the role "ROLE_CUSTOM"
* .matchers(customMatcher).hasRole("CUSTOM")
* // any other request requires the user to be authenticated
* .anyExchange().authenticated();
* return http.build();
* }
* </pre>
*
* @return the {@link AuthorizeExchangeSpec} to customize
*/
public AuthorizeExchangeSpec authorizeExchange() {
if (this.authorizeExchange == null) {
this.authorizeExchange = new AuthorizeExchangeSpec();
}
return this.authorizeExchange;
}
/**
* Configures authorization. An example configuration can be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .authorizeExchange(exchanges ->
* exchanges
* // any URL that starts with /admin/ requires the role "ROLE_ADMIN"
* .pathMatchers("/admin/**").hasRole("ADMIN")
* // a POST to /users requires the role "USER_POST"
* .pathMatchers(HttpMethod.POST, "/users").hasAuthority("USER_POST")
* // a request to /users/{username} requires the current authentication's username
* // to be equal to the {username}
* .pathMatchers("/users/{username}").access((authentication, context) ->
* authentication
* .map(Authentication::getName)
* .map(username -> username.equals(context.getVariables().get("username")))
* .map(AuthorizationDecision::new)
* )
* // allows providing a custom matching strategy that requires the role "ROLE_CUSTOM"
* .matchers(customMatcher).hasRole("CUSTOM")
* // any other request requires the user to be authenticated
* .anyExchange().authenticated()
* );
* return http.build();
* }
* </pre>
*
* @param authorizeExchangeCustomizer the {@link Customizer} to provide more options for
* the {@link AuthorizeExchangeSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity authorizeExchange(Customizer<AuthorizeExchangeSpec> authorizeExchangeCustomizer) {
if (this.authorizeExchange == null) {
this.authorizeExchange = new AuthorizeExchangeSpec();
}
authorizeExchangeCustomizer.customize(this.authorizeExchange);
return this;
}
/**
* Configures log out. An example configuration can be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .logout()
* // configures how log out is done
* .logoutHandler(logoutHandler)
* // log out will be performed on POST /signout
* .logoutUrl("/signout")
* // configure what is done on logout success
* .logoutSuccessHandler(successHandler);
* return http.build();
* }
* </pre>
* @return the {@link LogoutSpec} to customize
*/
public LogoutSpec logout() {
if (this.logout == null) {
this.logout = new LogoutSpec();
}
return this.logout;
}
/**
* Configures log out. An example configuration can be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .logout(logout ->
* logout
* // configures how log out is done
* .logoutHandler(logoutHandler)
* // log out will be performed on POST /signout
* .logoutUrl("/signout")
* // configure what is done on logout success
* .logoutSuccessHandler(successHandler)
* );
* return http.build();
* }
* </pre>
*
* @param logoutCustomizer the {@link Customizer} to provide more options for
* the {@link LogoutSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity logout(Customizer<LogoutSpec> logoutCustomizer) {
if (this.logout == null) {
this.logout = new LogoutSpec();
}
logoutCustomizer.customize(this.logout);
return this;
}
/**
* Configures the request cache which is used when a flow is interrupted (i.e. due to requesting credentials) so
* that the request can be replayed after authentication. An example configuration can be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .requestCache()
* // configures how the request is cached
* .requestCache(requestCache);
* return http.build();
* }
* </pre>
*
* @return the {@link RequestCacheSpec} to customize
*/
public RequestCacheSpec requestCache() {
return this.requestCache;
}
/**
* Configures the request cache which is used when a flow is interrupted (i.e. due to requesting credentials) so
* that the request can be replayed after authentication. An example configuration can be found below:
*
* <pre class="code">
* @Bean
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
* http
* // ...
* .requestCache(requestCache ->
* requestCache
* // configures how the request is cached
* .requestCache(customRequestCache)
* );
* return http.build();
* }
* </pre>
*
* @param requestCacheCustomizer the {@link Customizer} to provide more options for
* the {@link RequestCacheSpec}
* @return the {@link ServerHttpSecurity} to customize
*/
public ServerHttpSecurity requestCache(Customizer<RequestCacheSpec> requestCacheCustomizer) {
requestCacheCustomizer.customize(this.requestCache);
return this;
}
/**
* Configure the default authentication manager.
* @param manager the authentication manager to use
* @return the {@code ServerHttpSecurity} to customize
*/
public ServerHttpSecurity authenticationManager(ReactiveAuthenticationManager manager) {
this.authenticationManager = manager;
return this;
}
/**
* Builds the {@link SecurityWebFilterChain}
* @return the {@link SecurityWebFilterChain}
*/
public SecurityWebFilterChain build() {
if (this.built != null) {
throw new IllegalStateException("This has already been built with the following stacktrace. " + buildToString());
}
this.built = new RuntimeException("First Build Invocation").fillInStackTrace();
if (this.headers != null) {
this.headers.configure(this);
}
WebFilter securityContextRepositoryWebFilter = securityContextRepositoryWebFilter();
this.webFilters.add(securityContextRepositoryWebFilter);
if (this.httpsRedirectSpec != null) {
this.httpsRedirectSpec.configure(this);
}
if (this.x509 != null) {
this.x509.configure(this);
}
if (this.csrf != null) {
this.csrf.configure(this);
}
if (this.cors != null) {
this.cors.configure(this);
}
if (this.httpBasic != null) {
if (this.httpBasic.authenticationManager == null) {
this.httpBasic.authenticationManager(this.authenticationManager);
}
if (this.httpBasic.securityContextRepository != null) {
this.httpBasic.securityContextRepository(this.httpBasic.securityContextRepository);
}
else if (this.securityContextRepository != null) {
this.httpBasic.securityContextRepository(this.securityContextRepository);
}
else {
this.httpBasic.securityContextRepository(NoOpServerSecurityContextRepository.getInstance());
}
this.httpBasic.configure(this);
}
if (this.formLogin != null) {
if (this.formLogin.authenticationManager == null) {
this.formLogin.authenticationManager(this.authenticationManager);
}
if (this.formLogin.securityContextRepository != null) {
this.formLogin.securityContextRepository(this.formLogin.securityContextRepository);
}
else if (this.securityContextRepository != null) {
this.formLogin.securityContextRepository(this.securityContextRepository);
}
else {
this.formLogin.securityContextRepository(new WebSessionServerSecurityContextRepository());
}
this.formLogin.configure(this);
}
if (this.oauth2Login != null) {
if (this.oauth2Login.securityContextRepository != null) {
this.oauth2Login.securityContextRepository(this.oauth2Login.securityContextRepository);
}
else if (this.securityContextRepository != null) {
this.oauth2Login.securityContextRepository(this.securityContextRepository);
}
else {
this.oauth2Login.securityContextRepository(new WebSessionServerSecurityContextRepository());
}
this.oauth2Login.configure(this);
}
if (this.resourceServer != null) {
this.resourceServer.configure(this);
}
if (this.client != null) {
this.client.configure(this);
}
if (this.anonymous != null) {
this.anonymous.configure(this);
}
this.loginPage.configure(this);
if (this.logout != null) {
this.logout.configure(this);
}
this.requestCache.configure(this);
this.addFilterAt(new SecurityContextServerWebExchangeWebFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
if (this.authorizeExchange != null) {
ServerAuthenticationEntryPoint authenticationEntryPoint = getAuthenticationEntryPoint();
ExceptionTranslationWebFilter exceptionTranslationWebFilter = new ExceptionTranslationWebFilter();
if (authenticationEntryPoint != null) {
exceptionTranslationWebFilter.setAuthenticationEntryPoint(
authenticationEntryPoint);
}
ServerAccessDeniedHandler accessDeniedHandler = getAccessDeniedHandler();
if (accessDeniedHandler != null) {
exceptionTranslationWebFilter.setAccessDeniedHandler(
accessDeniedHandler);
}
this.addFilterAt(exceptionTranslationWebFilter, SecurityWebFiltersOrder.EXCEPTION_TRANSLATION);
this.authorizeExchange.configure(this);
}
AnnotationAwareOrderComparator.sort(this.webFilters);
List<WebFilter> sortedWebFilters = new ArrayList<>();
this.webFilters.forEach( f -> {
if (f instanceof OrderedWebFilter) {
f = ((OrderedWebFilter) f).webFilter;
}
sortedWebFilters.add(f);
});
sortedWebFilters.add(0, new ServerWebExchangeReactorContextWebFilter());
return new MatcherSecurityWebFilterChain(getSecurityMatcher(), sortedWebFilters);
}
private String buildToString() {
try(StringWriter writer = new StringWriter()) {
try(PrintWriter printer = new PrintWriter(writer)) {
printer.println();
printer.println();
this.built.printStackTrace(printer);
printer.println();
printer.println();
return writer.toString();
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private ServerAuthenticationEntryPoint getAuthenticationEntryPoint() {
if (this.authenticationEntryPoint != null || this.defaultEntryPoints.isEmpty()) {
return this.authenticationEntryPoint;
}
if (this.defaultEntryPoints.size() == 1) {
return this.defaultEntryPoints.get(0).getEntryPoint();
}
DelegatingServerAuthenticationEntryPoint result = new DelegatingServerAuthenticationEntryPoint(this.defaultEntryPoints);
result.setDefaultEntryPoint(this.defaultEntryPoints.get(this.defaultEntryPoints.size() - 1).getEntryPoint());
return result;
}
private ServerAccessDeniedHandler getAccessDeniedHandler() {
if (this.accessDeniedHandler != null || this.defaultAccessDeniedHandlers.isEmpty()) {
return this.accessDeniedHandler;
}
if (this.defaultAccessDeniedHandlers.size() == 1) {
return this.defaultAccessDeniedHandlers.get(0).getAccessDeniedHandler();
}
ServerWebExchangeDelegatingServerAccessDeniedHandler result =
new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.defaultAccessDeniedHandlers);
result.setDefaultAccessDeniedHandler(this.defaultAccessDeniedHandlers
.get(this.defaultAccessDeniedHandlers.size() - 1).getAccessDeniedHandler());
return result;
}
/**
* Creates a new instance.
* @return the new {@link ServerHttpSecurity} instance
*/
public static ServerHttpSecurity http() {
return new ServerHttpSecurity();
}
private WebFilter securityContextRepositoryWebFilter() {
ServerSecurityContextRepository repository = this.securityContextRepository == null ?
new WebSessionServerSecurityContextRepository() : this.securityContextRepository;
WebFilter result = new ReactorContextWebFilter(repository);
return new OrderedWebFilter(result, SecurityWebFiltersOrder.REACTOR_CONTEXT.getOrder());
}
protected ServerHttpSecurity() {}
/**
* Configures authorization
*
* @author Rob Winch
* @since 5.0
* @see #authorizeExchange()
*/
public class AuthorizeExchangeSpec
extends AbstractServerWebExchangeMatcherRegistry<AuthorizeExchangeSpec.Access> {
private DelegatingReactiveAuthorizationManager.Builder managerBldr = DelegatingReactiveAuthorizationManager.builder();
private ServerWebExchangeMatcher matcher;
private boolean anyExchangeRegistered;
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables authorization.
* @return the {@link Access} to continue configuring
*/
@Override
public Access anyExchange() {
Access result = super.anyExchange();
this.anyExchangeRegistered = true;
return result;
}
@Override
protected Access registerMatcher(ServerWebExchangeMatcher matcher) {
if (this.anyExchangeRegistered) {
throw new IllegalStateException("Cannot register " + matcher + " which would be unreachable because anyExchange() has already been registered.");
}
if (this.matcher != null) {
throw new IllegalStateException("The matcher " + matcher + " does not have an access rule defined");
}
this.matcher = matcher;
return new Access();
}
protected void configure(ServerHttpSecurity http) {
if (this.matcher != null) {
throw new IllegalStateException("The matcher " + this.matcher + " does not have an access rule defined");
}
AuthorizationWebFilter result = new AuthorizationWebFilter(this.managerBldr.build());
http.addFilterAt(result, SecurityWebFiltersOrder.AUTHORIZATION);
}
/**
* Configures the access for a particular set of exchanges.
*/
public final class Access {
/**
* Allow access for anyone
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec permitAll() {
return access( (a, e) -> Mono.just(new AuthorizationDecision(true)));
}
/**
* Deny access for everyone
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec denyAll() {
return access( (a, e) -> Mono.just(new AuthorizationDecision(false)));
}
/**
* Require a specific role. This is a shorcut for {@link #hasAuthority(String)}
* @param role the role (i.e. "USER" would require "ROLE_USER")
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec hasRole(String role) {
return access(AuthorityReactiveAuthorizationManager.hasRole(role));
}
/**
* Require any specific role. This is a shortcut for {@link #hasAnyAuthority(String...)}
* @param roles the roles (i.e. "USER" would require "ROLE_USER")
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec hasAnyRole(String... roles) {
return access(AuthorityReactiveAuthorizationManager.hasAnyRole(roles));
}
/**
* Require a specific authority.
* @param authority the authority to require (i.e. "USER" woudl require authority of "USER").
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec hasAuthority(String authority) {
return access(AuthorityReactiveAuthorizationManager.hasAuthority(authority));
}
/**
* Require any authority
* @param authorities the authorities to require (i.e. "USER" would require authority of "USER").
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec hasAnyAuthority(String... authorities) {
return access(AuthorityReactiveAuthorizationManager.hasAnyAuthority(authorities));
}
/**
* Require an authenticated user
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec authenticated() {
return access(AuthenticatedReactiveAuthorizationManager.authenticated());
}
/**
* Allows plugging in a custom authorization strategy
* @param manager the authorization manager to use
* @return the {@link AuthorizeExchangeSpec} to configure
*/
public AuthorizeExchangeSpec access(ReactiveAuthorizationManager<AuthorizationContext> manager) {
AuthorizeExchangeSpec.this.managerBldr
.add(new ServerWebExchangeMatcherEntry<>(
AuthorizeExchangeSpec.this.matcher, manager));
AuthorizeExchangeSpec.this.matcher = null;
return AuthorizeExchangeSpec.this;
}
}
}
/**
* Configures HTTPS redirection rules
*
* @author Josh Cummings
* @since 5.1
* @see #redirectToHttps()
*/
public class HttpsRedirectSpec {
private ServerWebExchangeMatcher serverWebExchangeMatcher;
private PortMapper portMapper;
/**
* Configures when this filter should redirect to https
*
* By default, the filter will redirect whenever an exchange's scheme is not https
*
* @param matchers the list of conditions that, when any are met, the filter should redirect to https
* @return the {@link HttpsRedirectSpec} for additional configuration
*/
public HttpsRedirectSpec httpsRedirectWhen(ServerWebExchangeMatcher... matchers) {
this.serverWebExchangeMatcher = new OrServerWebExchangeMatcher(matchers);
return this;
}
/**
* Configures when this filter should redirect to https
*
* By default, the filter will redirect whenever an exchange's scheme is not https
*
* @param when determines when to redirect to https
* @return the {@link HttpsRedirectSpec} for additional configuration
*/
public HttpsRedirectSpec httpsRedirectWhen(
Function<ServerWebExchange, Boolean> when) {
ServerWebExchangeMatcher matcher = e -> when.apply(e) ?
ServerWebExchangeMatcher.MatchResult.match() :
ServerWebExchangeMatcher.MatchResult.notMatch();
return httpsRedirectWhen(matcher);
}
/**
* Configures a custom HTTPS port to redirect to
*
* @param portMapper the {@link PortMapper} to use
* @return the {@link HttpsRedirectSpec} for additional configuration
*/
public HttpsRedirectSpec portMapper(PortMapper portMapper) {
this.portMapper = portMapper;
return this;
}
protected void configure(ServerHttpSecurity http) {
HttpsRedirectWebFilter httpsRedirectWebFilter = new HttpsRedirectWebFilter();
if (this.serverWebExchangeMatcher != null) {
httpsRedirectWebFilter.setRequiresHttpsRedirectMatcher(this.serverWebExchangeMatcher);
}
if (this.portMapper != null) {
httpsRedirectWebFilter.setPortMapper(this.portMapper);
}
http.addFilterAt(httpsRedirectWebFilter, SecurityWebFiltersOrder.HTTPS_REDIRECT);
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
}
/**
* Configures <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet">CSRF Protection</a>
*
* @author Rob Winch
* @since 5.0
* @see #csrf()
*/
public class CsrfSpec {
private CsrfWebFilter filter = new CsrfWebFilter();
private ServerCsrfTokenRepository csrfTokenRepository = new WebSessionServerCsrfTokenRepository();
private boolean specifiedRequireCsrfProtectionMatcher;
/**
* Configures the {@link ServerAccessDeniedHandler} used when a CSRF token is invalid. Default is
* to send an {@link org.springframework.http.HttpStatus#FORBIDDEN}.
*
* @param accessDeniedHandler the access denied handler.
* @return the {@link CsrfSpec} for additional configuration
*/
public CsrfSpec accessDeniedHandler(
ServerAccessDeniedHandler accessDeniedHandler) {
this.filter.setAccessDeniedHandler(accessDeniedHandler);
return this;
}
/**
* Configures the {@link ServerCsrfTokenRepository} used to persist the CSRF Token. Default is
* {@link org.springframework.security.web.server.csrf.WebSessionServerCsrfTokenRepository}.
*
* @param csrfTokenRepository the repository to use
* @return the {@link CsrfSpec} for additional configuration
*/
public CsrfSpec csrfTokenRepository(
ServerCsrfTokenRepository csrfTokenRepository) {
this.csrfTokenRepository = csrfTokenRepository;
return this;
}
/**
* Configures the {@link ServerWebExchangeMatcher} used to determine when CSRF protection is enabled. Default is
* PUT, POST, DELETE requests.
*
* @param requireCsrfProtectionMatcher the matcher to use
* @return the {@link CsrfSpec} for additional configuration
*/
public CsrfSpec requireCsrfProtectionMatcher(
ServerWebExchangeMatcher requireCsrfProtectionMatcher) {
this.filter.setRequireCsrfProtectionMatcher(requireCsrfProtectionMatcher);
this.specifiedRequireCsrfProtectionMatcher = true;
return this;
}
/**
* Specifies if {@link CsrfWebFilter} should try to resolve the actual CSRF token from the body of multipart
* data requests.
*
* @param enabled true if should read from multipart form body, else false. Default is false
* @return the {@link CsrfSpec} for additional configuration
*/
public CsrfSpec tokenFromMultipartDataEnabled(boolean enabled) {
this.filter.setTokenFromMultipartDataEnabled(enabled);
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables CSRF Protection. Disabling CSRF Protection is only recommended when the application is never used
* within a browser.
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.csrf = null;
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
if (this.csrfTokenRepository != null) {
this.filter.setCsrfTokenRepository(this.csrfTokenRepository);
if (ServerHttpSecurity.this.logout != null) {
ServerHttpSecurity.this.logout.addLogoutHandler(new CsrfServerLogoutHandler(this.csrfTokenRepository));
}
}
http.addFilterAt(this.filter, SecurityWebFiltersOrder.CSRF);
}
private CsrfSpec() {}
}
/**
* Configures exception handling
*
* @author Rob Winch
* @since 5.0
* @see #exceptionHandling()
*/
public class ExceptionHandlingSpec {
/**
* Configures what to do when the application request authentication
* @param authenticationEntryPoint the entry point to use
* @return the {@link ExceptionHandlingSpec} to configure
*/
public ExceptionHandlingSpec authenticationEntryPoint(ServerAuthenticationEntryPoint authenticationEntryPoint) {
ServerHttpSecurity.this.authenticationEntryPoint = authenticationEntryPoint;
return this;
}
/**
* Configures what to do when an authenticated user does not hold a required authority
* @param accessDeniedHandler the access denied handler to use
* @return the {@link ExceptionHandlingSpec} to configure
*
* @since 5.0.5
*/
public ExceptionHandlingSpec accessDeniedHandler(ServerAccessDeniedHandler accessDeniedHandler) {
ServerHttpSecurity.this.accessDeniedHandler = accessDeniedHandler;
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
private ExceptionHandlingSpec() {}
}
/**
* Configures the request cache which is used when a flow is interrupted (i.e. due to requesting credentials) so
* that the request can be replayed after authentication.
*
* @author Rob Winch
* @since 5.0
* @see #requestCache()
*/
public class RequestCacheSpec {
private ServerRequestCache requestCache = new WebSessionServerRequestCache();
/**
* Configures the cache used
* @param requestCache the request cache
* @return the {@link RequestCacheSpec} to configure
*/
public RequestCacheSpec requestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
return this;
}
protected void configure(ServerHttpSecurity http) {
ServerRequestCacheWebFilter filter = new ServerRequestCacheWebFilter();
filter.setRequestCache(this.requestCache);
http.addFilterAt(filter, SecurityWebFiltersOrder.SERVER_REQUEST_CACHE);
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables the {@link RequestCacheSpec}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
this.requestCache = NoOpServerRequestCache.getInstance();
return and();
}
private RequestCacheSpec() {}
}
/**
* Configures HTTP Basic Authentication
*
* @author Rob Winch
* @since 5.0
* @see #httpBasic()
*/
public class HttpBasicSpec {
private ReactiveAuthenticationManager authenticationManager;
private ServerSecurityContextRepository securityContextRepository;
private ServerAuthenticationEntryPoint entryPoint = new HttpBasicServerAuthenticationEntryPoint();
/**
* The {@link ReactiveAuthenticationManager} used to authenticate. Defaults to
* {@link ServerHttpSecurity#authenticationManager(ReactiveAuthenticationManager)}.
*
* @param authenticationManager the authentication manager to use
* @return the {@link HttpBasicSpec} to continue configuring
*/
public HttpBasicSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
/**
* The {@link ServerSecurityContextRepository} used to save the {@code Authentication}. Defaults to
* {@link NoOpServerSecurityContextRepository}. For the {@code SecurityContext} to be loaded on subsequent
* requests the {@link ReactorContextWebFilter} must be configured to be able to load the value (they are not
* implicitly linked).
*
* @param securityContextRepository the repository to use
* @return the {@link HttpBasicSpec} to continue configuring
*/
public HttpBasicSpec securityContextRepository(ServerSecurityContextRepository securityContextRepository) {
this.securityContextRepository = securityContextRepository;
return this;
}
/**
* Allows easily setting the entry point.
* @param authenticationEntryPoint the {@link ServerAuthenticationEntryPoint} to use
* @return {@link HttpBasicSpec} for additional customization
* @since 5.2.0
* @author Ankur Pathak
*/
public HttpBasicSpec authenticationEntryPoint(ServerAuthenticationEntryPoint authenticationEntryPoint){
Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null");
this.entryPoint = authenticationEntryPoint;
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables HTTP Basic authentication.
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.httpBasic = null;
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
MediaTypeServerWebExchangeMatcher restMatcher = new MediaTypeServerWebExchangeMatcher(
MediaType.APPLICATION_ATOM_XML,
MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_XML,
MediaType.MULTIPART_FORM_DATA, MediaType.TEXT_XML);
restMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
ServerHttpSecurity.this.defaultEntryPoints.add(new DelegateEntry(restMatcher, this.entryPoint));
AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(
this.authenticationManager);
authenticationFilter.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(this.entryPoint));
authenticationFilter.setAuthenticationConverter(new ServerHttpBasicAuthenticationConverter());
authenticationFilter.setSecurityContextRepository(this.securityContextRepository);
http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.HTTP_BASIC);
}
private HttpBasicSpec() {}
}
/**
* Configures Form Based authentication
*
* @author Rob Winch
* @since 5.0
* @see #formLogin()
*/
public class FormLoginSpec {
private final RedirectServerAuthenticationSuccessHandler defaultSuccessHandler = new RedirectServerAuthenticationSuccessHandler("/");
private RedirectServerAuthenticationEntryPoint defaultEntryPoint;
private ReactiveAuthenticationManager authenticationManager;
private ServerSecurityContextRepository securityContextRepository;
private ServerAuthenticationEntryPoint authenticationEntryPoint;
private boolean isEntryPointExplicit;
private ServerWebExchangeMatcher requiresAuthenticationMatcher;
private ServerAuthenticationFailureHandler authenticationFailureHandler;
private ServerAuthenticationSuccessHandler authenticationSuccessHandler = this.defaultSuccessHandler;
/**
* The {@link ReactiveAuthenticationManager} used to authenticate. Defaults to
* {@link ServerHttpSecurity#authenticationManager(ReactiveAuthenticationManager)}.
*
* @param authenticationManager the authentication manager to use
* @return the {@link FormLoginSpec} to continue configuring
*/
public FormLoginSpec authenticationManager(ReactiveAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
return this;
}
/**
* The {@link ServerAuthenticationSuccessHandler} used after authentication success. Defaults to
* {@link RedirectServerAuthenticationSuccessHandler}.
* @param authenticationSuccessHandler the success handler to use
* @return the {@link FormLoginSpec} to continue configuring
*/
public FormLoginSpec authenticationSuccessHandler(
ServerAuthenticationSuccessHandler authenticationSuccessHandler) {
Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");
this.authenticationSuccessHandler = authenticationSuccessHandler;
return this;
}
/**
* Configures the log in page to redirect to, the authentication failure page, and when authentication is
* performed. The default is that Spring Security will generate a log in page at "/login" and a log out page at
* "/logout". If this is customized:
* <ul>
* <li>The default log in & log out page are no longer provided</li>
* <li>The application must render a log in page at the provided URL</li>
* <li>The application must render an authentication error page at the provided URL + "?error"</li>
* <li>Authentication will occur for POST to the provided URL</li>
* </ul>
* @param loginPage the url to redirect to which provides a form to log in (i.e. "/login")
* @return the {@link FormLoginSpec} to continue configuring
* @see #authenticationEntryPoint(ServerAuthenticationEntryPoint)
* @see #requiresAuthenticationMatcher(ServerWebExchangeMatcher)
* @see #authenticationFailureHandler(ServerAuthenticationFailureHandler)
*/
public FormLoginSpec loginPage(String loginPage) {
this.defaultEntryPoint = new RedirectServerAuthenticationEntryPoint(loginPage);
this.authenticationEntryPoint = this.defaultEntryPoint;
this.requiresAuthenticationMatcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, loginPage);
this.authenticationFailureHandler = new RedirectServerAuthenticationFailureHandler(loginPage + "?error");
return this;
}
/**
* How to request for authentication. The default is that Spring Security will
* generate a log in page at "/login".
* @param authenticationEntryPoint the entry point to use
* @return the {@link FormLoginSpec} to continue configuring
* @see #loginPage(String)
*/
public FormLoginSpec authenticationEntryPoint(ServerAuthenticationEntryPoint authenticationEntryPoint) {
this.authenticationEntryPoint = authenticationEntryPoint;
return this;
}
/**
* Configures when authentication is performed. The default is a POST to "/login".
* @param requiresAuthenticationMatcher the matcher to use
* @return the {@link FormLoginSpec} to continue configuring
* @see #loginPage(String)
*/
public FormLoginSpec requiresAuthenticationMatcher(ServerWebExchangeMatcher requiresAuthenticationMatcher) {
this.requiresAuthenticationMatcher = requiresAuthenticationMatcher;
return this;
}
/**
* Configures how a failed authentication is handled. The default is to redirect to "/login?error".
* @param authenticationFailureHandler the handler to use
* @return the {@link FormLoginSpec} to continue configuring
* @see #loginPage(String)
*/
public FormLoginSpec authenticationFailureHandler(ServerAuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
return this;
}
/**
* The {@link ServerSecurityContextRepository} used to save the {@code Authentication}. Defaults to
* {@link WebSessionServerSecurityContextRepository}. For the {@code SecurityContext} to be loaded on subsequent
* requests the {@link ReactorContextWebFilter} must be configured to be able to load the value (they are not
* implicitly linked).
*
* @param securityContextRepository the repository to use
* @return the {@link FormLoginSpec} to continue configuring
*/
public FormLoginSpec securityContextRepository(ServerSecurityContextRepository securityContextRepository) {
this.securityContextRepository = securityContextRepository;
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables HTTP Basic authentication.
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.formLogin = null;
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
if (this.authenticationEntryPoint == null) {
this.isEntryPointExplicit = false;
loginPage("/login");
} else {
this.isEntryPointExplicit = true;
}
if (http.requestCache != null) {
ServerRequestCache requestCache = http.requestCache.requestCache;
this.defaultSuccessHandler.setRequestCache(requestCache);
if (this.defaultEntryPoint != null) {
this.defaultEntryPoint.setRequestCache(requestCache);
}
}
MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(
MediaType.TEXT_HTML);
htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
ServerHttpSecurity.this.defaultEntryPoints.add(0, new DelegateEntry(htmlMatcher, this.authenticationEntryPoint));
AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(
this.authenticationManager);
authenticationFilter.setRequiresAuthenticationMatcher(this.requiresAuthenticationMatcher);
authenticationFilter.setAuthenticationFailureHandler(this.authenticationFailureHandler);
authenticationFilter.setAuthenticationConverter(new ServerFormLoginAuthenticationConverter());
authenticationFilter.setAuthenticationSuccessHandler(this.authenticationSuccessHandler);
authenticationFilter.setSecurityContextRepository(this.securityContextRepository);
http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.FORM_LOGIN);
}
private FormLoginSpec() {
}
}
private class LoginPageSpec {
protected void configure(ServerHttpSecurity http) {
if (http.authenticationEntryPoint != null) {
return;
}
if (http.formLogin != null && http.formLogin.isEntryPointExplicit) {
return;
}
LoginPageGeneratingWebFilter loginPage = null;
if (http.formLogin != null && !http.formLogin.isEntryPointExplicit) {
loginPage = new LoginPageGeneratingWebFilter();
loginPage.setFormLoginEnabled(true);
}
if (http.oauth2Login != null) {
Map<String, String> urlToText = http.oauth2Login.getLinks();
if (loginPage == null) {
loginPage = new LoginPageGeneratingWebFilter();
}
loginPage.setOauth2AuthenticationUrlToClientName(urlToText);
}
if (loginPage != null) {
http.addFilterAt(loginPage, SecurityWebFiltersOrder.LOGIN_PAGE_GENERATING);
http.addFilterAt(new LogoutPageGeneratingWebFilter(), SecurityWebFiltersOrder.LOGOUT_PAGE_GENERATING);
}
}
private LoginPageSpec() {}
}
/**
* Configures HTTP Response Headers.
*
* @author Rob Winch
* @since 5.0
* @see #headers()
*/
public class HeaderSpec {
private final List<ServerHttpHeadersWriter> writers;
private CacheControlServerHttpHeadersWriter cacheControl = new CacheControlServerHttpHeadersWriter();
private ContentTypeOptionsServerHttpHeadersWriter contentTypeOptions = new ContentTypeOptionsServerHttpHeadersWriter();
private StrictTransportSecurityServerHttpHeadersWriter hsts = new StrictTransportSecurityServerHttpHeadersWriter();
private XFrameOptionsServerHttpHeadersWriter frameOptions = new XFrameOptionsServerHttpHeadersWriter();
private XXssProtectionServerHttpHeadersWriter xss = new XXssProtectionServerHttpHeadersWriter();
private FeaturePolicyServerHttpHeadersWriter featurePolicy = new FeaturePolicyServerHttpHeadersWriter();
private ContentSecurityPolicyServerHttpHeadersWriter contentSecurityPolicy = new ContentSecurityPolicyServerHttpHeadersWriter();
private ReferrerPolicyServerHttpHeadersWriter referrerPolicy = new ReferrerPolicyServerHttpHeadersWriter();
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables http response headers
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.headers = null;
return ServerHttpSecurity.this;
}
/**
* Configures cache control headers
* @return the {@link CacheSpec} to configure
*/
public CacheSpec cache() {
return new CacheSpec();
}
/**
* Configures cache control headers
*
* @param cacheCustomizer the {@link Customizer} to provide more options for
* the {@link CacheSpec}
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec cache(Customizer<CacheSpec> cacheCustomizer) {
cacheCustomizer.customize(new CacheSpec());
return this;
}
/**
* Configures content type response headers
* @return the {@link ContentTypeOptionsSpec} to configure
*/
public ContentTypeOptionsSpec contentTypeOptions() {
return new ContentTypeOptionsSpec();
}
/**
* Configures content type response headers
*
* @param contentTypeOptionsCustomizer the {@link Customizer} to provide more options for
* the {@link ContentTypeOptionsSpec}
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec contentTypeOptions(Customizer<ContentTypeOptionsSpec> contentTypeOptionsCustomizer) {
contentTypeOptionsCustomizer.customize(new ContentTypeOptionsSpec());
return this;
}
/**
* Configures frame options response headers
* @return the {@link FrameOptionsSpec} to configure
*/
public FrameOptionsSpec frameOptions() {
return new FrameOptionsSpec();
}
/**
* Configures frame options response headers
*
* @param frameOptionsCustomizer the {@link Customizer} to provide more options for
* the {@link FrameOptionsSpec}
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec frameOptions(Customizer<FrameOptionsSpec> frameOptionsCustomizer) {
frameOptionsCustomizer.customize(new FrameOptionsSpec());
return this;
}
/**
* Configures the Strict Transport Security response headers
* @return the {@link HstsSpec} to configure
*/
public HstsSpec hsts() {
return new HstsSpec();
}
/**
* Configures the Strict Transport Security response headers
*
* @param hstsCustomizer the {@link Customizer} to provide more options for
* the {@link HstsSpec}
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec hsts(Customizer<HstsSpec> hstsCustomizer) {
hstsCustomizer.customize(new HstsSpec());
return this;
}
protected void configure(ServerHttpSecurity http) {
ServerHttpHeadersWriter writer = new CompositeServerHttpHeadersWriter(this.writers);
HttpHeaderWriterWebFilter result = new HttpHeaderWriterWebFilter(writer);
http.addFilterAt(result, SecurityWebFiltersOrder.HTTP_HEADERS_WRITER);
}
/**
* Configures x-xss-protection response header.
* @return the {@link XssProtectionSpec} to configure
*/
public XssProtectionSpec xssProtection() {
return new XssProtectionSpec();
}
/**
* Configures x-xss-protection response header.
*
* @param xssProtectionCustomizer the {@link Customizer} to provide more options for
* the {@link XssProtectionSpec}
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec xssProtection(Customizer<XssProtectionSpec> xssProtectionCustomizer) {
xssProtectionCustomizer.customize(new XssProtectionSpec());
return this;
}
/**
* Configures {@code Content-Security-Policy} response header.
* @param policyDirectives the policy directive(s)
* @return the {@link ContentSecurityPolicySpec} to configure
*/
public ContentSecurityPolicySpec contentSecurityPolicy(String policyDirectives) {
return new ContentSecurityPolicySpec(policyDirectives);
}
/**
* Configures {@code Content-Security-Policy} response header.
*
* @param contentSecurityPolicyCustomizer the {@link Customizer} to provide more options for
* the {@link ContentSecurityPolicySpec}
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec contentSecurityPolicy(Customizer<ContentSecurityPolicySpec> contentSecurityPolicyCustomizer) {
contentSecurityPolicyCustomizer.customize(new ContentSecurityPolicySpec());
return this;
}
/**
* Configures {@code Feature-Policy} response header.
* @param policyDirectives the policy directive(s)
* @return the {@link FeaturePolicySpec} to configure
*/
public FeaturePolicySpec featurePolicy(String policyDirectives) {
return new FeaturePolicySpec(policyDirectives);
}
/**
* Configures {@code Referrer-Policy} response header.
* @param referrerPolicy the policy to use
* @return the {@link ReferrerPolicySpec} to configure
*/
public ReferrerPolicySpec referrerPolicy(ReferrerPolicy referrerPolicy) {
return new ReferrerPolicySpec(referrerPolicy);
}
/**
* Configures {@code Referrer-Policy} response header.
* @return the {@link ReferrerPolicySpec} to configure
*/
public ReferrerPolicySpec referrerPolicy() {
return new ReferrerPolicySpec();
}
/**
* Configures {@code Referrer-Policy} response header.
*
* @param referrerPolicyCustomizer the {@link Customizer} to provide more options for
* the {@link ReferrerPolicySpec}
* @return the {@link HeaderSpec} to customize
*/
public HeaderSpec referrerPolicy(Customizer<ReferrerPolicySpec> referrerPolicyCustomizer) {
referrerPolicyCustomizer.customize(new ReferrerPolicySpec());
return this;
}
/**
* Configures cache control headers
* @see #cache()
*/
public class CacheSpec {
/**
* Disables cache control response headers
* @return the {@link HeaderSpec} to configure
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.cacheControl);
return HeaderSpec.this;
}
private CacheSpec() {}
}
/**
* The content type headers
* @see #contentTypeOptions()
*/
public class ContentTypeOptionsSpec {
/**
* Disables the content type options response header
* @return the {@link HeaderSpec} to configure
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.contentTypeOptions);
return HeaderSpec.this;
}
private ContentTypeOptionsSpec() {}
}
/**
* Configures frame options response header
* @see #frameOptions()
*/
public class FrameOptionsSpec {
/**
* The mode to configure. Default is
* {@link org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter.Mode#DENY}
* @param mode the mode to use
* @return the {@link HeaderSpec} to configure
*/
public HeaderSpec mode(XFrameOptionsServerHttpHeadersWriter.Mode mode) {
HeaderSpec.this.frameOptions.setMode(mode);
return and();
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link HeaderSpec} to continue configuring
*/
private HeaderSpec and() {
return HeaderSpec.this;
}
/**
* Disables frame options response header
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.frameOptions);
return and();
}
private FrameOptionsSpec() {}
}
/**
* Configures Strict Transport Security response header
* @see #hsts()
*/
public class HstsSpec {
/**
* Configures the max age. Default is one year.
* @param maxAge the max age
* @return the {@link HstsSpec} to continue configuring
*/
public HstsSpec maxAge(Duration maxAge) {
HeaderSpec.this.hsts.setMaxAge(maxAge);
return this;
}
/**
* Configures if subdomains should be included. Default is true
* @param includeSubDomains if subdomains should be included
* @return the {@link HstsSpec} to continue configuring
*/
public HstsSpec includeSubdomains(boolean includeSubDomains) {
HeaderSpec.this.hsts.setIncludeSubDomains(includeSubDomains);
return this;
}
/**
* <p>
* Configures if preload should be included. Default is false
* </p>
*
* <p>
* See <a href="https://hstspreload.org/">Website hstspreload.org</a>
* for additional details.
* </p>
*
* @param preload if subdomains should be included
* @return the {@link HstsSpec} to continue configuring
* @since 5.2.0
* @author Ankur Pathak
*/
public HstsSpec preload(boolean preload) {
HeaderSpec.this.hsts.setPreload(preload);
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec and() {
return HeaderSpec.this;
}
/**
* Disables strict transport security response header
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.hsts);
return HeaderSpec.this;
}
private HstsSpec() {}
}
/**
* Configures x-xss-protection response header
* @see #xssProtection()
*/
public class XssProtectionSpec {
/**
* Disables the x-xss-protection response header
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec disable() {
HeaderSpec.this.writers.remove(HeaderSpec.this.xss);
return HeaderSpec.this;
}
private XssProtectionSpec() {}
}
/**
* Configures {@code Content-Security-Policy} response header.
*
* @see #contentSecurityPolicy(String)
* @since 5.1
*/
public class ContentSecurityPolicySpec {
private static final String DEFAULT_SRC_SELF_POLICY = "default-src 'self'";
/**
* Whether to include the {@code Content-Security-Policy-Report-Only} header in
* the response. Otherwise, defaults to the {@code Content-Security-Policy} header.
* @param reportOnly whether to only report policy violations
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec reportOnly(boolean reportOnly) {
HeaderSpec.this.contentSecurityPolicy.setReportOnly(reportOnly);
return HeaderSpec.this;
}
/**
* Sets the security policy directive(s) to be used in the response header.
*
* @param policyDirectives the security policy directive(s)
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec policyDirectives(String policyDirectives) {
HeaderSpec.this.contentSecurityPolicy.setPolicyDirectives(policyDirectives);
return HeaderSpec.this;
}
/**
* Allows method chaining to continue configuring the
* {@link ServerHttpSecurity}.
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec and() {
return HeaderSpec.this;
}
private ContentSecurityPolicySpec(String policyDirectives) {
HeaderSpec.this.contentSecurityPolicy.setPolicyDirectives(policyDirectives);
}
private ContentSecurityPolicySpec() {
HeaderSpec.this.contentSecurityPolicy.setPolicyDirectives(DEFAULT_SRC_SELF_POLICY);
}
}
/**
* Configures {@code Feature-Policy} response header.
*
* @see #featurePolicy(String)
* @since 5.1
*/
public class FeaturePolicySpec {
/**
* Allows method chaining to continue configuring the
* {@link ServerHttpSecurity}.
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec and() {
return HeaderSpec.this;
}
private FeaturePolicySpec(String policyDirectives) {
HeaderSpec.this.featurePolicy.setPolicyDirectives(policyDirectives);
}
}
/**
* Configures {@code Referrer-Policy} response header.
*
* @see #referrerPolicy()
* @see #referrerPolicy(ReferrerPolicy)
* @since 5.1
*/
public class ReferrerPolicySpec {
/**
* Sets the policy to be used in the response header.
*
* @param referrerPolicy a referrer policy
* @return the {@link ReferrerPolicySpec} to continue configuring
*/
public ReferrerPolicySpec policy(ReferrerPolicy referrerPolicy) {
HeaderSpec.this.referrerPolicy.setPolicy(referrerPolicy);
return this;
}
/**
* Allows method chaining to continue configuring the
* {@link ServerHttpSecurity}.
* @return the {@link HeaderSpec} to continue configuring
*/
public HeaderSpec and() {
return HeaderSpec.this;
}
private ReferrerPolicySpec() {
}
private ReferrerPolicySpec(ReferrerPolicy referrerPolicy) {
HeaderSpec.this.referrerPolicy.setPolicy(referrerPolicy);
}
}
private HeaderSpec() {
this.writers = new ArrayList<>(
Arrays.asList(this.cacheControl, this.contentTypeOptions, this.hsts,
this.frameOptions, this.xss, this.featurePolicy, this.contentSecurityPolicy,
this.referrerPolicy));
}
}
/**
* Configures log out
* @author Shazin Sadakath
* @since 5.0
* @see #logout()
*/
public final class LogoutSpec {
private LogoutWebFilter logoutWebFilter = new LogoutWebFilter();
private List<ServerLogoutHandler> logoutHandlers = new ArrayList<>(Arrays.asList(new SecurityContextServerLogoutHandler()));
/**
* Configures the logout handler. Default is {@code SecurityContextServerLogoutHandler}
* @param logoutHandler
* @return the {@link LogoutSpec} to configure
*/
public LogoutSpec logoutHandler(ServerLogoutHandler logoutHandler) {
Assert.notNull(logoutHandler, "logoutHandler cannot be null");
this.logoutHandlers.clear();
return addLogoutHandler(logoutHandler);
}
private LogoutSpec addLogoutHandler(ServerLogoutHandler logoutHandler) {
Assert.notNull(logoutHandler, "logoutHandler cannot be null");
this.logoutHandlers.add(logoutHandler);
return this;
}
/**
* Configures what URL a POST to will trigger a log out.
* @param logoutUrl the url to trigger a log out (i.e. "/signout" would mean a POST to "/signout" would trigger
* log out)
* @return the {@link LogoutSpec} to configure
*/
public LogoutSpec logoutUrl(String logoutUrl) {
Assert.notNull(logoutUrl, "logoutUrl must not be null");
ServerWebExchangeMatcher requiresLogout = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, logoutUrl);
return requiresLogout(requiresLogout);
}
/**
* Configures when the log out will be triggered.
* @param requiresLogout the matcher to determine when log out is triggered
* @return the {@link LogoutSpec} to configure
*/
public LogoutSpec requiresLogout(ServerWebExchangeMatcher requiresLogout) {
this.logoutWebFilter.setRequiresLogoutMatcher(requiresLogout);
return this;
}
public LogoutSpec logoutSuccessHandler(ServerLogoutSuccessHandler handler) {
this.logoutWebFilter.setLogoutSuccessHandler(handler);
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables log out
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.logout = null;
return and();
}
private ServerLogoutHandler createLogoutHandler() {
if (this.logoutHandlers.isEmpty()) {
return null;
} else if (this.logoutHandlers.size() == 1) {
return this.logoutHandlers.get(0);
} else {
return new DelegatingServerLogoutHandler(this.logoutHandlers);
}
}
protected void configure(ServerHttpSecurity http) {
ServerLogoutHandler logoutHandler = createLogoutHandler();
if (logoutHandler != null) {
this.logoutWebFilter.setLogoutHandler(logoutHandler);
}
http.addFilterAt(this.logoutWebFilter, SecurityWebFiltersOrder.LOGOUT);
}
private LogoutSpec() {}
}
private <T> T getBean(Class<T> beanClass) {
if (this.context == null) {
return null;
}
return this.context.getBean(beanClass);
}
private <T> T getBeanOrNull(Class<T> beanClass) {
return getBeanOrNull(ResolvableType.forClass(beanClass));
}
private <T> T getBeanOrNull(ResolvableType type) {
if (this.context == null) {
return null;
}
String[] names = this.context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) this.context.getBean(names[0]);
}
return null;
}
protected void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
private static class OrderedWebFilter implements WebFilter, Ordered {
private final WebFilter webFilter;
private final int order;
OrderedWebFilter(WebFilter webFilter, int order) {
this.webFilter = webFilter;
this.order = order;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange,
WebFilterChain chain) {
return this.webFilter.filter(exchange, chain);
}
@Override
public int getOrder() {
return this.order;
}
@Override
public String toString() {
return "OrderedWebFilter{" + "webFilter=" + this.webFilter + ", order=" + this.order
+ '}';
}
}
/**
* Workaround https://jira.spring.io/projects/SPR/issues/SPR-17213
*/
static class ServerWebExchangeReactorContextWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange)
.subscriberContext(Context.of(ServerWebExchange.class, exchange));
}
}
/**
* Configures anonymous authentication
* @author Ankur Pathak
* @since 5.2.0
*/
public final class AnonymousSpec {
private String key;
private AnonymousAuthenticationWebFilter authenticationFilter;
private Object principal = "anonymousUser";
private List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
/**
* Sets the key to identify tokens created for anonymous authentication. Default is a
* secure randomly generated key.
*
* @param key the key to identify tokens created for anonymous authentication. Default
* is a secure randomly generated key.
* @return the {@link AnonymousSpec} for further customization of anonymous
* authentication
*/
public AnonymousSpec key(String key) {
this.key = key;
return this;
}
/**
* Sets the principal for {@link Authentication} objects of anonymous users
*
* @param principal used for the {@link Authentication} object of anonymous users
* @return the {@link AnonymousSpec} for further customization of anonymous
* authentication
*/
public AnonymousSpec principal(Object principal) {
this.principal = principal;
return this;
}
/**
* Sets the {@link org.springframework.security.core.Authentication#getAuthorities()}
* for anonymous users
*
* @param authorities Sets the
* {@link org.springframework.security.core.Authentication#getAuthorities()} for
* anonymous users
* @return the {@link AnonymousSpec} for further customization of anonymous
* authentication
*/
public AnonymousSpec authorities(List<GrantedAuthority> authorities) {
this.authorities = authorities;
return this;
}
/**
* Sets the {@link org.springframework.security.core.Authentication#getAuthorities()}
* for anonymous users
*
* @param authorities Sets the
* {@link org.springframework.security.core.Authentication#getAuthorities()} for
* anonymous users (i.e. "ROLE_ANONYMOUS")
* @return the {@link AnonymousSpec} for further customization of anonymous
* authentication
*/
public AnonymousSpec authorities(String... authorities) {
return authorities(AuthorityUtils.createAuthorityList(authorities));
}
/**
* Sets the {@link AnonymousAuthenticationWebFilter} used to populate an anonymous user.
* If this is set, no attributes on the {@link AnonymousSpec} will be set on the
* {@link AnonymousAuthenticationWebFilter}.
*
* @param authenticationFilter the {@link AnonymousAuthenticationWebFilter} used to
* populate an anonymous user.
*
* @return the {@link AnonymousSpec} for further customization of anonymous
* authentication
*/
public AnonymousSpec authenticationFilter(
AnonymousAuthenticationWebFilter authenticationFilter) {
this.authenticationFilter = authenticationFilter;
return this;
}
/**
* Allows method chaining to continue configuring the {@link ServerHttpSecurity}
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
/**
* Disables anonymous authentication.
* @return the {@link ServerHttpSecurity} to continue configuring
*/
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.anonymous = null;
return ServerHttpSecurity.this;
}
protected void configure(ServerHttpSecurity http) {
if (authenticationFilter == null) {
authenticationFilter = new AnonymousAuthenticationWebFilter(getKey(), principal,
authorities);
}
http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.ANONYMOUS_AUTHENTICATION);
}
private String getKey() {
if (key == null) {
key = UUID.randomUUID().toString();
}
return key;
}
private AnonymousSpec() {}
}
}
| 1 | 14,689 | Remove unused import | spring-projects-spring-security | java |
@@ -182,7 +182,7 @@ func (i *Instance) Restart(newCaddyfile Input) (*Instance, error) {
newInst := &Instance{serverType: newCaddyfile.ServerType(), wg: i.wg}
// attempt to start new instance
- err := startWithListenerFds(newCaddyfile, newInst, restartFds)
+ err := startWithListenerFds(newCaddyfile, newInst, restartFds, false)
if err != nil {
return i, err
} | 1 | // Package caddy implements the Caddy server manager.
//
// To use this package:
//
// 1. Set the AppName and AppVersion variables.
// 2. Call LoadCaddyfile() to get the Caddyfile.
// Pass in the name of the server type (like "http").
// 3. Call caddy.Start() to start Caddy. You get back
// an Instance, on which you can call Restart() to
// restart it or Stop() to stop it.
//
// You should call Wait() on your instance to wait for
// all servers to quit before your process exits.
package caddy
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/mholt/caddy/caddyfile"
)
// Configurable application parameters
var (
// AppName is the name of the application.
AppName string
// AppVersion is the version of the application.
AppVersion string
// Quiet mode will not show any informative output on initialization.
Quiet bool
// PidFile is the path to the pidfile to create.
PidFile string
// GracefulTimeout is the maximum duration of a graceful shutdown.
GracefulTimeout time.Duration
// isUpgrade will be set to true if this process
// was started as part of an upgrade, where a parent
// Caddy process started this one.
isUpgrade bool
// started will be set to true when the first
// instance is started; it never gets set to
// false after that.
started bool
// mu protects the variables 'isUpgrade' and 'started'.
mu sync.Mutex
)
// Instance contains the state of servers created as a result of
// calling Start and can be used to access or control those servers.
type Instance struct {
// serverType is the name of the instance's server type
serverType string
// caddyfileInput is the input configuration text used for this process
caddyfileInput Input
// wg is used to wait for all servers to shut down
wg *sync.WaitGroup
// context is the context created for this instance.
context Context
// servers is the list of servers with their listeners.
servers []ServerListener
// these callbacks execute when certain events occur
onFirstStartup []func() error // starting, not as part of a restart
onStartup []func() error // starting, even as part of a restart
onRestart []func() error // before restart commences
onShutdown []func() error // stopping, even as part of a restart
onFinalShutdown []func() error // stopping, not as part of a restart
}
// Servers returns the ServerListeners in i.
func (i *Instance) Servers() []ServerListener { return i.servers }
// Stop stops all servers contained in i. It does NOT
// execute shutdown callbacks.
func (i *Instance) Stop() error {
// stop the servers
for _, s := range i.servers {
if gs, ok := s.server.(GracefulServer); ok {
if err := gs.Stop(); err != nil {
log.Printf("[ERROR] Stopping %s: %v", gs.Address(), err)
}
}
}
// splice i out of instance list, causing it to be garbage-collected
instancesMu.Lock()
for j, other := range instances {
if other == i {
instances = append(instances[:j], instances[j+1:]...)
break
}
}
instancesMu.Unlock()
return nil
}
// ShutdownCallbacks executes all the shutdown callbacks of i,
// including ones that are scheduled only for the final shutdown
// of i. An error returned from one does not stop execution of
// the rest. All the non-nil errors will be returned.
func (i *Instance) ShutdownCallbacks() []error {
var errs []error
for _, shutdownFunc := range i.onShutdown {
err := shutdownFunc()
if err != nil {
errs = append(errs, err)
}
}
for _, finalShutdownFunc := range i.onFinalShutdown {
err := finalShutdownFunc()
if err != nil {
errs = append(errs, err)
}
}
return errs
}
// Restart replaces the servers in i with new servers created from
// executing the newCaddyfile. Upon success, it returns the new
// instance to replace i. Upon failure, i will not be replaced.
func (i *Instance) Restart(newCaddyfile Input) (*Instance, error) {
log.Println("[INFO] Reloading")
i.wg.Add(1)
defer i.wg.Done()
// run restart callbacks
for _, fn := range i.onRestart {
err := fn()
if err != nil {
return i, err
}
}
if newCaddyfile == nil {
newCaddyfile = i.caddyfileInput
}
// Add file descriptors of all the sockets that are capable of it
restartFds := make(map[string]restartTriple)
for _, s := range i.servers {
gs, srvOk := s.server.(GracefulServer)
ln, lnOk := s.listener.(Listener)
pc, pcOk := s.packet.(PacketConn)
if srvOk {
if lnOk && pcOk {
restartFds[gs.Address()] = restartTriple{server: gs, listener: ln, packet: pc}
continue
}
if lnOk {
restartFds[gs.Address()] = restartTriple{server: gs, listener: ln}
continue
}
if pcOk {
restartFds[gs.Address()] = restartTriple{server: gs, packet: pc}
continue
}
}
}
// create new instance; if the restart fails, it is simply discarded
newInst := &Instance{serverType: newCaddyfile.ServerType(), wg: i.wg}
// attempt to start new instance
err := startWithListenerFds(newCaddyfile, newInst, restartFds)
if err != nil {
return i, err
}
// success! stop the old instance
for _, shutdownFunc := range i.onShutdown {
err := shutdownFunc()
if err != nil {
return i, err
}
}
i.Stop()
log.Println("[INFO] Reloading complete")
return newInst, nil
}
// SaveServer adds s and its associated listener ln to the
// internally-kept list of servers that is running. For
// saved servers, graceful restarts will be provided.
func (i *Instance) SaveServer(s Server, ln net.Listener) {
i.servers = append(i.servers, ServerListener{server: s, listener: ln})
}
// HasListenerWithAddress returns whether this package is
// tracking a server using a listener with the address
// addr.
func HasListenerWithAddress(addr string) bool {
instancesMu.Lock()
defer instancesMu.Unlock()
for _, inst := range instances {
for _, sln := range inst.servers {
if listenerAddrEqual(sln.listener, addr) {
return true
}
}
}
return false
}
// listenerAddrEqual compares a listener's address with
// addr. Extra care is taken to match addresses with an
// empty hostname portion, as listeners tend to report
// [::]:80, for example, when the matching address that
// created the listener might be simply :80.
func listenerAddrEqual(ln net.Listener, addr string) bool {
lnAddr := ln.Addr().String()
hostname, port, err := net.SplitHostPort(addr)
if err != nil {
return lnAddr == addr
}
if lnAddr == net.JoinHostPort("::", port) {
return true
}
if lnAddr == net.JoinHostPort("0.0.0.0", port) {
return true
}
return hostname != "" && lnAddr == addr
}
// TCPServer is a type that can listen and serve connections.
// A TCPServer must associate with exactly zero or one net.Listeners.
type TCPServer interface {
// Listen starts listening by creating a new listener
// and returning it. It does not start accepting
// connections. For UDP-only servers, this method
// can be a no-op that returns (nil, nil).
Listen() (net.Listener, error)
// Serve starts serving using the provided listener.
// Serve must start the server loop nearly immediately,
// or at least not return any errors before the server
// loop begins. Serve blocks indefinitely, or in other
// words, until the server is stopped. For UDP-only
// servers, this method can be a no-op that returns nil.
Serve(net.Listener) error
}
// UDPServer is a type that can listen and serve packets.
// A UDPServer must associate with exactly zero or one net.PacketConns.
type UDPServer interface {
// ListenPacket starts listening by creating a new packetconn
// and returning it. It does not start accepting connections.
// TCP-only servers may leave this method blank and return
// (nil, nil).
ListenPacket() (net.PacketConn, error)
// ServePacket starts serving using the provided packetconn.
// ServePacket must start the server loop nearly immediately,
// or at least not return any errors before the server
// loop begins. ServePacket blocks indefinitely, or in other
// words, until the server is stopped. For TCP-only servers,
// this method can be a no-op that returns nil.
ServePacket(net.PacketConn) error
}
// Server is a type that can listen and serve. It supports both
// TCP and UDP, although the UDPServer interface can be used
// for more than just UDP.
//
// If the server uses TCP, it should implement TCPServer completely.
// If it uses UDP or some other protocol, it should implement
// UDPServer completely. If it uses both, both interfaces should be
// fully implemented. Any unimplemented methods should be made as
// no-ops that simply return nil values.
type Server interface {
TCPServer
UDPServer
}
// Stopper is a type that can stop serving. The stop
// does not necessarily have to be graceful.
type Stopper interface {
// Stop stops the server. It blocks until the
// server is completely stopped.
Stop() error
}
// GracefulServer is a Server and Stopper, the stopping
// of which is graceful (whatever that means for the kind
// of server being implemented). It must be able to return
// the address it is configured to listen on so that its
// listener can be paired with it upon graceful restarts.
// The net.Listener that a GracefulServer creates must
// implement the Listener interface for restarts to be
// graceful (assuming the listener is for TCP).
type GracefulServer interface {
Server
Stopper
// Address returns the address the server should
// listen on; it is used to pair the server to
// its listener during a graceful/zero-downtime
// restart. Thus when implementing this method,
// you must not access a listener to get the
// address; you must store the address the
// server is to serve on some other way.
Address() string
}
// Listener is a net.Listener with an underlying file descriptor.
// A server's listener should implement this interface if it is
// to support zero-downtime reloads.
type Listener interface {
net.Listener
File() (*os.File, error)
}
// PacketConn is a net.PacketConn with an underlying file descriptor.
// A server's packetconn should implement this interface if it is
// to support zero-downtime reloads (in sofar this holds true for datagram
// connections).
type PacketConn interface {
net.PacketConn
File() (*os.File, error)
}
// AfterStartup is an interface that can be implemented
// by a server type that wants to run some code after all
// servers for the same Instance have started.
type AfterStartup interface {
OnStartupComplete()
}
// LoadCaddyfile loads a Caddyfile by calling the plugged in
// Caddyfile loader methods. An error is returned if more than
// one loader returns a non-nil Caddyfile input. If no loaders
// load a Caddyfile, the default loader is used. If no default
// loader is registered or it returns nil, the server type's
// default Caddyfile is loaded. If the server type does not
// specify any default Caddyfile value, then an empty Caddyfile
// is returned. Consequently, this function never returns a nil
// value as long as there are no errors.
func LoadCaddyfile(serverType string) (Input, error) {
// Ask plugged-in loaders for a Caddyfile
cdyfile, err := loadCaddyfileInput(serverType)
if err != nil {
return nil, err
}
// Otherwise revert to default
if cdyfile == nil {
cdyfile = DefaultInput(serverType)
}
// Still nil? Geez.
if cdyfile == nil {
cdyfile = CaddyfileInput{ServerTypeName: serverType}
}
return cdyfile, nil
}
// Wait blocks until all of i's servers have stopped.
func (i *Instance) Wait() {
i.wg.Wait()
}
// CaddyfileFromPipe loads the Caddyfile input from f if f is
// not interactive input. f is assumed to be a pipe or stream,
// such as os.Stdin. If f is not a pipe, no error is returned
// but the Input value will be nil. An error is only returned
// if there was an error reading the pipe, even if the length
// of what was read is 0.
func CaddyfileFromPipe(f *os.File, serverType string) (Input, error) {
fi, err := f.Stat()
if err == nil && fi.Mode()&os.ModeCharDevice == 0 {
// Note that a non-nil error is not a problem. Windows
// will not create a stdin if there is no pipe, which
// produces an error when calling Stat(). But Unix will
// make one either way, which is why we also check that
// bitmask.
// NOTE: Reading from stdin after this fails (e.g. for the let's encrypt email address) (OS X)
confBody, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return CaddyfileInput{
Contents: confBody,
Filepath: f.Name(),
ServerTypeName: serverType,
}, nil
}
// not having input from the pipe is not itself an error,
// just means no input to return.
return nil, nil
}
// Caddyfile returns the Caddyfile used to create i.
func (i *Instance) Caddyfile() Input {
return i.caddyfileInput
}
// Start starts Caddy with the given Caddyfile.
//
// This function blocks until all the servers are listening.
func Start(cdyfile Input) (*Instance, error) {
writePidFile()
inst := &Instance{serverType: cdyfile.ServerType(), wg: new(sync.WaitGroup)}
return inst, startWithListenerFds(cdyfile, inst, nil)
}
func startWithListenerFds(cdyfile Input, inst *Instance, restartFds map[string]restartTriple) error {
if cdyfile == nil {
cdyfile = CaddyfileInput{}
}
stypeName := cdyfile.ServerType()
stype, err := getServerType(stypeName)
if err != nil {
return err
}
inst.caddyfileInput = cdyfile
sblocks, err := loadServerBlocks(stypeName, cdyfile.Path(), bytes.NewReader(cdyfile.Body()))
if err != nil {
return err
}
inst.context = stype.NewContext()
if inst.context == nil {
return fmt.Errorf("server type %s produced a nil Context", stypeName)
}
sblocks, err = inst.context.InspectServerBlocks(cdyfile.Path(), sblocks)
if err != nil {
return err
}
err = executeDirectives(inst, cdyfile.Path(), stype.Directives(), sblocks)
if err != nil {
return err
}
slist, err := inst.context.MakeServers()
if err != nil {
return err
}
// run startup callbacks
if restartFds == nil {
for _, firstStartupFunc := range inst.onFirstStartup {
err := firstStartupFunc()
if err != nil {
return err
}
}
}
for _, startupFunc := range inst.onStartup {
err := startupFunc()
if err != nil {
return err
}
}
err = startServers(slist, inst, restartFds)
if err != nil {
return err
}
instancesMu.Lock()
instances = append(instances, inst)
instancesMu.Unlock()
// run any AfterStartup callbacks if this is not
// part of a restart; then show file descriptor notice
if restartFds == nil {
for _, srvln := range inst.servers {
if srv, ok := srvln.server.(AfterStartup); ok {
srv.OnStartupComplete()
}
}
if !Quiet {
for _, srvln := range inst.servers {
if !IsLoopback(srvln.listener.Addr().String()) {
checkFdlimit()
break
}
}
}
}
mu.Lock()
started = true
mu.Unlock()
return nil
}
func executeDirectives(inst *Instance, filename string,
directives []string, sblocks []caddyfile.ServerBlock) error {
// map of server block ID to map of directive name to whatever.
storages := make(map[int]map[string]interface{})
// It is crucial that directives are executed in the proper order.
// We loop with the directives on the outer loop so we execute
// a directive for all server blocks before going to the next directive.
// This is important mainly due to the parsing callbacks (below).
for _, dir := range directives {
for i, sb := range sblocks {
var once sync.Once
if _, ok := storages[i]; !ok {
storages[i] = make(map[string]interface{})
}
for j, key := range sb.Keys {
// Execute directive if it is in the server block
if tokens, ok := sb.Tokens[dir]; ok {
controller := &Controller{
instance: inst,
Key: key,
Dispenser: caddyfile.NewDispenserTokens(filename, tokens),
OncePerServerBlock: func(f func() error) error {
var err error
once.Do(func() {
err = f()
})
return err
},
ServerBlockIndex: i,
ServerBlockKeyIndex: j,
ServerBlockKeys: sb.Keys,
ServerBlockStorage: storages[i][dir],
}
setup, err := DirectiveAction(inst.serverType, dir)
if err != nil {
return err
}
err = setup(controller)
if err != nil {
return err
}
storages[i][dir] = controller.ServerBlockStorage // persist for this server block
}
}
}
// See if there are any callbacks to execute after this directive
if allCallbacks, ok := parsingCallbacks[inst.serverType]; ok {
callbacks := allCallbacks[dir]
for _, callback := range callbacks {
if err := callback(inst.context); err != nil {
return err
}
}
}
}
return nil
}
func startServers(serverList []Server, inst *Instance, restartFds map[string]restartTriple) error {
errChan := make(chan error, len(serverList))
for _, s := range serverList {
var (
ln net.Listener
pc net.PacketConn
err error
)
// If this is a reload and s is a GracefulServer,
// reuse the listener for a graceful restart.
if gs, ok := s.(GracefulServer); ok && restartFds != nil {
addr := gs.Address()
if old, ok := restartFds[addr]; ok {
// listener
if old.listener != nil {
file, err := old.listener.File()
if err != nil {
return err
}
ln, err = net.FileListener(file)
if err != nil {
return err
}
file.Close()
}
// packetconn
if old.packet != nil {
file, err := old.packet.File()
if err != nil {
return err
}
pc, err = net.FilePacketConn(file)
if err != nil {
return err
}
file.Close()
}
}
}
if ln == nil {
ln, err = s.Listen()
if err != nil {
return err
}
}
if pc == nil {
pc, err = s.ListenPacket()
if err != nil {
return err
}
}
inst.wg.Add(2)
go func(s Server, ln net.Listener, pc net.PacketConn, inst *Instance) {
defer inst.wg.Done()
go func() {
errChan <- s.Serve(ln)
defer inst.wg.Done()
}()
errChan <- s.ServePacket(pc)
}(s, ln, pc, inst)
inst.servers = append(inst.servers, ServerListener{server: s, listener: ln, packet: pc})
}
// Log errors that may be returned from Serve() calls,
// these errors should only be occurring in the server loop.
go func() {
for err := range errChan {
if err == nil {
continue
}
if strings.Contains(err.Error(), "use of closed network connection") {
// this error is normal when closing the listener
continue
}
log.Println(err)
}
}()
return nil
}
func getServerType(serverType string) (ServerType, error) {
stype, ok := serverTypes[serverType]
if ok {
return stype, nil
}
if len(serverTypes) == 0 {
return ServerType{}, fmt.Errorf("no server types plugged in")
}
if serverType == "" {
if len(serverTypes) == 1 {
for _, stype := range serverTypes {
return stype, nil
}
}
return ServerType{}, fmt.Errorf("multiple server types available; must choose one")
}
return ServerType{}, fmt.Errorf("unknown server type '%s'", serverType)
}
func loadServerBlocks(serverType, filename string, input io.Reader) ([]caddyfile.ServerBlock, error) {
validDirectives := ValidDirectives(serverType)
serverBlocks, err := caddyfile.Parse(filename, input, validDirectives)
if err != nil {
return nil, err
}
if len(serverBlocks) == 0 && serverTypes[serverType].DefaultInput != nil {
newInput := serverTypes[serverType].DefaultInput()
serverBlocks, err = caddyfile.Parse(newInput.Path(),
bytes.NewReader(newInput.Body()), validDirectives)
if err != nil {
return nil, err
}
}
return serverBlocks, nil
}
// Stop stops ALL servers. It blocks until they are all stopped.
// It does NOT execute shutdown callbacks, and it deletes all
// instances after stopping is completed. Do not re-use any
// references to old instances after calling Stop.
func Stop() error {
// This awkward for loop is to avoid a deadlock since
// inst.Stop() also acquires the instancesMu lock.
for {
instancesMu.Lock()
if len(instances) == 0 {
break
}
inst := instances[0]
instancesMu.Unlock()
if err := inst.Stop(); err != nil {
log.Printf("[ERROR] Stopping %s: %v", inst.serverType, err)
}
}
return nil
}
// IsLoopback returns true if the hostname of addr looks
// explicitly like a common local hostname. addr must only
// be a host or a host:port combination.
func IsLoopback(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr // happens if the addr is just a hostname
}
return host == "localhost" ||
strings.Trim(host, "[]") == "::1" ||
strings.HasPrefix(host, "127.")
}
// Upgrade re-launches the process, preserving the listeners
// for a graceful restart. It does NOT load new configuration;
// it only starts the process anew with a fresh binary.
//
// TODO: This is not yet implemented
func Upgrade() error {
return fmt.Errorf("not implemented")
// TODO: have child process set isUpgrade = true
}
// IsUpgrade returns true if this process is part of an upgrade
// where a parent caddy process spawned this one to ugprade
// the binary.
func IsUpgrade() bool {
mu.Lock()
defer mu.Unlock()
return isUpgrade
}
// Started returns true if at least one instance has been
// started by this package. It never gets reset to false
// once it is set to true.
func Started() bool {
mu.Lock()
defer mu.Unlock()
return started
}
// CaddyfileInput represents a Caddyfile as input
// and is simply a convenient way to implement
// the Input interface.
type CaddyfileInput struct {
Filepath string
Contents []byte
ServerTypeName string
}
// Body returns c.Contents.
func (c CaddyfileInput) Body() []byte { return c.Contents }
// Path returns c.Filepath.
func (c CaddyfileInput) Path() string { return c.Filepath }
// ServerType returns c.ServerType.
func (c CaddyfileInput) ServerType() string { return c.ServerTypeName }
// Input represents a Caddyfile; its contents and file path
// (which should include the file name at the end of the path).
// If path does not apply (e.g. piped input) you may use
// any understandable value. The path is mainly used for logging,
// error messages, and debugging.
type Input interface {
// Gets the Caddyfile contents
Body() []byte
// Gets the path to the origin file
Path() string
// The type of server this input is intended for
ServerType() string
}
// DefaultInput returns the default Caddyfile input
// to use when it is otherwise empty or missing.
// It uses the default host and port (depends on
// host, e.g. localhost is 2015, otherwise 443) and
// root.
func DefaultInput(serverType string) Input {
if _, ok := serverTypes[serverType]; !ok {
return nil
}
if serverTypes[serverType].DefaultInput == nil {
return nil
}
return serverTypes[serverType].DefaultInput()
}
// writePidFile writes the process ID to the file at PidFile.
// It does nothing if PidFile is not set.
func writePidFile() error {
if PidFile == "" {
return nil
}
pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
return ioutil.WriteFile(PidFile, pid, 0644)
}
type restartTriple struct {
server GracefulServer
listener Listener
packet PacketConn
}
var (
// instances is the list of running Instances.
instances []*Instance
// instancesMu protects instances.
instancesMu sync.Mutex
)
var (
// DefaultConfigFile is the name of the configuration file that is loaded
// by default if no other file is specified.
DefaultConfigFile = "Caddyfile"
)
| 1 | 9,897 | I assume there will never be a scenario where justValidate is expected to be true on a restart | caddyserver-caddy | go |
@@ -356,6 +356,9 @@ public class PMD {
sortFiles(configuration, files);
+ // Make sure the cache is listening for analysis results
+ ctx.getReport().addListener(configuration.getAnalysisCache());
+
/*
* Check if multithreaded support is available. ExecutorService can also
* be disabled if threadCount is not positive, e.g. using the | 1 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.benchmark.Benchmark;
import net.sourceforge.pmd.benchmark.Benchmarker;
import net.sourceforge.pmd.benchmark.TextReport;
import net.sourceforge.pmd.cli.PMDCommandLineInterface;
import net.sourceforge.pmd.cli.PMDParameters;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageFilenameFilter;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.lang.LanguageVersionHandler;
import net.sourceforge.pmd.lang.Parser;
import net.sourceforge.pmd.lang.ParserOptions;
import net.sourceforge.pmd.processor.MonoThreadProcessor;
import net.sourceforge.pmd.processor.MultiThreadProcessor;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.stat.Metric;
import net.sourceforge.pmd.util.ClasspathClassLoader;
import net.sourceforge.pmd.util.FileUtil;
import net.sourceforge.pmd.util.IOUtil;
import net.sourceforge.pmd.util.database.DBMSMetadata;
import net.sourceforge.pmd.util.database.DBURI;
import net.sourceforge.pmd.util.database.SourceObject;
import net.sourceforge.pmd.util.datasource.DataSource;
import net.sourceforge.pmd.util.datasource.ReaderDataSource;
import net.sourceforge.pmd.util.log.ConsoleLogHandler;
import net.sourceforge.pmd.util.log.ScopedLogHandlersManager;
/**
* This is the main class for interacting with PMD. The primary flow of all Rule
* process is controlled via interactions with this class. A command line
* interface is supported, as well as a programmatic API for integrating PMD
* with other software such as IDEs and Ant.
*/
public class PMD {
private static final Logger LOG = Logger.getLogger(PMD.class.getName());
/** The line delimiter used by PMD in outputs. Usually the platform specific line separator. */
public static final String EOL = System.getProperty("line.separator", "\n");
/** The default suppress marker string. */
public static final String SUPPRESS_MARKER = "NOPMD";
/** Contains the configuration with which this PMD instance has been created. */
protected final PMDConfiguration configuration;
private final SourceCodeProcessor rulesetsFileProcessor;
/**
* Constant that contains always the current version of PMD.
*/
public static final String VERSION;
/**
* Create a PMD instance using a default Configuration. Changes to the
* configuration may be required.
*/
public PMD() {
this(new PMDConfiguration());
}
/**
* Create a PMD instance using the specified Configuration.
*
* @param configuration
* The runtime Configuration of PMD to use.
*/
public PMD(PMDConfiguration configuration) {
this.configuration = configuration;
this.rulesetsFileProcessor = new SourceCodeProcessor(configuration);
}
/**
* Parses the given string as a database uri and returns a list of datasources.
* @param uriString the URI to parse
* @return list of data sources
* @throws PMDException if the URI couldn't be parsed
* @see DBURI
*/
public static List<DataSource> getURIDataSources(String uriString) throws PMDException {
List<DataSource> dataSources = new ArrayList<>();
try {
DBURI dbUri = new DBURI(uriString);
DBMSMetadata dbmsMetadata = new DBMSMetadata(dbUri);
LOG.log(Level.FINE, "DBMSMetadata retrieved");
List<SourceObject> sourceObjectList = dbmsMetadata.getSourceObjectList();
LOG.log(Level.FINE, "Located {0} database source objects", sourceObjectList.size());
for (SourceObject sourceObject : sourceObjectList) {
String falseFilePath = sourceObject.getPseudoFileName();
LOG.log(Level.FINEST, "Adding database source object {0}", falseFilePath);
try {
dataSources.add(new ReaderDataSource(dbmsMetadata.getSourceCode(sourceObject), falseFilePath));
} catch (SQLException ex) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, "Cannot get SourceCode for " + falseFilePath + " - skipping ...", ex);
}
}
}
} catch (URISyntaxException e) {
throw new PMDException("Cannot get DataSources from DBURI - \"" + uriString + "\"", e);
} catch (SQLException e) {
throw new PMDException("Cannot get DataSources from DBURI, couldn't access the database - \"" + uriString
+ "\"", e);
} catch (ClassNotFoundException e) {
throw new PMDException("Cannot get DataSources from DBURI, probably missing database jdbc driver - \""
+ uriString + "\"", e);
} catch (Exception e) {
throw new PMDException("Encountered unexpected problem with URI \""
+ uriString + "\"", e);
}
return dataSources;
}
/**
* Helper method to get a configured parser for the requested language. The parser is
* configured based on the given {@link PMDConfiguration}.
* @param languageVersion the requested language
* @param configuration the given configuration
* @return the pre-configured parser
*/
public static Parser parserFor(LanguageVersion languageVersion, PMDConfiguration configuration) {
// TODO Handle Rules having different parser options.
LanguageVersionHandler languageVersionHandler = languageVersion.getLanguageVersionHandler();
ParserOptions options = languageVersionHandler.getDefaultParserOptions();
if (configuration != null) {
options.setSuppressMarker(configuration.getSuppressMarker());
}
return languageVersionHandler.getParser(options);
}
/**
* Create a report, filter out any defective rules, and keep a record of
* them.
*
* @param rs the rules
* @param ctx the rule context
* @param fileName the filename of the source file, which should appear in the report
* @return the Report
*/
public static Report setupReport(RuleSets rs, RuleContext ctx, String fileName) {
Set<Rule> brokenRules = removeBrokenRules(rs);
Report report = Report.createReport(ctx, fileName);
for (Rule rule : brokenRules) {
report.addConfigError(new Report.RuleConfigurationError(rule, rule.dysfunctionReason()));
}
return report;
}
/**
* Remove and return the misconfigured rules from the rulesets and log them
* for good measure.
*
* @param ruleSets
* RuleSets
* @return Set<Rule>
*/
private static Set<Rule> removeBrokenRules(RuleSets ruleSets) {
Set<Rule> brokenRules = new HashSet<>();
ruleSets.removeDysfunctionalRules(brokenRules);
for (Rule rule : brokenRules) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING,
"Removed misconfigured rule: " + rule.getName() + " cause: " + rule.dysfunctionReason());
}
}
return brokenRules;
}
/**
* Get the runtime configuration. The configuration can be modified to
* affect how PMD behaves.
*
* @return The configuration.
* @see PMDConfiguration
*/
public PMDConfiguration getConfiguration() {
return configuration;
}
/**
* Gets the source code processor.
* @return SourceCodeProcessor
*/
public SourceCodeProcessor getSourceCodeProcessor() {
return rulesetsFileProcessor;
}
/**
* This method is the main entry point for command line usage.
*
* @param configuration the configure to use
* @return number of violations found.
*/
public static int doPMD(PMDConfiguration configuration) {
// Load the RuleSets
RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration);
RuleSets ruleSets = RulesetsFactoryUtils.getRuleSetsWithBenchmark(configuration.getRuleSets(), ruleSetFactory);
if (ruleSets == null) {
return 0;
}
Set<Language> languages = getApplicableLanguages(configuration, ruleSets);
List<DataSource> files = getApplicableFiles(configuration, languages);
long reportStart = System.nanoTime();
try {
Renderer renderer = configuration.createRenderer();
List<Renderer> renderers = Collections.singletonList(renderer);
renderer.setWriter(IOUtil.createWriter(configuration.getReportFile()));
renderer.start();
Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
RuleContext ctx = new RuleContext();
final AtomicInteger violations = new AtomicInteger(0);
ctx.getReport().addListener(new ReportListener() {
@Override
public void ruleViolationAdded(RuleViolation ruleViolation) {
violations.incrementAndGet();
}
@Override
public void metricAdded(Metric metric) {
}
});
processFiles(configuration, ruleSetFactory, files, ctx, renderers);
reportStart = System.nanoTime();
renderer.end();
renderer.flush();
return violations.get();
} catch (Exception e) {
String message = e.getMessage();
if (message != null) {
LOG.severe(message);
} else {
LOG.log(Level.SEVERE, "Exception during processing", e);
}
LOG.log(Level.FINE, "Exception during processing", e);
LOG.info(PMDCommandLineInterface.buildUsageText());
return 0;
} finally {
Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
}
}
/**
* Creates a new rule context, initialized with a new, empty report.
*
* @param sourceCodeFilename the source code filename
* @param sourceCodeFile the source code file
* @return the rule context
*/
public static RuleContext newRuleContext(String sourceCodeFilename, File sourceCodeFile) {
RuleContext context = new RuleContext();
context.setSourceCodeFile(sourceCodeFile);
context.setSourceCodeFilename(sourceCodeFilename);
context.setReport(new Report());
return context;
}
/**
* A callback that would be implemented by IDEs keeping track of PMD's
* progress as it evaluates a set of files.
*
* @author Brian Remedios
*/
public interface ProgressMonitor {
/**
* A status update reporting on current progress. Implementers will
* return true if it is to continue, false otherwise.
*
* @param total total number of files to be analyzed
* @param totalDone number of files, that have been done analyzing.
* @return <code>true</code> if the execution of PMD should continue, <code>false</code> if the execution
* should be cancelled/terminated.
*/
boolean status(int total, int totalDone);
}
/**
* An entry point that would typically be used by IDEs intent on providing
* ongoing feedback and the ability to terminate it at will.
*
* @param configuration the PMD configuration to use
* @param ruleSetFactory ruleset factory
* @param files the files to analyze
* @param ctx the rule context to use for the execution
* @param monitor PMD informs about the progress through this progress monitor. It provides also
* the ability to terminate/cancel the execution.
*/
public static void processFiles(PMDConfiguration configuration, RuleSetFactory ruleSetFactory,
Collection<File> files, RuleContext ctx, ProgressMonitor monitor) {
// TODO
// call the main processFiles with just the new monitor and a single
// logRenderer
}
/**
* Run PMD on a list of files using multiple threads - if more than one is
* available
*
* @param configuration
* Configuration
* @param ruleSetFactory
* RuleSetFactory
* @param files
* List<DataSource>
* @param ctx
* RuleContext
* @param renderers
* List<Renderer>
*/
public static void processFiles(final PMDConfiguration configuration, final RuleSetFactory ruleSetFactory,
final List<DataSource> files, final RuleContext ctx, final List<Renderer> renderers) {
sortFiles(configuration, files);
/*
* Check if multithreaded support is available. ExecutorService can also
* be disabled if threadCount is not positive, e.g. using the
* "-threads 0" command line option.
*/
if (configuration.getThreads() > 0) {
new MultiThreadProcessor(configuration).processFiles(ruleSetFactory, files, ctx, renderers);
} else {
new MonoThreadProcessor(configuration).processFiles(ruleSetFactory, files, ctx, renderers);
}
if (configuration.getClassLoader() instanceof ClasspathClassLoader) {
IOUtil.tryCloseClassLoader(configuration.getClassLoader());
}
}
private static void sortFiles(final PMDConfiguration configuration, final List<DataSource> files) {
if (configuration.isStressTest()) {
// randomize processing order
Collections.shuffle(files);
} else {
final boolean useShortNames = configuration.isReportShortNames();
final String inputPaths = configuration.getInputPaths();
Collections.sort(files, new Comparator<DataSource>() {
@Override
public int compare(DataSource left, DataSource right) {
String leftString = left.getNiceFileName(useShortNames, inputPaths);
String rightString = right.getNiceFileName(useShortNames, inputPaths);
return leftString.compareTo(rightString);
}
});
}
}
/**
* Determines all the files, that should be analyzed by PMD.
* @param configuration contains either the file path or the DB URI, from where to load the files
* @param languages used to filter by file extension
* @return List<DataSource> of files
*/
public static List<DataSource> getApplicableFiles(PMDConfiguration configuration, Set<Language> languages) {
long startFiles = System.nanoTime();
List<DataSource> files = internalGetApplicableFiles(configuration, languages);
long endFiles = System.nanoTime();
Benchmarker.mark(Benchmark.CollectFiles, endFiles - startFiles, 0);
return files;
}
private static List<DataSource> internalGetApplicableFiles(PMDConfiguration configuration, Set<Language> languages) {
LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(languages);
List<DataSource> files = new ArrayList<>();
if (null != configuration.getInputPaths()) {
files.addAll(FileUtil.collectFiles(configuration.getInputPaths(), fileSelector));
}
if (null != configuration.getInputUri()) {
String uriString = configuration.getInputUri();
try {
List<DataSource> dataSources = getURIDataSources(uriString);
files.addAll(dataSources);
} catch (PMDException ex) {
LOG.log(Level.SEVERE, "Problem with Input URI", ex);
throw new RuntimeException("Problem with DBURI: " + uriString, ex);
}
}
if (null != configuration.getInputFilePath()) {
String inputFilePath = configuration.getInputFilePath();
File file = new File(inputFilePath);
try {
if (!file.exists()) {
LOG.log(Level.SEVERE, "Problem with Input File Path", inputFilePath);
throw new RuntimeException("Problem with Input File Path: " + inputFilePath);
} else {
String filePaths = FileUtils.readFileToString(new File(inputFilePath));
filePaths = StringUtils.trimToEmpty(filePaths);
filePaths = filePaths.replaceAll("\\r?\\n", ",");
filePaths = filePaths.replaceAll(",+", ",");
files.addAll(FileUtil.collectFiles(filePaths, fileSelector));
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, "Problem with Input File", ex);
throw new RuntimeException("Problem with Input File Path: " + inputFilePath, ex);
}
}
return files;
}
private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) {
Set<Language> languages = new HashSet<>();
LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer();
for (Rule rule : ruleSets.getAllRules()) {
Language language = rule.getLanguage();
if (languages.contains(language)) {
continue;
}
LanguageVersion version = discoverer.getDefaultLanguageVersion(language);
if (RuleSet.applies(rule, version)) {
languages.add(language);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Using " + language.getShortName() + " version: " + version.getShortName());
}
}
}
return languages;
}
/**
* Entry to invoke PMD as command line tool
*
* @param args command line arguments
*/
public static void main(String[] args) {
PMDCommandLineInterface.run(args);
}
/**
* Parses the command line arguments and executes PMD.
* @param args command line arguments
* @return the exit code, where <code>0</code> means successful execution, <code>1</code> means error,
* <code>4</code> means there have been violations found.
*/
public static int run(String[] args) {
int status = 0;
long start = System.nanoTime();
final PMDParameters params = PMDCommandLineInterface.extractParameters(new PMDParameters(), args, "pmd");
final PMDConfiguration configuration = PMDParameters.transformParametersIntoConfiguration(params);
final Level logLevel = params.isDebug() ? Level.FINER : Level.INFO;
final Handler logHandler = new ConsoleLogHandler();
final ScopedLogHandlersManager logHandlerManager = new ScopedLogHandlersManager(logLevel, logHandler);
final Level oldLogLevel = LOG.getLevel();
LOG.setLevel(logLevel); // Need to do this, since the static logger has
// already been initialized at this point
try {
int violations = PMD.doPMD(configuration);
if (violations > 0 && configuration.isFailOnViolation()) {
status = PMDCommandLineInterface.VIOLATIONS_FOUND;
} else {
status = 0;
}
} catch (Exception e) {
System.out.println(PMDCommandLineInterface.buildUsageText());
System.out.println();
System.err.println(e.getMessage());
status = PMDCommandLineInterface.ERROR_STATUS;
} finally {
logHandlerManager.close();
LOG.setLevel(oldLogLevel);
if (params.isBenchmark()) {
long end = System.nanoTime();
Benchmarker.mark(Benchmark.TotalPMD, end - start, 0);
TextReport report = new TextReport(); // TODO get specified
// report format from
// config
report.generate(Benchmarker.values(), System.err);
}
}
return status;
}
/**
* Determines the version from maven's generated pom.properties file.
*/
static {
String pmdVersion = null;
InputStream stream = PMD.class.getResourceAsStream("/META-INF/maven/net.sourceforge.pmd/pmd-core/pom.properties");
if (stream != null) {
try {
Properties properties = new Properties();
properties.load(stream);
pmdVersion = properties.getProperty("version");
} catch (IOException e) {
LOG.log(Level.FINE, "Couldn't determine version of PMD", e);
} finally {
IOUtils.closeQuietly(stream);
}
}
if (pmdVersion == null) {
pmdVersion = "unknown";
}
VERSION = pmdVersion;
}
}
| 1 | 11,694 | Report listeners are synchronized, even 'though the cache is thread-safe... I've not profiled it, but it may be a cause of contingency. Any better way around this? Also, do listeners **really** need to be synchronized? Can't we just make them thread-safe? | pmd-pmd | java |
@@ -3,7 +3,7 @@ module Travis
class Script
class C < Script
DEFAULTS = {
- compiler: 'gcc'
+ compiler: ''
}
def export | 1 | module Travis
module Build
class Script
class C < Script
DEFAULTS = {
compiler: 'gcc'
}
def export
super
sh.export 'CC', compiler
if data.cache?(:ccache)
sh.export 'PATH', "/usr/lib/ccache:$PATH"
end
end
def announce
super
sh.cmd "#{compiler} --version"
end
def script
sh.cmd './configure && make && make test'
end
def cache_slug
super << '--compiler-' << compiler
end
def setup_cache
if data.cache?(:ccache)
sh.fold 'cache.ccache' do
sh.echo ''
directory_cache.add('~/.ccache')
end
end
end
def use_directory_cache?
super || data.cache?(:ccache)
end
private
def compiler
config[:compiler].to_s
end
end
end
end
end
| 1 | 13,763 | I don't think this is correct. When `compiler` is not given in `.travis.yml`, the announcement will be `--version`, which results in "`command not found`" (though not critical), and the cache slug will lack this information (also not critical). | travis-ci-travis-build | rb |
@@ -33,6 +33,9 @@ const instanceMethods = {
},
async callFunction(name, args, service = undefined) {
+ if (!args) {
+ args = [];
+ }
const cleanedArgs = cleanArguments(args);
const stringifiedArgs = EJSON.stringify(cleanedArgs, { relaxed: false });
const result = await promisify(cb => this._callFunction(name, stringifiedArgs, service, cb)); | 1 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 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";
const { EJSON } = require("bson");
const {MongoDBCollection} = require("./mongo-client");
const {cleanArguments, promisify} = require("./utils");
const instanceMethods = {
linkCredentials(credentials) {
return promisify(cb => this._linkCredentials(credentials, cb));
},
logOut() {
return promisify(cb => this._logOut(cb));
},
async callFunction(name, args, service = undefined) {
const cleanedArgs = cleanArguments(args);
const stringifiedArgs = EJSON.stringify(cleanedArgs, { relaxed: false });
const result = await promisify(cb => this._callFunction(name, stringifiedArgs, service, cb));
return EJSON.parse(result);
},
async refreshCustomData() {
await promisify(cb => this._refreshCustomData(cb));
return this.customData;
},
mongoClient(serviceName) {
const user = this;
return {
get serviceName() {
return serviceName;
},
db(dbName) {
return {
get name() {
return dbName;
},
collection(collName) {
return new MongoDBCollection(
user,
serviceName,
dbName,
collName,
);
},
};
},
};
},
push(serviceName) {
const user = this;
return {
register(token) {
return promisify(cb => user._pushRegister(serviceName, token, cb));
},
deregister() {
return promisify(cb => user._pushDeregister(serviceName, cb));
},
};
},
get functions() {
return this._functionsOnService(undefined);
},
get auth() {
const user = this;
return new Proxy({}, {
get(target, name) {
if (name === "apiKeys") {
return user._authApiKeys;
}
}
});
},
get customData() {
return EJSON.parse(this._customData);
},
// Internal helpers.
_functionsOnService(service) {
const user = this;
return new Proxy({}, {
get(target, name, receiver) {
if (typeof name === "string" && name != "inspect") {
return (...args) => {
return user.callFunction(name, args, service);
};
} else {
return Reflect.get(target, name, receiver);
}
},
});
},
}
const staticMethods = {
// none
};
module.exports = {
static: staticMethods,
instance: instanceMethods,
};
| 1 | 20,461 | Why do this rather than `args = []` in the function signature? | realm-realm-js | js |
@@ -22,6 +22,8 @@ module Bolt
%w[service-url cacert token-file task-environment local-validation]
end
+ PROVIDED_FEATURES = ['puppet-agent'].freeze
+
def self.validate(options)
validation_flag = options['local-validation']
unless !!validation_flag == validation_flag | 1 | # frozen_string_literal: true
require 'base64'
require 'concurrent'
require 'json'
require 'orchestrator_client'
require 'bolt/transport/base'
require 'bolt/transport/orch/connection'
require 'bolt/result'
module Bolt
module Transport
class Orch < Base
CONF_FILE = File.expand_path('~/.puppetlabs/client-tools/orchestrator.conf')
BOLT_COMMAND_TASK = Struct.new(:name).new('bolt_shim::command').freeze
BOLT_SCRIPT_TASK = Struct.new(:name).new('bolt_shim::script').freeze
BOLT_UPLOAD_TASK = Struct.new(:name).new('bolt_shim::upload').freeze
attr_writer :plan_context
def self.options
%w[service-url cacert token-file task-environment local-validation]
end
def self.validate(options)
validation_flag = options['local-validation']
unless !!validation_flag == validation_flag
raise Bolt::ValidationError, 'local-validation option must be a Boolean true or false'
end
end
def initialize(*args)
@connections = {}
super
end
def finish_plan(result)
if result.is_a? Bolt::PlanResult
@connections.each_value do |conn|
begin
conn.finish_plan(result)
rescue StandardError => e
@logger.error("Failed to finish plan on #{conn.key}: #{e.message}")
end
end
end
end
# It's safe to create connections here for now because the
# batches/threads are per connection.
def get_connection(conn_opts)
key = Connection.get_key(conn_opts)
unless (conn = @connections[key])
conn = @connections[key] = Connection.new(conn_opts, @plan_context, logger)
end
conn
end
def process_run_results(targets, results)
targets_by_name = Hash[targets.map(&:host).zip(targets)]
results.map do |node_result|
target = targets_by_name[node_result['name']]
state = node_result['state']
result = node_result['result']
# If it's finished or already has a proper error simply pass it to the
# the result otherwise make sure an error is generated
if state == 'finished' || (result && result['_error'])
Bolt::Result.new(target, value: result)
elsif state == 'skipped'
Bolt::Result.new(
target,
value: { '_error' => {
'kind' => 'puppetlabs.tasks/skipped-node',
'msg' => "Node #{target.host} was skipped",
'details' => {}
} }
)
else
# Make a generic error with a unkown exit_code
Bolt::Result.for_task(target, result.to_json, '', 'unknown')
end
end
end
def batch_command(targets, command, options = {}, &callback)
params = {
command: command
}
results = run_task_job(targets,
BOLT_COMMAND_TASK,
params,
options,
&callback)
callback ||= proc {}
results.map! { |result| unwrap_bolt_result(result.target, result) }
results.each do |result|
callback.call(type: :node_result, result: result)
end
end
def batch_script(targets, script, arguments, options = {}, &callback)
content = File.open(script, &:read)
content = Base64.encode64(content)
params = {
content: content,
arguments: arguments
}
callback ||= proc {}
results = run_task_job(targets, BOLT_SCRIPT_TASK, params, options, &callback)
results.map! { |result| unwrap_bolt_result(result.target, result) }
results.each do |result|
callback.call(type: :node_result, result: result)
end
end
def batch_upload(targets, source, destination, options = {}, &callback)
content = File.open(source, &:read)
content = Base64.encode64(content)
mode = File.stat(source).mode
params = {
path: destination,
content: content,
mode: mode
}
callback ||= proc {}
results = run_task_job(targets, BOLT_UPLOAD_TASK, params, options, &callback)
results.map! do |result|
if result.error_hash
result
else
Bolt::Result.for_upload(result.target, source, destination)
end
end
results.each do |result|
callback&.call(type: :node_result, result: result)
end
end
def batches(targets)
targets.group_by { |target| Connection.get_key(target.options) }.values
end
def run_task_job(targets, task, arguments, options)
targets.each do |target|
yield(type: :node_start, target: target) if block_given?
end
begin
results = get_connection(targets.first.options).run_task(targets, task, arguments, options)
process_run_results(targets, results)
rescue OrchestratorClient::ApiError => e
targets.map do |target|
Bolt::Result.new(target, error: e.data)
end
rescue StandardError => e
targets.map do |target|
Bolt::Result.from_exception(target, e)
end
end
end
def batch_task(targets, task, arguments, options = {}, &callback)
callback ||= proc {}
results = run_task_job(targets, task, arguments, options, &callback)
results.each do |result|
callback.call(type: :node_result, result: result)
end
end
# run_task generates a result that makes sense for a generic task which
# needs to be unwrapped to extract stdout/stderr/exitcode.
#
def unwrap_bolt_result(target, result)
if result.error_hash
# something went wrong return the failure
return result
end
Bolt::Result.for_command(target, result.value['stdout'], result.value['stderr'], result.value['exit_code'])
end
end
end
end
| 1 | 8,609 | I think we probably *should* do validation of whether there is a suitable implementation if local-validation is true. I'm not sure how useful that actually is though | puppetlabs-bolt | rb |
@@ -1640,6 +1640,11 @@ class Dataset(object):
if self.handle is None or other.handle is None:
raise ValueError('Both source and target Datasets must be constructed before adding features')
_safe_call(_LIB.LGBM_DatasetAddFeaturesFrom(self.handle, other.handle))
+ if other.data is None:
+ self.data = None
+ if self.data is not None:
+ # FIXME: concat two dataset
+ self.data = [self.data, other.data]
return self
def _dump_text(self, filename): | 1 | # coding: utf-8
"""Wrapper for C API of LightGBM."""
from __future__ import absolute_import
import copy
import ctypes
import os
import warnings
from tempfile import NamedTemporaryFile
from collections import OrderedDict
import numpy as np
import scipy.sparse
from .compat import (PANDAS_INSTALLED, DataFrame, Series, is_dtype_sparse,
DataTable,
decode_string, string_type,
integer_types, numeric_types,
json, json_default_with_numpy,
range_, zip_)
from .libpath import find_lib_path
def _load_lib():
"""Load LightGBM library."""
lib_path = find_lib_path()
if len(lib_path) == 0:
return None
lib = ctypes.cdll.LoadLibrary(lib_path[0])
lib.LGBM_GetLastError.restype = ctypes.c_char_p
return lib
_LIB = _load_lib()
def _safe_call(ret):
"""Check the return value from C API call.
Parameters
----------
ret : int
The return value from C API calls.
"""
if ret != 0:
raise LightGBMError(decode_string(_LIB.LGBM_GetLastError()))
def is_numeric(obj):
"""Check whether object is a number or not, include numpy number, etc."""
try:
float(obj)
return True
except (TypeError, ValueError):
# TypeError: obj is not a string or a number
# ValueError: invalid literal
return False
def is_numpy_1d_array(data):
"""Check whether data is a numpy 1-D array."""
return isinstance(data, np.ndarray) and len(data.shape) == 1
def is_1d_list(data):
"""Check whether data is a 1-D list."""
return isinstance(data, list) and (not data or is_numeric(data[0]))
def list_to_1d_numpy(data, dtype=np.float32, name='list'):
"""Convert data to numpy 1-D array."""
if is_numpy_1d_array(data):
if data.dtype == dtype:
return data
else:
return data.astype(dtype=dtype, copy=False)
elif is_1d_list(data):
return np.array(data, dtype=dtype, copy=False)
elif isinstance(data, Series):
if _get_bad_pandas_dtypes([data.dtypes]):
raise ValueError('Series.dtypes must be int, float or bool')
return np.array(data, dtype=dtype, copy=False) # SparseArray should be supported as well
else:
raise TypeError("Wrong type({0}) for {1}.\n"
"It should be list, numpy 1-D array or pandas Series".format(type(data).__name__, name))
def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer')
def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer')
def cint32_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):
return np.fromiter(cptr, dtype=np.int32, count=length)
else:
raise RuntimeError('Expected int pointer')
def cint8_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer')
def c_str(string):
"""Convert a Python string to C string."""
return ctypes.c_char_p(string.encode('utf-8'))
def c_array(ctype, values):
"""Convert a Python array to C array."""
return (ctype * len(values))(*values)
def param_dict_to_str(data):
"""Convert Python dictionary to string, which is passed to C API."""
if data is None or not data:
return ""
pairs = []
for key, val in data.items():
if isinstance(val, (list, tuple, set)) or is_numpy_1d_array(val):
pairs.append(str(key) + '=' + ','.join(map(str, val)))
elif isinstance(val, string_type) or isinstance(val, numeric_types) or is_numeric(val):
pairs.append(str(key) + '=' + str(val))
elif val is not None:
raise TypeError('Unknown type of parameter:%s, got:%s'
% (key, type(val).__name__))
return ' '.join(pairs)
class _TempFile(object):
def __enter__(self):
with NamedTemporaryFile(prefix="lightgbm_tmp_", delete=True) as f:
self.name = f.name
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if os.path.isfile(self.name):
os.remove(self.name)
def readlines(self):
with open(self.name, "r+") as f:
ret = f.readlines()
return ret
def writelines(self, lines):
with open(self.name, "w+") as f:
f.writelines(lines)
class LightGBMError(Exception):
"""Error thrown by LightGBM."""
pass
class _ConfigAliases(object):
aliases = {"boosting": {"boosting",
"boosting_type",
"boost"},
"categorical_feature": {"categorical_feature",
"cat_feature",
"categorical_column",
"cat_column"},
"early_stopping_round": {"early_stopping_round",
"early_stopping_rounds",
"early_stopping",
"n_iter_no_change"},
"eval_at": {"eval_at",
"ndcg_eval_at",
"ndcg_at",
"map_eval_at",
"map_at"},
"header": {"header",
"has_header"},
"machines": {"machines",
"workers",
"nodes"},
"metric": {"metric",
"metrics",
"metric_types"},
"num_class": {"num_class",
"num_classes"},
"num_iterations": {"num_iterations",
"num_iteration",
"n_iter",
"num_tree",
"num_trees",
"num_round",
"num_rounds",
"num_boost_round",
"n_estimators"},
"objective": {"objective",
"objective_type",
"app",
"application"},
"verbosity": {"verbosity",
"verbose"}}
@classmethod
def get(cls, *args):
ret = set()
for i in args:
ret |= cls.aliases.get(i, set())
return ret
MAX_INT32 = (1 << 31) - 1
"""Macro definition of data type in C API of LightGBM"""
C_API_DTYPE_FLOAT32 = 0
C_API_DTYPE_FLOAT64 = 1
C_API_DTYPE_INT32 = 2
C_API_DTYPE_INT64 = 3
C_API_DTYPE_INT8 = 4
"""Matrix is row major in Python"""
C_API_IS_ROW_MAJOR = 1
"""Macro definition of prediction type in C API of LightGBM"""
C_API_PREDICT_NORMAL = 0
C_API_PREDICT_RAW_SCORE = 1
C_API_PREDICT_LEAF_INDEX = 2
C_API_PREDICT_CONTRIB = 3
"""Data type of data field"""
FIELD_TYPE_MAPPER = {"label": C_API_DTYPE_FLOAT32,
"weight": C_API_DTYPE_FLOAT32,
"init_score": C_API_DTYPE_FLOAT64,
"group": C_API_DTYPE_INT32,
"feature_penalty": C_API_DTYPE_FLOAT64,
"monotone_constraints": C_API_DTYPE_INT8}
def convert_from_sliced_object(data):
"""Fix the memory of multi-dimensional sliced object."""
if isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):
if not data.flags.c_contiguous:
warnings.warn("Usage of np.ndarray subset (sliced data) is not recommended "
"due to it will double the peak memory cost in LightGBM.")
return np.copy(data)
return data
def c_float_array(data):
"""Get pointer of float numpy array / list."""
if is_1d_list(data):
data = np.array(data, copy=False)
if is_numpy_1d_array(data):
data = convert_from_sliced_object(data)
assert data.flags.c_contiguous
if data.dtype == np.float32:
ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
type_data = C_API_DTYPE_FLOAT32
elif data.dtype == np.float64:
ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
type_data = C_API_DTYPE_FLOAT64
else:
raise TypeError("Expected np.float32 or np.float64, met type({})"
.format(data.dtype))
else:
raise TypeError("Unknown type({})".format(type(data).__name__))
return (ptr_data, type_data, data) # return `data` to avoid the temporary copy is freed
def c_int_array(data):
"""Get pointer of int numpy array / list."""
if is_1d_list(data):
data = np.array(data, copy=False)
if is_numpy_1d_array(data):
data = convert_from_sliced_object(data)
assert data.flags.c_contiguous
if data.dtype == np.int32:
ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_int32))
type_data = C_API_DTYPE_INT32
elif data.dtype == np.int64:
ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_int64))
type_data = C_API_DTYPE_INT64
else:
raise TypeError("Expected np.int32 or np.int64, met type({})"
.format(data.dtype))
else:
raise TypeError("Unknown type({})".format(type(data).__name__))
return (ptr_data, type_data, data) # return `data` to avoid the temporary copy is freed
def _get_bad_pandas_dtypes(dtypes):
pandas_dtype_mapper = {'int8': 'int', 'int16': 'int', 'int32': 'int',
'int64': 'int', 'uint8': 'int', 'uint16': 'int',
'uint32': 'int', 'uint64': 'int', 'bool': 'int',
'float16': 'float', 'float32': 'float', 'float64': 'float'}
bad_indices = [i for i, dtype in enumerate(dtypes) if (dtype.name not in pandas_dtype_mapper
and (not is_dtype_sparse(dtype)
or dtype.subtype.name not in pandas_dtype_mapper))]
return bad_indices
def _data_from_pandas(data, feature_name, categorical_feature, pandas_categorical):
if isinstance(data, DataFrame):
if len(data.shape) != 2 or data.shape[0] < 1:
raise ValueError('Input data must be 2 dimensional and non empty.')
if feature_name == 'auto' or feature_name is None:
data = data.rename(columns=str)
cat_cols = list(data.select_dtypes(include=['category']).columns)
cat_cols_not_ordered = [col for col in cat_cols if not data[col].cat.ordered]
if pandas_categorical is None: # train dataset
pandas_categorical = [list(data[col].cat.categories) for col in cat_cols]
else:
if len(cat_cols) != len(pandas_categorical):
raise ValueError('train and valid dataset categorical_feature do not match.')
for col, category in zip_(cat_cols, pandas_categorical):
if list(data[col].cat.categories) != list(category):
data[col] = data[col].cat.set_categories(category)
if len(cat_cols): # cat_cols is list
data = data.copy() # not alter origin DataFrame
data[cat_cols] = data[cat_cols].apply(lambda x: x.cat.codes).replace({-1: np.nan})
if categorical_feature is not None:
if feature_name is None:
feature_name = list(data.columns)
if categorical_feature == 'auto': # use cat cols from DataFrame
categorical_feature = cat_cols_not_ordered
else: # use cat cols specified by user
categorical_feature = list(categorical_feature)
if feature_name == 'auto':
feature_name = list(data.columns)
bad_indices = _get_bad_pandas_dtypes(data.dtypes)
if bad_indices:
raise ValueError("DataFrame.dtypes for data must be int, float or bool.\n"
"Did not expect the data types in the following fields: "
+ ', '.join(data.columns[bad_indices]))
data = data.values
if data.dtype != np.float32 and data.dtype != np.float64:
data = data.astype(np.float32)
else:
if feature_name == 'auto':
feature_name = None
if categorical_feature == 'auto':
categorical_feature = None
return data, feature_name, categorical_feature, pandas_categorical
def _label_from_pandas(label):
if isinstance(label, DataFrame):
if len(label.columns) > 1:
raise ValueError('DataFrame for label cannot have multiple columns')
if _get_bad_pandas_dtypes(label.dtypes):
raise ValueError('DataFrame.dtypes for label must be int, float or bool')
label = np.ravel(label.values.astype(np.float32, copy=False))
return label
def _dump_pandas_categorical(pandas_categorical, file_name=None):
pandas_str = ('\npandas_categorical:'
+ json.dumps(pandas_categorical, default=json_default_with_numpy)
+ '\n')
if file_name is not None:
with open(file_name, 'a') as f:
f.write(pandas_str)
return pandas_str
def _load_pandas_categorical(file_name=None, model_str=None):
pandas_key = 'pandas_categorical:'
offset = -len(pandas_key)
if file_name is not None:
max_offset = -os.path.getsize(file_name)
with open(file_name, 'rb') as f:
while True:
if offset < max_offset:
offset = max_offset
f.seek(offset, os.SEEK_END)
lines = f.readlines()
if len(lines) >= 2:
break
offset *= 2
last_line = decode_string(lines[-1]).strip()
if not last_line.startswith(pandas_key):
last_line = decode_string(lines[-2]).strip()
elif model_str is not None:
idx = model_str.rfind('\n', 0, offset)
last_line = model_str[idx:].strip()
if last_line.startswith(pandas_key):
return json.loads(last_line[len(pandas_key):])
else:
return None
class _InnerPredictor(object):
"""_InnerPredictor of LightGBM.
Not exposed to user.
Used only for prediction, usually used for continued training.
.. note::
Can be converted from Booster, but cannot be converted to Booster.
"""
def __init__(self, model_file=None, booster_handle=None, pred_parameter=None):
"""Initialize the _InnerPredictor.
Parameters
----------
model_file : string or None, optional (default=None)
Path to the model file.
booster_handle : object or None, optional (default=None)
Handle of Booster.
pred_parameter: dict or None, optional (default=None)
Other parameters for the prediciton.
"""
self.handle = ctypes.c_void_p()
self.__is_manage_handle = True
if model_file is not None:
"""Prediction task"""
out_num_iterations = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterCreateFromModelfile(
c_str(model_file),
ctypes.byref(out_num_iterations),
ctypes.byref(self.handle)))
out_num_class = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumClasses(
self.handle,
ctypes.byref(out_num_class)))
self.num_class = out_num_class.value
self.num_total_iteration = out_num_iterations.value
self.pandas_categorical = _load_pandas_categorical(file_name=model_file)
elif booster_handle is not None:
self.__is_manage_handle = False
self.handle = booster_handle
out_num_class = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumClasses(
self.handle,
ctypes.byref(out_num_class)))
self.num_class = out_num_class.value
out_num_iterations = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetCurrentIteration(
self.handle,
ctypes.byref(out_num_iterations)))
self.num_total_iteration = out_num_iterations.value
self.pandas_categorical = None
else:
raise TypeError('Need model_file or booster_handle to create a predictor')
pred_parameter = {} if pred_parameter is None else pred_parameter
self.pred_parameter = param_dict_to_str(pred_parameter)
def __del__(self):
try:
if self.__is_manage_handle:
_safe_call(_LIB.LGBM_BoosterFree(self.handle))
except AttributeError:
pass
def __getstate__(self):
this = self.__dict__.copy()
this.pop('handle', None)
return this
def predict(self, data, num_iteration=-1,
raw_score=False, pred_leaf=False, pred_contrib=False, data_has_header=False,
is_reshape=True):
"""Predict logic.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Data source for prediction.
When data type is string, it represents the path of txt file.
num_iteration : int, optional (default=-1)
Iteration used for prediction.
raw_score : bool, optional (default=False)
Whether to predict raw scores.
pred_leaf : bool, optional (default=False)
Whether to predict leaf index.
pred_contrib : bool, optional (default=False)
Whether to predict feature contributions.
data_has_header : bool, optional (default=False)
Whether data has header.
Used only for txt data.
is_reshape : bool, optional (default=True)
Whether to reshape to (nrow, ncol).
Returns
-------
result : numpy array
Prediction result.
"""
if isinstance(data, Dataset):
raise TypeError("Cannot use Dataset instance for prediction, please use raw data instead")
data = _data_from_pandas(data, None, None, self.pandas_categorical)[0]
predict_type = C_API_PREDICT_NORMAL
if raw_score:
predict_type = C_API_PREDICT_RAW_SCORE
if pred_leaf:
predict_type = C_API_PREDICT_LEAF_INDEX
if pred_contrib:
predict_type = C_API_PREDICT_CONTRIB
int_data_has_header = 1 if data_has_header else 0
if num_iteration > self.num_total_iteration:
num_iteration = self.num_total_iteration
if isinstance(data, string_type):
with _TempFile() as f:
_safe_call(_LIB.LGBM_BoosterPredictForFile(
self.handle,
c_str(data),
ctypes.c_int(int_data_has_header),
ctypes.c_int(predict_type),
ctypes.c_int(num_iteration),
c_str(self.pred_parameter),
c_str(f.name)))
lines = f.readlines()
nrow = len(lines)
preds = [float(token) for line in lines for token in line.split('\t')]
preds = np.array(preds, dtype=np.float64, copy=False)
elif isinstance(data, scipy.sparse.csr_matrix):
preds, nrow = self.__pred_for_csr(data, num_iteration, predict_type)
elif isinstance(data, scipy.sparse.csc_matrix):
preds, nrow = self.__pred_for_csc(data, num_iteration, predict_type)
elif isinstance(data, np.ndarray):
preds, nrow = self.__pred_for_np2d(data, num_iteration, predict_type)
elif isinstance(data, list):
try:
data = np.array(data)
except BaseException:
raise ValueError('Cannot convert data list to numpy array.')
preds, nrow = self.__pred_for_np2d(data, num_iteration, predict_type)
elif isinstance(data, DataTable):
preds, nrow = self.__pred_for_np2d(data.to_numpy(), num_iteration, predict_type)
else:
try:
warnings.warn('Converting data to scipy sparse matrix.')
csr = scipy.sparse.csr_matrix(data)
except BaseException:
raise TypeError('Cannot predict data for type {}'.format(type(data).__name__))
preds, nrow = self.__pred_for_csr(csr, num_iteration, predict_type)
if pred_leaf:
preds = preds.astype(np.int32)
if is_reshape and preds.size != nrow:
if preds.size % nrow == 0:
preds = preds.reshape(nrow, -1)
else:
raise ValueError('Length of predict result (%d) cannot be divide nrow (%d)'
% (preds.size, nrow))
return preds
def __get_num_preds(self, num_iteration, nrow, predict_type):
"""Get size of prediction result."""
if nrow > MAX_INT32:
raise LightGBMError('LightGBM cannot perform prediction for data'
'with number of rows greater than MAX_INT32 (%d).\n'
'You can split your data into chunks'
'and then concatenate predictions for them' % MAX_INT32)
n_preds = ctypes.c_int64(0)
_safe_call(_LIB.LGBM_BoosterCalcNumPredict(
self.handle,
ctypes.c_int(nrow),
ctypes.c_int(predict_type),
ctypes.c_int(num_iteration),
ctypes.byref(n_preds)))
return n_preds.value
def __pred_for_np2d(self, mat, num_iteration, predict_type):
"""Predict for a 2-D numpy matrix."""
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray or list must be 2 dimensional')
def inner_predict(mat, num_iteration, predict_type, preds=None):
if mat.dtype == np.float32 or mat.dtype == np.float64:
data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False)
else: # change non-float data to float data, need to copy
data = np.array(mat.reshape(mat.size), dtype=np.float32)
ptr_data, type_ptr_data, _ = c_float_array(data)
n_preds = self.__get_num_preds(num_iteration, mat.shape[0], predict_type)
if preds is None:
preds = np.zeros(n_preds, dtype=np.float64)
elif len(preds.shape) != 1 or len(preds) != n_preds:
raise ValueError("Wrong length of pre-allocated predict array")
out_num_preds = ctypes.c_int64(0)
_safe_call(_LIB.LGBM_BoosterPredictForMat(
self.handle,
ptr_data,
ctypes.c_int(type_ptr_data),
ctypes.c_int(mat.shape[0]),
ctypes.c_int(mat.shape[1]),
ctypes.c_int(C_API_IS_ROW_MAJOR),
ctypes.c_int(predict_type),
ctypes.c_int(num_iteration),
c_str(self.pred_parameter),
ctypes.byref(out_num_preds),
preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if n_preds != out_num_preds.value:
raise ValueError("Wrong length for predict results")
return preds, mat.shape[0]
nrow = mat.shape[0]
if nrow > MAX_INT32:
sections = np.arange(start=MAX_INT32, stop=nrow, step=MAX_INT32)
# __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal
n_preds = [self.__get_num_preds(num_iteration, i, predict_type) for i in np.diff([0] + list(sections) + [nrow])]
n_preds_sections = np.array([0] + n_preds, dtype=np.intp).cumsum()
preds = np.zeros(sum(n_preds), dtype=np.float64)
for chunk, (start_idx_pred, end_idx_pred) in zip_(np.array_split(mat, sections),
zip_(n_preds_sections, n_preds_sections[1:])):
# avoid memory consumption by arrays concatenation operations
inner_predict(chunk, num_iteration, predict_type, preds[start_idx_pred:end_idx_pred])
return preds, nrow
else:
return inner_predict(mat, num_iteration, predict_type)
def __pred_for_csr(self, csr, num_iteration, predict_type):
"""Predict for a CSR data."""
def inner_predict(csr, num_iteration, predict_type, preds=None):
nrow = len(csr.indptr) - 1
n_preds = self.__get_num_preds(num_iteration, nrow, predict_type)
if preds is None:
preds = np.zeros(n_preds, dtype=np.float64)
elif len(preds.shape) != 1 or len(preds) != n_preds:
raise ValueError("Wrong length of pre-allocated predict array")
out_num_preds = ctypes.c_int64(0)
ptr_indptr, type_ptr_indptr, __ = c_int_array(csr.indptr)
ptr_data, type_ptr_data, _ = c_float_array(csr.data)
assert csr.shape[1] <= MAX_INT32
csr.indices = csr.indices.astype(np.int32, copy=False)
_safe_call(_LIB.LGBM_BoosterPredictForCSR(
self.handle,
ptr_indptr,
ctypes.c_int32(type_ptr_indptr),
csr.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
ptr_data,
ctypes.c_int(type_ptr_data),
ctypes.c_int64(len(csr.indptr)),
ctypes.c_int64(len(csr.data)),
ctypes.c_int64(csr.shape[1]),
ctypes.c_int(predict_type),
ctypes.c_int(num_iteration),
c_str(self.pred_parameter),
ctypes.byref(out_num_preds),
preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if n_preds != out_num_preds.value:
raise ValueError("Wrong length for predict results")
return preds, nrow
nrow = len(csr.indptr) - 1
if nrow > MAX_INT32:
sections = [0] + list(np.arange(start=MAX_INT32, stop=nrow, step=MAX_INT32)) + [nrow]
# __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal
n_preds = [self.__get_num_preds(num_iteration, i, predict_type) for i in np.diff(sections)]
n_preds_sections = np.array([0] + n_preds, dtype=np.intp).cumsum()
preds = np.zeros(sum(n_preds), dtype=np.float64)
for (start_idx, end_idx), (start_idx_pred, end_idx_pred) in zip_(zip_(sections, sections[1:]),
zip_(n_preds_sections, n_preds_sections[1:])):
# avoid memory consumption by arrays concatenation operations
inner_predict(csr[start_idx:end_idx], num_iteration, predict_type, preds[start_idx_pred:end_idx_pred])
return preds, nrow
else:
return inner_predict(csr, num_iteration, predict_type)
def __pred_for_csc(self, csc, num_iteration, predict_type):
"""Predict for a CSC data."""
nrow = csc.shape[0]
if nrow > MAX_INT32:
return self.__pred_for_csr(csc.tocsr(), num_iteration, predict_type)
n_preds = self.__get_num_preds(num_iteration, nrow, predict_type)
preds = np.zeros(n_preds, dtype=np.float64)
out_num_preds = ctypes.c_int64(0)
ptr_indptr, type_ptr_indptr, __ = c_int_array(csc.indptr)
ptr_data, type_ptr_data, _ = c_float_array(csc.data)
assert csc.shape[0] <= MAX_INT32
csc.indices = csc.indices.astype(np.int32, copy=False)
_safe_call(_LIB.LGBM_BoosterPredictForCSC(
self.handle,
ptr_indptr,
ctypes.c_int32(type_ptr_indptr),
csc.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
ptr_data,
ctypes.c_int(type_ptr_data),
ctypes.c_int64(len(csc.indptr)),
ctypes.c_int64(len(csc.data)),
ctypes.c_int64(csc.shape[0]),
ctypes.c_int(predict_type),
ctypes.c_int(num_iteration),
c_str(self.pred_parameter),
ctypes.byref(out_num_preds),
preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if n_preds != out_num_preds.value:
raise ValueError("Wrong length for predict results")
return preds, nrow
class Dataset(object):
"""Dataset in LightGBM."""
def __init__(self, data, label=None, reference=None,
weight=None, group=None, init_score=None, silent=False,
feature_name='auto', categorical_feature='auto', params=None,
free_raw_data=True):
"""Initialize Dataset.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse or list of numpy arrays
Data source of Dataset.
If string, it represents the path to txt file.
label : list, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None)
Label of the data.
reference : Dataset or None, optional (default=None)
If this is Dataset for validation, training data should be used as reference.
weight : list, numpy 1-D array, pandas Series or None, optional (default=None)
Weight for each instance.
group : list, numpy 1-D array, pandas Series or None, optional (default=None)
Group/query size for Dataset.
init_score : list, numpy 1-D array, pandas Series or None, optional (default=None)
Init score for Dataset.
silent : bool, optional (default=False)
Whether to print messages during construction.
feature_name : list of strings or 'auto', optional (default="auto")
Feature names.
If 'auto' and data is pandas DataFrame, data columns names are used.
categorical_feature : list of strings or int, or 'auto', optional (default="auto")
Categorical features.
If list of int, interpreted as indices.
If list of strings, interpreted as feature names (need to specify ``feature_name`` as well).
If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.
All values in categorical features should be less than int32 max value (2147483647).
Large values could be memory consuming. Consider using consecutive integers starting from zero.
All negative values in categorical features will be treated as missing values.
The output cannot be monotonically constrained with respect to a categorical feature.
params : dict or None, optional (default=None)
Other parameters for Dataset.
free_raw_data : bool, optional (default=True)
If True, raw data is freed after constructing inner Dataset.
"""
self.handle = None
self.data = data
self.label = label
self.reference = reference
self.weight = weight
self.group = group
self.init_score = init_score
self.silent = silent
self.feature_name = feature_name
self.categorical_feature = categorical_feature
self.params = copy.deepcopy(params)
self.free_raw_data = free_raw_data
self.used_indices = None
self.need_slice = True
self._predictor = None
self.pandas_categorical = None
self.params_back_up = None
self.feature_penalty = None
self.monotone_constraints = None
self.version = 0
def __del__(self):
try:
self._free_handle()
except AttributeError:
pass
def _free_handle(self):
if self.handle is not None:
_safe_call(_LIB.LGBM_DatasetFree(self.handle))
self.handle = None
self.need_slice = True
if self.used_indices is not None:
self.data = None
return self
def _set_init_score_by_predictor(self, predictor, data, used_indices=None):
data_has_header = False
if isinstance(data, string_type):
# check data has header or not
data_has_header = any(self.params.get(alias, False) for alias in _ConfigAliases.get("header"))
init_score = predictor.predict(data,
raw_score=True,
data_has_header=data_has_header,
is_reshape=False)
num_data = self.num_data()
if used_indices is not None:
assert not self.need_slice
if isinstance(data, string_type):
sub_init_score = np.zeros(num_data * predictor.num_class, dtype=np.float32)
assert num_data == len(used_indices)
for i in range_(len(used_indices)):
for j in range_(predictor.num_class):
sub_init_score[i * predictor.num_class + j] = init_score[used_indices[i] * predictor.num_class + j]
init_score = sub_init_score
if predictor.num_class > 1:
# need to regroup init_score
new_init_score = np.zeros(init_score.size, dtype=np.float32)
for i in range_(num_data):
for j in range_(predictor.num_class):
new_init_score[j * num_data + i] = init_score[i * predictor.num_class + j]
init_score = new_init_score
self.set_init_score(init_score)
def _lazy_init(self, data, label=None, reference=None,
weight=None, group=None, init_score=None, predictor=None,
silent=False, feature_name='auto',
categorical_feature='auto', params=None):
if data is None:
self.handle = None
return self
if reference is not None:
self.pandas_categorical = reference.pandas_categorical
categorical_feature = reference.categorical_feature
data, feature_name, categorical_feature, self.pandas_categorical = _data_from_pandas(data,
feature_name,
categorical_feature,
self.pandas_categorical)
label = _label_from_pandas(label)
# process for args
params = {} if params is None else params
args_names = (getattr(self.__class__, '_lazy_init')
.__code__
.co_varnames[:getattr(self.__class__, '_lazy_init').__code__.co_argcount])
for key, _ in params.items():
if key in args_names:
warnings.warn('{0} keyword has been found in `params` and will be ignored.\n'
'Please use {0} argument of the Dataset constructor to pass this parameter.'
.format(key))
# user can set verbose with params, it has higher priority
if not any(verbose_alias in params for verbose_alias in _ConfigAliases.get("verbosity")) and silent:
params["verbose"] = -1
# get categorical features
if categorical_feature is not None:
categorical_indices = set()
feature_dict = {}
if feature_name is not None:
feature_dict = {name: i for i, name in enumerate(feature_name)}
for name in categorical_feature:
if isinstance(name, string_type) and name in feature_dict:
categorical_indices.add(feature_dict[name])
elif isinstance(name, integer_types):
categorical_indices.add(name)
else:
raise TypeError("Wrong type({}) or unknown name({}) in categorical_feature"
.format(type(name).__name__, name))
if categorical_indices:
for cat_alias in _ConfigAliases.get("categorical_feature"):
if cat_alias in params:
warnings.warn('{} in param dict is overridden.'.format(cat_alias))
params.pop(cat_alias, None)
params['categorical_column'] = sorted(categorical_indices)
params_str = param_dict_to_str(params)
# process for reference dataset
ref_dataset = None
if isinstance(reference, Dataset):
ref_dataset = reference.construct().handle
elif reference is not None:
raise TypeError('Reference dataset should be None or dataset instance')
# start construct data
if isinstance(data, string_type):
self.handle = ctypes.c_void_p()
_safe_call(_LIB.LGBM_DatasetCreateFromFile(
c_str(data),
c_str(params_str),
ref_dataset,
ctypes.byref(self.handle)))
elif isinstance(data, scipy.sparse.csr_matrix):
self.__init_from_csr(data, params_str, ref_dataset)
elif isinstance(data, scipy.sparse.csc_matrix):
self.__init_from_csc(data, params_str, ref_dataset)
elif isinstance(data, np.ndarray):
self.__init_from_np2d(data, params_str, ref_dataset)
elif isinstance(data, list) and len(data) > 0 and all(isinstance(x, np.ndarray) for x in data):
self.__init_from_list_np2d(data, params_str, ref_dataset)
elif isinstance(data, DataTable):
self.__init_from_np2d(data.to_numpy(), params_str, ref_dataset)
else:
try:
csr = scipy.sparse.csr_matrix(data)
self.__init_from_csr(csr, params_str, ref_dataset)
except BaseException:
raise TypeError('Cannot initialize Dataset from {}'.format(type(data).__name__))
if label is not None:
self.set_label(label)
if self.get_label() is None:
raise ValueError("Label should not be None")
if weight is not None:
self.set_weight(weight)
if group is not None:
self.set_group(group)
if isinstance(predictor, _InnerPredictor):
if self._predictor is None and init_score is not None:
warnings.warn("The init_score will be overridden by the prediction of init_model.")
self._set_init_score_by_predictor(predictor, data)
elif init_score is not None:
self.set_init_score(init_score)
elif predictor is not None:
raise TypeError('Wrong predictor type {}'.format(type(predictor).__name__))
# set feature names
return self.set_feature_name(feature_name)
def __init_from_np2d(self, mat, params_str, ref_dataset):
"""Initialize data from a 2-D numpy matrix."""
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray must be 2 dimensional')
self.handle = ctypes.c_void_p()
if mat.dtype == np.float32 or mat.dtype == np.float64:
data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False)
else: # change non-float data to float data, need to copy
data = np.array(mat.reshape(mat.size), dtype=np.float32)
ptr_data, type_ptr_data, _ = c_float_array(data)
_safe_call(_LIB.LGBM_DatasetCreateFromMat(
ptr_data,
ctypes.c_int(type_ptr_data),
ctypes.c_int(mat.shape[0]),
ctypes.c_int(mat.shape[1]),
ctypes.c_int(C_API_IS_ROW_MAJOR),
c_str(params_str),
ref_dataset,
ctypes.byref(self.handle)))
return self
def __init_from_list_np2d(self, mats, params_str, ref_dataset):
"""Initialize data from a list of 2-D numpy matrices."""
ncol = mats[0].shape[1]
nrow = np.zeros((len(mats),), np.int32)
if mats[0].dtype == np.float64:
ptr_data = (ctypes.POINTER(ctypes.c_double) * len(mats))()
else:
ptr_data = (ctypes.POINTER(ctypes.c_float) * len(mats))()
holders = []
type_ptr_data = None
for i, mat in enumerate(mats):
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray must be 2 dimensional')
if mat.shape[1] != ncol:
raise ValueError('Input arrays must have same number of columns')
nrow[i] = mat.shape[0]
if mat.dtype == np.float32 or mat.dtype == np.float64:
mats[i] = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False)
else: # change non-float data to float data, need to copy
mats[i] = np.array(mat.reshape(mat.size), dtype=np.float32)
chunk_ptr_data, chunk_type_ptr_data, holder = c_float_array(mats[i])
if type_ptr_data is not None and chunk_type_ptr_data != type_ptr_data:
raise ValueError('Input chunks must have same type')
ptr_data[i] = chunk_ptr_data
type_ptr_data = chunk_type_ptr_data
holders.append(holder)
self.handle = ctypes.c_void_p()
_safe_call(_LIB.LGBM_DatasetCreateFromMats(
ctypes.c_int(len(mats)),
ctypes.cast(ptr_data, ctypes.POINTER(ctypes.POINTER(ctypes.c_double))),
ctypes.c_int(type_ptr_data),
nrow.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
ctypes.c_int(ncol),
ctypes.c_int(C_API_IS_ROW_MAJOR),
c_str(params_str),
ref_dataset,
ctypes.byref(self.handle)))
return self
def __init_from_csr(self, csr, params_str, ref_dataset):
"""Initialize data from a CSR matrix."""
if len(csr.indices) != len(csr.data):
raise ValueError('Length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data)))
self.handle = ctypes.c_void_p()
ptr_indptr, type_ptr_indptr, __ = c_int_array(csr.indptr)
ptr_data, type_ptr_data, _ = c_float_array(csr.data)
assert csr.shape[1] <= MAX_INT32
csr.indices = csr.indices.astype(np.int32, copy=False)
_safe_call(_LIB.LGBM_DatasetCreateFromCSR(
ptr_indptr,
ctypes.c_int(type_ptr_indptr),
csr.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
ptr_data,
ctypes.c_int(type_ptr_data),
ctypes.c_int64(len(csr.indptr)),
ctypes.c_int64(len(csr.data)),
ctypes.c_int64(csr.shape[1]),
c_str(params_str),
ref_dataset,
ctypes.byref(self.handle)))
return self
def __init_from_csc(self, csc, params_str, ref_dataset):
"""Initialize data from a CSC matrix."""
if len(csc.indices) != len(csc.data):
raise ValueError('Length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data)))
self.handle = ctypes.c_void_p()
ptr_indptr, type_ptr_indptr, __ = c_int_array(csc.indptr)
ptr_data, type_ptr_data, _ = c_float_array(csc.data)
assert csc.shape[0] <= MAX_INT32
csc.indices = csc.indices.astype(np.int32, copy=False)
_safe_call(_LIB.LGBM_DatasetCreateFromCSC(
ptr_indptr,
ctypes.c_int(type_ptr_indptr),
csc.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
ptr_data,
ctypes.c_int(type_ptr_data),
ctypes.c_int64(len(csc.indptr)),
ctypes.c_int64(len(csc.data)),
ctypes.c_int64(csc.shape[0]),
c_str(params_str),
ref_dataset,
ctypes.byref(self.handle)))
return self
def construct(self):
"""Lazy init.
Returns
-------
self : Dataset
Constructed Dataset object.
"""
if self.handle is None:
if self.reference is not None:
if self.used_indices is None:
# create valid
self._lazy_init(self.data, label=self.label, reference=self.reference,
weight=self.weight, group=self.group,
init_score=self.init_score, predictor=self._predictor,
silent=self.silent, feature_name=self.feature_name, params=self.params)
else:
# construct subset
used_indices = list_to_1d_numpy(self.used_indices, np.int32, name='used_indices')
assert used_indices.flags.c_contiguous
if self.reference.group is not None:
group_info = np.array(self.reference.group).astype(np.int32, copy=False)
_, self.group = np.unique(np.repeat(range_(len(group_info)), repeats=group_info)[self.used_indices],
return_counts=True)
self.handle = ctypes.c_void_p()
params_str = param_dict_to_str(self.params)
_safe_call(_LIB.LGBM_DatasetGetSubset(
self.reference.construct().handle,
used_indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
ctypes.c_int(used_indices.shape[0]),
c_str(params_str),
ctypes.byref(self.handle)))
if not self.free_raw_data:
self.get_data()
if self.group is not None:
self.set_group(self.group)
if self.get_label() is None:
raise ValueError("Label should not be None.")
if isinstance(self._predictor, _InnerPredictor) and self._predictor is not self.reference._predictor:
self.get_data()
self._set_init_score_by_predictor(self._predictor, self.data, used_indices)
else:
# create train
self._lazy_init(self.data, label=self.label,
weight=self.weight, group=self.group,
init_score=self.init_score, predictor=self._predictor,
silent=self.silent, feature_name=self.feature_name,
categorical_feature=self.categorical_feature, params=self.params)
if self.free_raw_data:
self.data = None
return self
def create_valid(self, data, label=None, weight=None, group=None,
init_score=None, silent=False, params=None):
"""Create validation data align with current Dataset.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse or list of numpy arrays
Data source of Dataset.
If string, it represents the path to txt file.
label : list, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None)
Label of the data.
weight : list, numpy 1-D array, pandas Series or None, optional (default=None)
Weight for each instance.
group : list, numpy 1-D array, pandas Series or None, optional (default=None)
Group/query size for Dataset.
init_score : list, numpy 1-D array, pandas Series or None, optional (default=None)
Init score for Dataset.
silent : bool, optional (default=False)
Whether to print messages during construction.
params : dict or None, optional (default=None)
Other parameters for validation Dataset.
Returns
-------
valid : Dataset
Validation Dataset with reference to self.
"""
ret = Dataset(data, label=label, reference=self,
weight=weight, group=group, init_score=init_score,
silent=silent, params=params, free_raw_data=self.free_raw_data)
ret._predictor = self._predictor
ret.pandas_categorical = self.pandas_categorical
return ret
def subset(self, used_indices, params=None):
"""Get subset of current Dataset.
Parameters
----------
used_indices : list of int
Indices used to create the subset.
params : dict or None, optional (default=None)
These parameters will be passed to Dataset constructor.
Returns
-------
subset : Dataset
Subset of the current Dataset.
"""
if params is None:
params = self.params
ret = Dataset(None, reference=self, feature_name=self.feature_name,
categorical_feature=self.categorical_feature, params=params,
free_raw_data=self.free_raw_data)
ret._predictor = self._predictor
ret.pandas_categorical = self.pandas_categorical
ret.used_indices = sorted(used_indices)
return ret
def save_binary(self, filename):
"""Save Dataset to a binary file.
.. note::
Please note that `init_score` is not saved in binary file.
If you need it, please set it again after loading Dataset.
Parameters
----------
filename : string
Name of the output file.
Returns
-------
self : Dataset
Returns self.
"""
_safe_call(_LIB.LGBM_DatasetSaveBinary(
self.construct().handle,
c_str(filename)))
return self
def _update_params(self, params):
if self.handle is not None and params is not None:
_safe_call(_LIB.LGBM_DatasetUpdateParam(self.handle, c_str(param_dict_to_str(params))))
if not self.params:
self.params = copy.deepcopy(params)
else:
self.params_back_up = copy.deepcopy(self.params)
self.params.update(params)
return self
def _reverse_update_params(self):
self.params = copy.deepcopy(self.params_back_up)
self.params_back_up = None
if self.handle is not None and self.params is not None:
_safe_call(_LIB.LGBM_DatasetUpdateParam(self.handle, c_str(param_dict_to_str(self.params))))
return self
def set_field(self, field_name, data):
"""Set property into the Dataset.
Parameters
----------
field_name : string
The field name of the information.
data : list, numpy 1-D array, pandas Series or None
The array of data to be set.
Returns
-------
self : Dataset
Dataset with set property.
"""
if self.handle is None:
raise Exception("Cannot set %s before construct dataset" % field_name)
if data is None:
# set to None
_safe_call(_LIB.LGBM_DatasetSetField(
self.handle,
c_str(field_name),
None,
ctypes.c_int(0),
ctypes.c_int(FIELD_TYPE_MAPPER[field_name])))
return self
dtype = np.float32
if field_name == 'group':
dtype = np.int32
elif field_name == 'init_score':
dtype = np.float64
data = list_to_1d_numpy(data, dtype, name=field_name)
if data.dtype == np.float32 or data.dtype == np.float64:
ptr_data, type_data, _ = c_float_array(data)
elif data.dtype == np.int32:
ptr_data, type_data, _ = c_int_array(data)
else:
raise TypeError("Expected np.float32/64 or np.int32, met type({})".format(data.dtype))
if type_data != FIELD_TYPE_MAPPER[field_name]:
raise TypeError("Input type error for set_field")
_safe_call(_LIB.LGBM_DatasetSetField(
self.handle,
c_str(field_name),
ptr_data,
ctypes.c_int(len(data)),
ctypes.c_int(type_data)))
self.version += 1
return self
def get_field(self, field_name):
"""Get property from the Dataset.
Parameters
----------
field_name : string
The field name of the information.
Returns
-------
info : numpy array
A numpy array with information from the Dataset.
"""
if self.handle is None:
raise Exception("Cannot get %s before construct Dataset" % field_name)
tmp_out_len = ctypes.c_int()
out_type = ctypes.c_int()
ret = ctypes.POINTER(ctypes.c_void_p)()
_safe_call(_LIB.LGBM_DatasetGetField(
self.handle,
c_str(field_name),
ctypes.byref(tmp_out_len),
ctypes.byref(ret),
ctypes.byref(out_type)))
if out_type.value != FIELD_TYPE_MAPPER[field_name]:
raise TypeError("Return type error for get_field")
if tmp_out_len.value == 0:
return None
if out_type.value == C_API_DTYPE_INT32:
return cint32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int32)), tmp_out_len.value)
elif out_type.value == C_API_DTYPE_FLOAT32:
return cfloat32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_float)), tmp_out_len.value)
elif out_type.value == C_API_DTYPE_FLOAT64:
return cfloat64_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_double)), tmp_out_len.value)
elif out_type.value == C_API_DTYPE_INT8:
return cint8_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int8)), tmp_out_len.value)
else:
raise TypeError("Unknown type")
def set_categorical_feature(self, categorical_feature):
"""Set categorical features.
Parameters
----------
categorical_feature : list of int or strings
Names or indices of categorical features.
Returns
-------
self : Dataset
Dataset with set categorical features.
"""
if self.categorical_feature == categorical_feature:
return self
if self.data is not None:
if self.categorical_feature is None:
self.categorical_feature = categorical_feature
return self._free_handle()
elif categorical_feature == 'auto':
warnings.warn('Using categorical_feature in Dataset.')
return self
else:
warnings.warn('categorical_feature in Dataset is overridden.\n'
'New categorical_feature is {}'.format(sorted(list(categorical_feature))))
self.categorical_feature = categorical_feature
return self._free_handle()
else:
raise LightGBMError("Cannot set categorical feature after freed raw data, "
"set free_raw_data=False when construct Dataset to avoid this.")
def _set_predictor(self, predictor):
"""Set predictor for continued training.
It is not recommended for user to call this function.
Please use init_model argument in engine.train() or engine.cv() instead.
"""
if predictor is self._predictor:
return self
if self.data is not None or (self.used_indices is not None
and self.reference is not None
and self.reference.data is not None):
self._predictor = predictor
return self._free_handle()
else:
raise LightGBMError("Cannot set predictor after freed raw data, "
"set free_raw_data=False when construct Dataset to avoid this.")
def set_reference(self, reference):
"""Set reference Dataset.
Parameters
----------
reference : Dataset
Reference that is used as a template to construct the current Dataset.
Returns
-------
self : Dataset
Dataset with set reference.
"""
self.set_categorical_feature(reference.categorical_feature) \
.set_feature_name(reference.feature_name) \
._set_predictor(reference._predictor)
# we're done if self and reference share a common upstrem reference
if self.get_ref_chain().intersection(reference.get_ref_chain()):
return self
if self.data is not None:
self.reference = reference
return self._free_handle()
else:
raise LightGBMError("Cannot set reference after freed raw data, "
"set free_raw_data=False when construct Dataset to avoid this.")
def set_feature_name(self, feature_name):
"""Set feature name.
Parameters
----------
feature_name : list of strings
Feature names.
Returns
-------
self : Dataset
Dataset with set feature name.
"""
if feature_name != 'auto':
self.feature_name = feature_name
if self.handle is not None and feature_name is not None and feature_name != 'auto':
if len(feature_name) != self.num_feature():
raise ValueError("Length of feature_name({}) and num_feature({}) don't match"
.format(len(feature_name), self.num_feature()))
c_feature_name = [c_str(name) for name in feature_name]
_safe_call(_LIB.LGBM_DatasetSetFeatureNames(
self.handle,
c_array(ctypes.c_char_p, c_feature_name),
ctypes.c_int(len(feature_name))))
return self
def set_label(self, label):
"""Set label of Dataset.
Parameters
----------
label : list, numpy 1-D array, pandas Series / one-column DataFrame or None
The label information to be set into Dataset.
Returns
-------
self : Dataset
Dataset with set label.
"""
self.label = label
if self.handle is not None:
label = list_to_1d_numpy(_label_from_pandas(label), name='label')
self.set_field('label', label)
self.label = self.get_field('label') # original values can be modified at cpp side
return self
def set_weight(self, weight):
"""Set weight of each instance.
Parameters
----------
weight : list, numpy 1-D array, pandas Series or None
Weight to be set for each data point.
Returns
-------
self : Dataset
Dataset with set weight.
"""
if weight is not None and np.all(weight == 1):
weight = None
self.weight = weight
if self.handle is not None and weight is not None:
weight = list_to_1d_numpy(weight, name='weight')
self.set_field('weight', weight)
self.weight = self.get_field('weight') # original values can be modified at cpp side
return self
def set_init_score(self, init_score):
"""Set init score of Booster to start from.
Parameters
----------
init_score : list, numpy 1-D array, pandas Series or None
Init score for Booster.
Returns
-------
self : Dataset
Dataset with set init score.
"""
self.init_score = init_score
if self.handle is not None and init_score is not None:
init_score = list_to_1d_numpy(init_score, np.float64, name='init_score')
self.set_field('init_score', init_score)
self.init_score = self.get_field('init_score') # original values can be modified at cpp side
return self
def set_group(self, group):
"""Set group size of Dataset (used for ranking).
Parameters
----------
group : list, numpy 1-D array, pandas Series or None
Group size of each group.
Returns
-------
self : Dataset
Dataset with set group.
"""
self.group = group
if self.handle is not None and group is not None:
group = list_to_1d_numpy(group, np.int32, name='group')
self.set_field('group', group)
return self
def get_label(self):
"""Get the label of the Dataset.
Returns
-------
label : numpy array or None
The label information from the Dataset.
"""
if self.label is None:
self.label = self.get_field('label')
return self.label
def get_weight(self):
"""Get the weight of the Dataset.
Returns
-------
weight : numpy array or None
Weight for each data point from the Dataset.
"""
if self.weight is None:
self.weight = self.get_field('weight')
return self.weight
def get_feature_penalty(self):
"""Get the feature penalty of the Dataset.
Returns
-------
feature_penalty : numpy array or None
Feature penalty for each feature in the Dataset.
"""
if self.feature_penalty is None:
self.feature_penalty = self.get_field('feature_penalty')
return self.feature_penalty
def get_monotone_constraints(self):
"""Get the monotone constraints of the Dataset.
Returns
-------
monotone_constraints : numpy array or None
Monotone constraints: -1, 0 or 1, for each feature in the Dataset.
"""
if self.monotone_constraints is None:
self.monotone_constraints = self.get_field('monotone_constraints')
return self.monotone_constraints
def get_init_score(self):
"""Get the initial score of the Dataset.
Returns
-------
init_score : numpy array or None
Init score of Booster.
"""
if self.init_score is None:
self.init_score = self.get_field('init_score')
return self.init_score
def get_data(self):
"""Get the raw data of the Dataset.
Returns
-------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list of numpy arrays or None
Raw data used in the Dataset construction.
"""
if self.handle is None:
raise Exception("Cannot get data before construct Dataset")
if self.need_slice and self.used_indices is not None and self.reference is not None:
self.data = self.reference.data
if self.data is not None:
if isinstance(self.data, np.ndarray) or scipy.sparse.issparse(self.data):
self.data = self.data[self.used_indices, :]
elif isinstance(self.data, DataFrame):
self.data = self.data.iloc[self.used_indices].copy()
elif isinstance(self.data, DataTable):
self.data = self.data[self.used_indices, :]
else:
warnings.warn("Cannot subset {} type of raw data.\n"
"Returning original raw data".format(type(self.data).__name__))
self.need_slice = False
if self.data is None:
raise LightGBMError("Cannot call `get_data` after freed raw data, "
"set free_raw_data=False when construct Dataset to avoid this.")
return self.data
def get_group(self):
"""Get the group of the Dataset.
Returns
-------
group : numpy array or None
Group size of each group.
"""
if self.group is None:
self.group = self.get_field('group')
if self.group is not None:
# group data from LightGBM is boundaries data, need to convert to group size
self.group = np.diff(self.group)
return self.group
def num_data(self):
"""Get the number of rows in the Dataset.
Returns
-------
number_of_rows : int
The number of rows in the Dataset.
"""
if self.handle is not None:
ret = ctypes.c_int()
_safe_call(_LIB.LGBM_DatasetGetNumData(self.handle,
ctypes.byref(ret)))
return ret.value
else:
raise LightGBMError("Cannot get num_data before construct dataset")
def num_feature(self):
"""Get the number of columns (features) in the Dataset.
Returns
-------
number_of_columns : int
The number of columns (features) in the Dataset.
"""
if self.handle is not None:
ret = ctypes.c_int()
_safe_call(_LIB.LGBM_DatasetGetNumFeature(self.handle,
ctypes.byref(ret)))
return ret.value
else:
raise LightGBMError("Cannot get num_feature before construct dataset")
def get_ref_chain(self, ref_limit=100):
"""Get a chain of Dataset objects.
Starts with r, then goes to r.reference (if exists),
then to r.reference.reference, etc.
until we hit ``ref_limit`` or a reference loop.
Parameters
----------
ref_limit : int, optional (default=100)
The limit number of references.
Returns
-------
ref_chain : set of Dataset
Chain of references of the Datasets.
"""
head = self
ref_chain = set()
while len(ref_chain) < ref_limit:
if isinstance(head, Dataset):
ref_chain.add(head)
if (head.reference is not None) and (head.reference not in ref_chain):
head = head.reference
else:
break
else:
break
return ref_chain
def add_features_from(self, other):
"""Add features from other Dataset to the current Dataset.
Both Datasets must be constructed before calling this method.
Parameters
----------
other : Dataset
The Dataset to take features from.
Returns
-------
self : Dataset
Dataset with the new features added.
"""
if self.handle is None or other.handle is None:
raise ValueError('Both source and target Datasets must be constructed before adding features')
_safe_call(_LIB.LGBM_DatasetAddFeaturesFrom(self.handle, other.handle))
return self
def _dump_text(self, filename):
"""Save Dataset to a text file.
This format cannot be loaded back in by LightGBM, but is useful for debugging purposes.
Parameters
----------
filename : string
Name of the output file.
Returns
-------
self : Dataset
Returns self.
"""
_safe_call(_LIB.LGBM_DatasetDumpText(
self.construct().handle,
c_str(filename)))
return self
class Booster(object):
"""Booster in LightGBM."""
def __init__(self, params=None, train_set=None, model_file=None, model_str=None, silent=False):
"""Initialize the Booster.
Parameters
----------
params : dict or None, optional (default=None)
Parameters for Booster.
train_set : Dataset or None, optional (default=None)
Training dataset.
model_file : string or None, optional (default=None)
Path to the model file.
model_str : string or None, optional (default=None)
Model will be loaded from this string.
silent : bool, optional (default=False)
Whether to print messages during construction.
"""
self.handle = None
self.network = False
self.__need_reload_eval_info = True
self._train_data_name = "training"
self.__attr = {}
self.__set_objective_to_none = False
self.best_iteration = -1
self.best_score = {}
params = {} if params is None else copy.deepcopy(params)
# user can set verbose with params, it has higher priority
if not any(verbose_alias in params for verbose_alias in _ConfigAliases.get("verbosity")) and silent:
params["verbose"] = -1
if train_set is not None:
# Training task
if not isinstance(train_set, Dataset):
raise TypeError('Training data should be Dataset instance, met {}'
.format(type(train_set).__name__))
params_str = param_dict_to_str(params)
# set network if necessary
for alias in _ConfigAliases.get("machines"):
if alias in params:
machines = params[alias]
if isinstance(machines, string_type):
num_machines = len(machines.split(','))
elif isinstance(machines, (list, set)):
num_machines = len(machines)
machines = ','.join(machines)
else:
raise ValueError("Invalid machines in params.")
self.set_network(machines,
local_listen_port=params.get("local_listen_port", 12400),
listen_time_out=params.get("listen_time_out", 120),
num_machines=params.get("num_machines", num_machines))
break
# construct booster object
self.handle = ctypes.c_void_p()
_safe_call(_LIB.LGBM_BoosterCreate(
train_set.construct().handle,
c_str(params_str),
ctypes.byref(self.handle)))
# save reference to data
self.train_set = train_set
self.valid_sets = []
self.name_valid_sets = []
self.__num_dataset = 1
self.__init_predictor = train_set._predictor
if self.__init_predictor is not None:
_safe_call(_LIB.LGBM_BoosterMerge(
self.handle,
self.__init_predictor.handle))
out_num_class = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumClasses(
self.handle,
ctypes.byref(out_num_class)))
self.__num_class = out_num_class.value
# buffer for inner predict
self.__inner_predict_buffer = [None]
self.__is_predicted_cur_iter = [False]
self.__get_eval_info()
self.pandas_categorical = train_set.pandas_categorical
self.train_set_version = train_set.version
elif model_file is not None:
# Prediction task
out_num_iterations = ctypes.c_int(0)
self.handle = ctypes.c_void_p()
_safe_call(_LIB.LGBM_BoosterCreateFromModelfile(
c_str(model_file),
ctypes.byref(out_num_iterations),
ctypes.byref(self.handle)))
out_num_class = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumClasses(
self.handle,
ctypes.byref(out_num_class)))
self.__num_class = out_num_class.value
self.pandas_categorical = _load_pandas_categorical(file_name=model_file)
elif model_str is not None:
self.model_from_string(model_str, not silent)
else:
raise TypeError('Need at least one training dataset or model file or model string '
'to create Booster instance')
self.params = params
def __del__(self):
try:
if self.network:
self.free_network()
except AttributeError:
pass
try:
if self.handle is not None:
_safe_call(_LIB.LGBM_BoosterFree(self.handle))
except AttributeError:
pass
def __copy__(self):
return self.__deepcopy__(None)
def __deepcopy__(self, _):
model_str = self.model_to_string(num_iteration=-1)
booster = Booster(model_str=model_str)
return booster
def __getstate__(self):
this = self.__dict__.copy()
handle = this['handle']
this.pop('train_set', None)
this.pop('valid_sets', None)
if handle is not None:
this["handle"] = self.model_to_string(num_iteration=-1)
return this
def __setstate__(self, state):
model_str = state.get('handle', None)
if model_str is not None:
handle = ctypes.c_void_p()
out_num_iterations = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterLoadModelFromString(
c_str(model_str),
ctypes.byref(out_num_iterations),
ctypes.byref(handle)))
state['handle'] = handle
self.__dict__.update(state)
def free_dataset(self):
"""Free Booster's Datasets.
Returns
-------
self : Booster
Booster without Datasets.
"""
self.__dict__.pop('train_set', None)
self.__dict__.pop('valid_sets', None)
self.__num_dataset = 0
return self
def _free_buffer(self):
self.__inner_predict_buffer = []
self.__is_predicted_cur_iter = []
return self
def set_network(self, machines, local_listen_port=12400,
listen_time_out=120, num_machines=1):
"""Set the network configuration.
Parameters
----------
machines : list, set or string
Names of machines.
local_listen_port : int, optional (default=12400)
TCP listen port for local machines.
listen_time_out : int, optional (default=120)
Socket time-out in minutes.
num_machines : int, optional (default=1)
The number of machines for parallel learning application.
Returns
-------
self : Booster
Booster with set network.
"""
_safe_call(_LIB.LGBM_NetworkInit(c_str(machines),
ctypes.c_int(local_listen_port),
ctypes.c_int(listen_time_out),
ctypes.c_int(num_machines)))
self.network = True
return self
def free_network(self):
"""Free Booster's network.
Returns
-------
self : Booster
Booster with freed network.
"""
_safe_call(_LIB.LGBM_NetworkFree())
self.network = False
return self
def trees_to_dataframe(self):
"""Parse the fitted model and return in an easy-to-read pandas DataFrame.
Returns
-------
result : pandas DataFrame
Returns a pandas DataFrame of the parsed model.
"""
if not PANDAS_INSTALLED:
raise LightGBMError('This method cannot be run without pandas installed')
if self.num_trees() == 0:
raise LightGBMError('There are no trees in this Booster and thus nothing to parse')
def _is_split_node(tree):
return 'split_index' in tree.keys()
def create_node_record(tree, node_depth=1, tree_index=None,
feature_names=None, parent_node=None):
def _get_node_index(tree, tree_index):
tree_num = str(tree_index) + '-' if tree_index is not None else ''
is_split = _is_split_node(tree)
node_type = 'S' if is_split else 'L'
# if a single node tree it won't have `leaf_index` so return 0
node_num = str(tree.get('split_index' if is_split else 'leaf_index', 0))
return tree_num + node_type + node_num
def _get_split_feature(tree, feature_names):
if _is_split_node(tree):
if feature_names is not None:
feature_name = feature_names[tree['split_feature']]
else:
feature_name = tree['split_feature']
else:
feature_name = None
return feature_name
def _is_single_node_tree(tree):
return set(tree.keys()) == {'leaf_value'}
# Create the node record, and populate universal data members
node = OrderedDict()
node['tree_index'] = tree_index
node['node_depth'] = node_depth
node['node_index'] = _get_node_index(tree, tree_index)
node['left_child'] = None
node['right_child'] = None
node['parent_index'] = parent_node
node['split_feature'] = _get_split_feature(tree, feature_names)
node['split_gain'] = None
node['threshold'] = None
node['decision_type'] = None
node['missing_direction'] = None
node['missing_type'] = None
node['value'] = None
node['weight'] = None
node['count'] = None
# Update values to reflect node type (leaf or split)
if _is_split_node(tree):
node['left_child'] = _get_node_index(tree['left_child'], tree_index)
node['right_child'] = _get_node_index(tree['right_child'], tree_index)
node['split_gain'] = tree['split_gain']
node['threshold'] = tree['threshold']
node['decision_type'] = tree['decision_type']
node['missing_direction'] = 'left' if tree['default_left'] else 'right'
node['missing_type'] = tree['missing_type']
node['value'] = tree['internal_value']
node['weight'] = tree['internal_weight']
node['count'] = tree['internal_count']
else:
node['value'] = tree['leaf_value']
if not _is_single_node_tree(tree):
node['weight'] = tree['leaf_weight']
node['count'] = tree['leaf_count']
return node
def tree_dict_to_node_list(tree, node_depth=1, tree_index=None,
feature_names=None, parent_node=None):
node = create_node_record(tree,
node_depth=node_depth,
tree_index=tree_index,
feature_names=feature_names,
parent_node=parent_node)
res = [node]
if _is_split_node(tree):
# traverse the next level of the tree
children = ['left_child', 'right_child']
for child in children:
subtree_list = tree_dict_to_node_list(
tree[child],
node_depth=node_depth + 1,
tree_index=tree_index,
feature_names=feature_names,
parent_node=node['node_index'])
# In tree format, "subtree_list" is a list of node records (dicts),
# and we add node to the list.
res.extend(subtree_list)
return res
model_dict = self.dump_model()
feature_names = model_dict['feature_names']
model_list = []
for tree in model_dict['tree_info']:
model_list.extend(tree_dict_to_node_list(tree['tree_structure'],
tree_index=tree['tree_index'],
feature_names=feature_names))
return DataFrame(model_list, columns=model_list[0].keys())
def set_train_data_name(self, name):
"""Set the name to the training Dataset.
Parameters
----------
name : string
Name for the training Dataset.
Returns
-------
self : Booster
Booster with set training Dataset name.
"""
self._train_data_name = name
return self
def add_valid(self, data, name):
"""Add validation data.
Parameters
----------
data : Dataset
Validation data.
name : string
Name of validation data.
Returns
-------
self : Booster
Booster with set validation data.
"""
if not isinstance(data, Dataset):
raise TypeError('Validation data should be Dataset instance, met {}'
.format(type(data).__name__))
if data._predictor is not self.__init_predictor:
raise LightGBMError("Add validation data failed, "
"you should use same predictor for these data")
_safe_call(_LIB.LGBM_BoosterAddValidData(
self.handle,
data.construct().handle))
self.valid_sets.append(data)
self.name_valid_sets.append(name)
self.__num_dataset += 1
self.__inner_predict_buffer.append(None)
self.__is_predicted_cur_iter.append(False)
return self
def reset_parameter(self, params):
"""Reset parameters of Booster.
Parameters
----------
params : dict
New parameters for Booster.
Returns
-------
self : Booster
Booster with new parameters.
"""
params_str = param_dict_to_str(params)
if params_str:
_safe_call(_LIB.LGBM_BoosterResetParameter(
self.handle,
c_str(params_str)))
self.params.update(params)
return self
def update(self, train_set=None, fobj=None):
"""Update Booster for one iteration.
Parameters
----------
train_set : Dataset or None, optional (default=None)
Training data.
If None, last training data is used.
fobj : callable or None, optional (default=None)
Customized objective function.
Should accept two parameters: preds, train_data,
and return (grad, hess).
preds : list or numpy 1-D array
The predicted values.
train_data : Dataset
The training dataset.
grad : list or numpy 1-D array
The value of the first order derivative (gradient) for each sample point.
hess : list or numpy 1-D array
The value of the second order derivative (Hessian) for each sample point.
For multi-class task, the preds is group by class_id first, then group by row_id.
If you want to get i-th row preds in j-th class, the access way is score[j * num_data + i]
and you should group grad and hess in this way as well.
Returns
-------
is_finished : bool
Whether the update was successfully finished.
"""
# need reset training data
if train_set is None and self.train_set_version != self.train_set.version:
train_set = self.train_set
is_the_same_train_set = False
else:
is_the_same_train_set = train_set is self.train_set and self.train_set_version == train_set.version
if train_set is not None and not is_the_same_train_set:
if not isinstance(train_set, Dataset):
raise TypeError('Training data should be Dataset instance, met {}'
.format(type(train_set).__name__))
if train_set._predictor is not self.__init_predictor:
raise LightGBMError("Replace training data failed, "
"you should use same predictor for these data")
self.train_set = train_set
_safe_call(_LIB.LGBM_BoosterResetTrainingData(
self.handle,
self.train_set.construct().handle))
self.__inner_predict_buffer[0] = None
self.train_set_version = self.train_set.version
is_finished = ctypes.c_int(0)
if fobj is None:
if self.__set_objective_to_none:
raise LightGBMError('Cannot update due to null objective function.')
_safe_call(_LIB.LGBM_BoosterUpdateOneIter(
self.handle,
ctypes.byref(is_finished)))
self.__is_predicted_cur_iter = [False for _ in range_(self.__num_dataset)]
return is_finished.value == 1
else:
if not self.__set_objective_to_none:
self.reset_parameter({"objective": "none"}).__set_objective_to_none = True
grad, hess = fobj(self.__inner_predict(0), self.train_set)
return self.__boost(grad, hess)
def __boost(self, grad, hess):
"""Boost Booster for one iteration with customized gradient statistics.
.. note::
For multi-class task, the score is group by class_id first, then group by row_id.
If you want to get i-th row score in j-th class, the access way is score[j * num_data + i]
and you should group grad and hess in this way as well.
Parameters
----------
grad : list or numpy 1-D array
The first order derivative (gradient).
hess : list or numpy 1-D array
The second order derivative (Hessian).
Returns
-------
is_finished : bool
Whether the boost was successfully finished.
"""
grad = list_to_1d_numpy(grad, name='gradient')
hess = list_to_1d_numpy(hess, name='hessian')
assert grad.flags.c_contiguous
assert hess.flags.c_contiguous
if len(grad) != len(hess):
raise ValueError("Lengths of gradient({}) and hessian({}) don't match"
.format(len(grad), len(hess)))
is_finished = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterUpdateOneIterCustom(
self.handle,
grad.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
hess.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
ctypes.byref(is_finished)))
self.__is_predicted_cur_iter = [False for _ in range_(self.__num_dataset)]
return is_finished.value == 1
def rollback_one_iter(self):
"""Rollback one iteration.
Returns
-------
self : Booster
Booster with rolled back one iteration.
"""
_safe_call(_LIB.LGBM_BoosterRollbackOneIter(
self.handle))
self.__is_predicted_cur_iter = [False for _ in range_(self.__num_dataset)]
return self
def current_iteration(self):
"""Get the index of the current iteration.
Returns
-------
cur_iter : int
The index of the current iteration.
"""
out_cur_iter = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetCurrentIteration(
self.handle,
ctypes.byref(out_cur_iter)))
return out_cur_iter.value
def num_model_per_iteration(self):
"""Get number of models per iteration.
Returns
-------
model_per_iter : int
The number of models per iteration.
"""
model_per_iter = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterNumModelPerIteration(
self.handle,
ctypes.byref(model_per_iter)))
return model_per_iter.value
def num_trees(self):
"""Get number of weak sub-models.
Returns
-------
num_trees : int
The number of weak sub-models.
"""
num_trees = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterNumberOfTotalModel(
self.handle,
ctypes.byref(num_trees)))
return num_trees.value
def eval(self, data, name, feval=None):
"""Evaluate for data.
Parameters
----------
data : Dataset
Data for the evaluating.
name : string
Name of the data.
feval : callable or None, optional (default=None)
Customized evaluation function.
Should accept two parameters: preds, eval_data,
and return (eval_name, eval_result, is_higher_better) or list of such tuples.
preds : list or numpy 1-D array
The predicted values.
eval_data : Dataset
The evaluation dataset.
eval_name : string
The name of evaluation function (without whitespaces).
eval_result : float
The eval result.
is_higher_better : bool
Is eval result higher better, e.g. AUC is ``is_higher_better``.
For multi-class task, the preds is group by class_id first, then group by row_id.
If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].
Returns
-------
result : list
List with evaluation results.
"""
if not isinstance(data, Dataset):
raise TypeError("Can only eval for Dataset instance")
data_idx = -1
if data is self.train_set:
data_idx = 0
else:
for i in range_(len(self.valid_sets)):
if data is self.valid_sets[i]:
data_idx = i + 1
break
# need to push new valid data
if data_idx == -1:
self.add_valid(data, name)
data_idx = self.__num_dataset - 1
return self.__inner_eval(name, data_idx, feval)
def eval_train(self, feval=None):
"""Evaluate for training data.
Parameters
----------
feval : callable or None, optional (default=None)
Customized evaluation function.
Should accept two parameters: preds, train_data,
and return (eval_name, eval_result, is_higher_better) or list of such tuples.
preds : list or numpy 1-D array
The predicted values.
train_data : Dataset
The training dataset.
eval_name : string
The name of evaluation function (without whitespaces).
eval_result : float
The eval result.
is_higher_better : bool
Is eval result higher better, e.g. AUC is ``is_higher_better``.
For multi-class task, the preds is group by class_id first, then group by row_id.
If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].
Returns
-------
result : list
List with evaluation results.
"""
return self.__inner_eval(self._train_data_name, 0, feval)
def eval_valid(self, feval=None):
"""Evaluate for validation data.
Parameters
----------
feval : callable or None, optional (default=None)
Customized evaluation function.
Should accept two parameters: preds, valid_data,
and return (eval_name, eval_result, is_higher_better) or list of such tuples.
preds : list or numpy 1-D array
The predicted values.
valid_data : Dataset
The validation dataset.
eval_name : string
The name of evaluation function (without whitespaces).
eval_result : float
The eval result.
is_higher_better : bool
Is eval result higher better, e.g. AUC is ``is_higher_better``.
For multi-class task, the preds is group by class_id first, then group by row_id.
If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].
Returns
-------
result : list
List with evaluation results.
"""
return [item for i in range_(1, self.__num_dataset)
for item in self.__inner_eval(self.name_valid_sets[i - 1], i, feval)]
def save_model(self, filename, num_iteration=None, start_iteration=0):
"""Save Booster to file.
Parameters
----------
filename : string
Filename to save Booster.
num_iteration : int or None, optional (default=None)
Index of the iteration that should be saved.
If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.
If <= 0, all iterations are saved.
start_iteration : int, optional (default=0)
Start index of the iteration that should be saved.
Returns
-------
self : Booster
Returns self.
"""
if num_iteration is None:
num_iteration = self.best_iteration
_safe_call(_LIB.LGBM_BoosterSaveModel(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
c_str(filename)))
_dump_pandas_categorical(self.pandas_categorical, filename)
return self
def shuffle_models(self, start_iteration=0, end_iteration=-1):
"""Shuffle models.
Parameters
----------
start_iteration : int, optional (default=0)
The first iteration that will be shuffled.
end_iteration : int, optional (default=-1)
The last iteration that will be shuffled.
If <= 0, means the last available iteration.
Returns
-------
self : Booster
Booster with shuffled models.
"""
_safe_call(_LIB.LGBM_BoosterShuffleModels(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(end_iteration)))
return self
def model_from_string(self, model_str, verbose=True):
"""Load Booster from a string.
Parameters
----------
model_str : string
Model will be loaded from this string.
verbose : bool, optional (default=True)
Whether to print messages while loading model.
Returns
-------
self : Booster
Loaded Booster object.
"""
if self.handle is not None:
_safe_call(_LIB.LGBM_BoosterFree(self.handle))
self._free_buffer()
self.handle = ctypes.c_void_p()
out_num_iterations = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterLoadModelFromString(
c_str(model_str),
ctypes.byref(out_num_iterations),
ctypes.byref(self.handle)))
out_num_class = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumClasses(
self.handle,
ctypes.byref(out_num_class)))
if verbose:
print('Finished loading model, total used %d iterations' % int(out_num_iterations.value))
self.__num_class = out_num_class.value
self.pandas_categorical = _load_pandas_categorical(model_str=model_str)
return self
def model_to_string(self, num_iteration=None, start_iteration=0):
"""Save Booster to string.
Parameters
----------
num_iteration : int or None, optional (default=None)
Index of the iteration that should be saved.
If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.
If <= 0, all iterations are saved.
start_iteration : int, optional (default=0)
Start index of the iteration that should be saved.
Returns
-------
str_repr : string
String representation of Booster.
"""
if num_iteration is None:
num_iteration = self.best_iteration
buffer_len = 1 << 20
tmp_out_len = ctypes.c_int64(0)
string_buffer = ctypes.create_string_buffer(buffer_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterSaveModelToString(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(buffer_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
actual_len = tmp_out_len.value
# if buffer length is not long enough, re-allocate a buffer
if actual_len > buffer_len:
string_buffer = ctypes.create_string_buffer(actual_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterSaveModelToString(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(actual_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
ret = string_buffer.value.decode()
ret += _dump_pandas_categorical(self.pandas_categorical)
return ret
def dump_model(self, num_iteration=None, start_iteration=0):
"""Dump Booster to JSON format.
Parameters
----------
num_iteration : int or None, optional (default=None)
Index of the iteration that should be dumped.
If None, if the best iteration exists, it is dumped; otherwise, all iterations are dumped.
If <= 0, all iterations are dumped.
start_iteration : int, optional (default=0)
Start index of the iteration that should be dumped.
Returns
-------
json_repr : dict
JSON format of Booster.
"""
if num_iteration is None:
num_iteration = self.best_iteration
buffer_len = 1 << 20
tmp_out_len = ctypes.c_int64(0)
string_buffer = ctypes.create_string_buffer(buffer_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterDumpModel(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(buffer_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
actual_len = tmp_out_len.value
# if buffer length is not long enough, reallocate a buffer
if actual_len > buffer_len:
string_buffer = ctypes.create_string_buffer(actual_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterDumpModel(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(actual_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
ret = json.loads(string_buffer.value.decode())
ret['pandas_categorical'] = json.loads(json.dumps(self.pandas_categorical,
default=json_default_with_numpy))
return ret
def predict(self, data, num_iteration=None,
raw_score=False, pred_leaf=False, pred_contrib=False,
data_has_header=False, is_reshape=True, **kwargs):
"""Make a prediction.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Data source for prediction.
If string, it represents the path to txt file.
num_iteration : int or None, optional (default=None)
Limit number of iterations in the prediction.
If None, if the best iteration exists, it is used; otherwise, all iterations are used.
If <= 0, all iterations are used (no limits).
raw_score : bool, optional (default=False)
Whether to predict raw scores.
pred_leaf : bool, optional (default=False)
Whether to predict leaf index.
pred_contrib : bool, optional (default=False)
Whether to predict feature contributions.
.. note::
If you want to get more explanations for your model's predictions using SHAP values,
like SHAP interaction values,
you can install the shap package (https://github.com/slundberg/shap).
Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra
column, where the last column is the expected value.
data_has_header : bool, optional (default=False)
Whether the data has header.
Used only if data is string.
is_reshape : bool, optional (default=True)
If True, result is reshaped to [nrow, ncol].
**kwargs
Other parameters for the prediction.
Returns
-------
result : numpy array
Prediction result.
"""
predictor = self._to_predictor(copy.deepcopy(kwargs))
if num_iteration is None:
num_iteration = self.best_iteration
return predictor.predict(data, num_iteration,
raw_score, pred_leaf, pred_contrib,
data_has_header, is_reshape)
def refit(self, data, label, decay_rate=0.9, **kwargs):
"""Refit the existing Booster by new data.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Data source for refit.
If string, it represents the path to txt file.
label : list, numpy 1-D array or pandas Series / one-column DataFrame
Label for refit.
decay_rate : float, optional (default=0.9)
Decay rate of refit,
will use ``leaf_output = decay_rate * old_leaf_output + (1.0 - decay_rate) * new_leaf_output`` to refit trees.
**kwargs
Other parameters for refit.
These parameters will be passed to ``predict`` method.
Returns
-------
result : Booster
Refitted Booster.
"""
if self.__set_objective_to_none:
raise LightGBMError('Cannot refit due to null objective function.')
predictor = self._to_predictor(copy.deepcopy(kwargs))
leaf_preds = predictor.predict(data, -1, pred_leaf=True)
nrow, ncol = leaf_preds.shape
train_set = Dataset(data, label, silent=True)
new_params = copy.deepcopy(self.params)
new_params['refit_decay_rate'] = decay_rate
new_booster = Booster(new_params, train_set, silent=True)
# Copy models
_safe_call(_LIB.LGBM_BoosterMerge(
new_booster.handle,
predictor.handle))
leaf_preds = leaf_preds.reshape(-1)
ptr_data, type_ptr_data, _ = c_int_array(leaf_preds)
_safe_call(_LIB.LGBM_BoosterRefit(
new_booster.handle,
ptr_data,
ctypes.c_int(nrow),
ctypes.c_int(ncol)))
new_booster.network = self.network
new_booster.__attr = self.__attr.copy()
return new_booster
def get_leaf_output(self, tree_id, leaf_id):
"""Get the output of a leaf.
Parameters
----------
tree_id : int
The index of the tree.
leaf_id : int
The index of the leaf in the tree.
Returns
-------
result : float
The output of the leaf.
"""
ret = ctypes.c_double(0)
_safe_call(_LIB.LGBM_BoosterGetLeafValue(
self.handle,
ctypes.c_int(tree_id),
ctypes.c_int(leaf_id),
ctypes.byref(ret)))
return ret.value
def _to_predictor(self, pred_parameter=None):
"""Convert to predictor."""
predictor = _InnerPredictor(booster_handle=self.handle, pred_parameter=pred_parameter)
predictor.pandas_categorical = self.pandas_categorical
return predictor
def num_feature(self):
"""Get number of features.
Returns
-------
num_feature : int
The number of features.
"""
out_num_feature = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumFeature(
self.handle,
ctypes.byref(out_num_feature)))
return out_num_feature.value
def feature_name(self):
"""Get names of features.
Returns
-------
result : list
List with names of features.
"""
num_feature = self.num_feature()
# Get name of features
tmp_out_len = ctypes.c_int(0)
string_buffers = [ctypes.create_string_buffer(255) for i in range_(num_feature)]
ptr_string_buffers = (ctypes.c_char_p * num_feature)(*map(ctypes.addressof, string_buffers))
_safe_call(_LIB.LGBM_BoosterGetFeatureNames(
self.handle,
ctypes.byref(tmp_out_len),
ptr_string_buffers))
if num_feature != tmp_out_len.value:
raise ValueError("Length of feature names doesn't equal with num_feature")
return [string_buffers[i].value.decode() for i in range_(num_feature)]
def feature_importance(self, importance_type='split', iteration=None):
"""Get feature importances.
Parameters
----------
importance_type : string, optional (default="split")
How the importance is calculated.
If "split", result contains numbers of times the feature is used in a model.
If "gain", result contains total gains of splits which use the feature.
iteration : int or None, optional (default=None)
Limit number of iterations in the feature importance calculation.
If None, if the best iteration exists, it is used; otherwise, all trees are used.
If <= 0, all trees are used (no limits).
Returns
-------
result : numpy array
Array with feature importances.
"""
if iteration is None:
iteration = self.best_iteration
if importance_type == "split":
importance_type_int = 0
elif importance_type == "gain":
importance_type_int = 1
else:
importance_type_int = -1
result = np.zeros(self.num_feature(), dtype=np.float64)
_safe_call(_LIB.LGBM_BoosterFeatureImportance(
self.handle,
ctypes.c_int(iteration),
ctypes.c_int(importance_type_int),
result.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if importance_type_int == 0:
return result.astype(np.int32)
else:
return result
def get_split_value_histogram(self, feature, bins=None, xgboost_style=False):
"""Get split value histogram for the specified feature.
Parameters
----------
feature : int or string
The feature name or index the histogram is calculated for.
If int, interpreted as index.
If string, interpreted as name.
.. warning::
Categorical features are not supported.
bins : int, string or None, optional (default=None)
The maximum number of bins.
If None, or int and > number of unique split values and ``xgboost_style=True``,
the number of bins equals number of unique split values.
If string, it should be one from the list of the supported values by ``numpy.histogram()`` function.
xgboost_style : bool, optional (default=False)
Whether the returned result should be in the same form as it is in XGBoost.
If False, the returned value is tuple of 2 numpy arrays as it is in ``numpy.histogram()`` function.
If True, the returned value is matrix, in which the first column is the right edges of non-empty bins
and the second one is the histogram values.
Returns
-------
result_tuple : tuple of 2 numpy arrays
If ``xgboost_style=False``, the values of the histogram of used splitting values for the specified feature
and the bin edges.
result_array_like : numpy array or pandas DataFrame (if pandas is installed)
If ``xgboost_style=True``, the histogram of used splitting values for the specified feature.
"""
def add(root):
"""Recursively add thresholds."""
if 'split_index' in root: # non-leaf
if feature_names is not None and isinstance(feature, string_type):
split_feature = feature_names[root['split_feature']]
else:
split_feature = root['split_feature']
if split_feature == feature:
if isinstance(root['threshold'], string_type):
raise LightGBMError('Cannot compute split value histogram for the categorical feature')
else:
values.append(root['threshold'])
add(root['left_child'])
add(root['right_child'])
model = self.dump_model()
feature_names = model.get('feature_names')
tree_infos = model['tree_info']
values = []
for tree_info in tree_infos:
add(tree_info['tree_structure'])
if bins is None or isinstance(bins, integer_types) and xgboost_style:
n_unique = len(np.unique(values))
bins = max(min(n_unique, bins) if bins is not None else n_unique, 1)
hist, bin_edges = np.histogram(values, bins=bins)
if xgboost_style:
ret = np.column_stack((bin_edges[1:], hist))
ret = ret[ret[:, 1] > 0]
if PANDAS_INSTALLED:
return DataFrame(ret, columns=['SplitValue', 'Count'])
else:
return ret
else:
return hist, bin_edges
def __inner_eval(self, data_name, data_idx, feval=None):
"""Evaluate training or validation data."""
if data_idx >= self.__num_dataset:
raise ValueError("Data_idx should be smaller than number of dataset")
self.__get_eval_info()
ret = []
if self.__num_inner_eval > 0:
result = np.zeros(self.__num_inner_eval, dtype=np.float64)
tmp_out_len = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetEval(
self.handle,
ctypes.c_int(data_idx),
ctypes.byref(tmp_out_len),
result.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if tmp_out_len.value != self.__num_inner_eval:
raise ValueError("Wrong length of eval results")
for i in range_(self.__num_inner_eval):
ret.append((data_name, self.__name_inner_eval[i],
result[i], self.__higher_better_inner_eval[i]))
if feval is not None:
if data_idx == 0:
cur_data = self.train_set
else:
cur_data = self.valid_sets[data_idx - 1]
feval_ret = feval(self.__inner_predict(data_idx), cur_data)
if isinstance(feval_ret, list):
for eval_name, val, is_higher_better in feval_ret:
ret.append((data_name, eval_name, val, is_higher_better))
else:
eval_name, val, is_higher_better = feval_ret
ret.append((data_name, eval_name, val, is_higher_better))
return ret
def __inner_predict(self, data_idx):
"""Predict for training and validation dataset."""
if data_idx >= self.__num_dataset:
raise ValueError("Data_idx should be smaller than number of dataset")
if self.__inner_predict_buffer[data_idx] is None:
if data_idx == 0:
n_preds = self.train_set.num_data() * self.__num_class
else:
n_preds = self.valid_sets[data_idx - 1].num_data() * self.__num_class
self.__inner_predict_buffer[data_idx] = np.zeros(n_preds, dtype=np.float64)
# avoid to predict many time in one iteration
if not self.__is_predicted_cur_iter[data_idx]:
tmp_out_len = ctypes.c_int64(0)
data_ptr = self.__inner_predict_buffer[data_idx].ctypes.data_as(ctypes.POINTER(ctypes.c_double))
_safe_call(_LIB.LGBM_BoosterGetPredict(
self.handle,
ctypes.c_int(data_idx),
ctypes.byref(tmp_out_len),
data_ptr))
if tmp_out_len.value != len(self.__inner_predict_buffer[data_idx]):
raise ValueError("Wrong length of predict results for data %d" % (data_idx))
self.__is_predicted_cur_iter[data_idx] = True
return self.__inner_predict_buffer[data_idx]
def __get_eval_info(self):
"""Get inner evaluation count and names."""
if self.__need_reload_eval_info:
self.__need_reload_eval_info = False
out_num_eval = ctypes.c_int(0)
# Get num of inner evals
_safe_call(_LIB.LGBM_BoosterGetEvalCounts(
self.handle,
ctypes.byref(out_num_eval)))
self.__num_inner_eval = out_num_eval.value
if self.__num_inner_eval > 0:
# Get name of evals
tmp_out_len = ctypes.c_int(0)
string_buffers = [ctypes.create_string_buffer(255) for i in range_(self.__num_inner_eval)]
ptr_string_buffers = (ctypes.c_char_p * self.__num_inner_eval)(*map(ctypes.addressof, string_buffers))
_safe_call(_LIB.LGBM_BoosterGetEvalNames(
self.handle,
ctypes.byref(tmp_out_len),
ptr_string_buffers))
if self.__num_inner_eval != tmp_out_len.value:
raise ValueError("Length of eval names doesn't equal with num_evals")
self.__name_inner_eval = \
[string_buffers[i].value.decode() for i in range_(self.__num_inner_eval)]
self.__higher_better_inner_eval = \
[name.startswith(('auc', 'ndcg@', 'map@')) for name in self.__name_inner_eval]
def attr(self, key):
"""Get attribute string from the Booster.
Parameters
----------
key : string
The name of the attribute.
Returns
-------
value : string or None
The attribute value.
Returns None if attribute does not exist.
"""
return self.__attr.get(key, None)
def set_attr(self, **kwargs):
"""Set attributes to the Booster.
Parameters
----------
**kwargs
The attributes to set.
Setting a value to None deletes an attribute.
Returns
-------
self : Booster
Booster with set attributes.
"""
for key, value in kwargs.items():
if value is not None:
if not isinstance(value, string_type):
raise ValueError("Only string values are accepted")
self.__attr[key] = value
else:
self.__attr.pop(key, None)
return self
| 1 | 22,146 | @StrikerRUS here may need to concat two data by col. | microsoft-LightGBM | cpp |
@@ -64,7 +64,7 @@ public interface NodeWithJavadoc<N extends Node> {
*/
@SuppressWarnings("unchecked")
default N setJavadocComment(String comment) {
- return setJavadocComment(new JavadocComment(comment));
+ return setJavadocComment(new JavadocComment(" " + comment));
}
default N setJavadocComment(JavadocComment comment) { | 1 | /*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2016 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) 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.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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.
*/
package com.github.javaparser.ast.nodeTypes;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.comments.JavadocComment;
import com.github.javaparser.javadoc.Javadoc;
import java.util.Optional;
/**
* A node that can be documented with a Javadoc comment.
*/
public interface NodeWithJavadoc<N extends Node> {
Optional<Comment> getComment();
Node setComment(Comment comment);
/**
* Gets the JavadocComment for this node. You can set the JavadocComment by calling setJavadocComment passing a
* JavadocComment.
*
* @return The JavadocComment for this node wrapped in an optional as it may be absent.
*/
default Optional<JavadocComment> getJavadocComment() {
return getComment()
.filter(comment -> comment instanceof JavadocComment)
.map(comment -> (JavadocComment) comment);
}
/**
* Gets the Javadoc for this node. You can set the Javadoc by calling setJavadocComment passing a Javadoc.
*
* @return The Javadoc for this node wrapped in an optional as it may be absent.
*/
default Optional<Javadoc> getJavadoc() {
return getJavadocComment().map(JavadocComment::parse);
}
/**
* Use this to store additional information to this node.
*
* @param comment to be set
*/
@SuppressWarnings("unchecked")
default N setJavadocComment(String comment) {
return setJavadocComment(new JavadocComment(comment));
}
default N setJavadocComment(JavadocComment comment) {
setComment(comment);
return (N) this;
}
default N setJavadocComment(String indentation, Javadoc javadoc) {
JavadocComment comment = javadoc.toComment(indentation);
return setJavadocComment(comment);
}
default boolean removeJavaDocComment() {
return hasJavaDocComment() && getComment().get().remove();
}
default boolean hasJavaDocComment() {
return getComment().isPresent() && getComment().get() instanceof JavadocComment;
}
}
| 1 | 12,156 | Why the space? | javaparser-javaparser | java |
@@ -38,10 +38,10 @@ public interface ZalcanoConfig extends Config
{
@ConfigTitleSection(
- keyName = "zalcanoTitle",
- name = "Zalcano",
- description = "",
- position = 0
+ keyName = "zalcanoTitle",
+ name = "Zalcano",
+ description = "",
+ position = 0
)
default Title zalcanoTitle()
{ | 1 | /*
*
* * Copyright (c) 2019, gazivodag <https://github.com/gazivodag>
* * 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.client.plugins.zalcano;
import java.awt.Color;
import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;
import net.runelite.client.config.ConfigTitleSection;
import net.runelite.client.config.Title;
@ConfigGroup("zalcano")
public interface ZalcanoConfig extends Config
{
@ConfigTitleSection(
keyName = "zalcanoTitle",
name = "Zalcano",
description = "",
position = 0
)
default Title zalcanoTitle()
{
return new Title();
}
@ConfigItem(
keyName = "highlightZalcanoHull",
name = "Highlight Zalcano",
description = "Highlight Zalcano\'s convex hull.",
titleSection = "zalcanoTitle",
position = 1
)
default boolean highlightZalcanoHull()
{
return false;
}
@ConfigItem(
keyName = "zalcanoHullColor",
name = "Color for highlight",
description = "",
titleSection = "zalcanoTitle",
position = 2
)
default Color zalcanoHullColor()
{
return new Color(255, 25, 0);
}
@ConfigTitleSection(
keyName = "zalcanoAoesTitle",
name = "Area of Effect",
description = "",
position = 3
)
default Title zalcanoAoesTitle()
{
return new Title();
}
@ConfigItem(
keyName = "showAoeZalcanoWakeup",
name = "Zalcano Wakeup",
description = "Shows an AOE warning for Zalcano waking back up.",
titleSection = "zalcanoAoesTitle",
position = 4
)
default boolean showAoeZalcanoWakeup()
{
return true;
}
@ConfigItem(
keyName = "showAoeForRockfall",
name = "Small Rocks",
description = "Shows an AOE warning for the rocks that fall occasionally.",
titleSection = "zalcanoAoesTitle",
position = 5
)
default boolean showAoeForRockfall()
{
return true;
}
@ConfigItem(
keyName = "showAoeForRedSymbols",
name = "Red Symbols",
description = "Shows an AOE warning for the 3x3 red symbols that appear.",
titleSection = "zalcanoAoesTitle",
position = 6
)
default boolean showAoeForRedSymbols()
{
return true;
}
@ConfigItem(
keyName = "highlightMiningSpot",
name = "Mining spot",
description = "Highlights the glowing rock and warns you if Zalcano attacks it.",
titleSection = "zalcanoAoesTitle",
position = 7
)
default boolean highlightMiningSpot()
{
return true;
}
@ConfigTitleSection(
keyName = "helperTitle",
name = "Helpers",
description = "",
position = 8
)
default Title helperTitle()
{
return new Title();
}
/**
* TODO: improve helper
*/
@ConfigItem(
keyName = "showSteps",
name = "Show Step",
description = "",
titleSection = "helperTitle",
position = 9,
hidden = true //hidden until fully functional
)
default boolean showSteps()
{
return false;
}
@ConfigItem(
keyName = "showAoeZalcanoMineable",
name = "Zalcano Mineable",
description = "Highlights Zalcano if she is mineable.",
titleSection = "helperTitle",
position = 10
)
default boolean showAoeZalcanoMineable()
{
return true;
}
@ConfigItem(
keyName = "highlightGolem",
name = "Highlight Golem",
description = "Highlights the Golem that Zalcano spawns in.",
titleSection = "helperTitle",
position = 11
)
default boolean highlightGolem()
{
return true;
}
}
| 1 | 16,106 | please resolve the extra indentation | open-osrs-runelite | java |
@@ -69,8 +69,9 @@ namespace pwiz.Skyline.Model.Lib
protected override bool StateChanged(SrmDocument document, SrmDocument previous)
{
return previous == null ||
- !ReferenceEquals(document.Settings.PeptideSettings.Libraries, previous.Settings.PeptideSettings.Libraries) ||
- !ReferenceEquals(document.Settings.MeasuredResults, previous.Settings.MeasuredResults);
+ !ReferenceEquals(document.Settings.PeptideSettings.Libraries, previous.Settings.PeptideSettings.Libraries) ||
+ !ReferenceEquals(document.Settings.MeasuredResults, previous.Settings.MeasuredResults) ||
+ !ReferenceEquals(document.Id, previous.Id);
}
protected override string IsNotLoadedExplained(SrmDocument document) | 1 | /*
* Original author: Brendan MacLean <brendanx .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2009 University of Washington - Seattle, WA
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using pwiz.Common.Chemistry;
using pwiz.Common.Collections;
using pwiz.Common.SystemUtil;
using pwiz.Skyline.Model.AuditLog;
using pwiz.Skyline.Model.Crosslinking;
using pwiz.Skyline.Model.DocSettings;
using pwiz.Skyline.Model.DocSettings.Extensions;
using pwiz.Skyline.Model.Irt;
using pwiz.Skyline.Model.Lib.ChromLib;
using pwiz.Skyline.Model.Lib.Midas;
using pwiz.Skyline.Model.Prosit;
using pwiz.Skyline.Model.Results;
using pwiz.Skyline.Model.RetentionTimes;
using pwiz.Skyline.Properties;
using pwiz.Skyline.Util;
using pwiz.Skyline.Util.Extensions;
namespace pwiz.Skyline.Model.Lib
{
public sealed class LibraryManager : BackgroundLoader
{
private readonly Dictionary<string, Library> _loadedLibraries =
new Dictionary<string, Library>();
private readonly Dictionary<string, LibraryLoadLock> _loadingLibraries =
new Dictionary<string, LibraryLoadLock>();
private class LibraryLoadLock
{
public Library Library { get; set; }
public bool IsLoaded { get; set; }
}
public override void ClearCache()
{
lock(_loadedLibraries)
{
_loadedLibraries.Clear();
}
}
protected override bool StateChanged(SrmDocument document, SrmDocument previous)
{
return previous == null ||
!ReferenceEquals(document.Settings.PeptideSettings.Libraries, previous.Settings.PeptideSettings.Libraries) ||
!ReferenceEquals(document.Settings.MeasuredResults, previous.Settings.MeasuredResults);
}
protected override string IsNotLoadedExplained(SrmDocument document)
{
PeptideLibraries libraries = document.Settings.PeptideSettings.Libraries;
if (document.Settings.MeasuredResults != null)
{
var missingFiles = MidasLibrary.GetMissingFiles(document, new Library[0]);
if (missingFiles.Any())
{
return TextUtil.LineSeparate(@"MIDAS library is missing files:",
TextUtil.LineSeparate(missingFiles));
}
}
return !libraries.HasLibraries ? null : libraries.IsNotLoadedExplained;
}
protected override IEnumerable<IPooledStream> GetOpenStreams(SrmDocument document)
{
if (document == null)
yield break;
var libraries = document.Settings.PeptideSettings.Libraries.Libraries;
foreach (var readStream in libraries.Where(library => library != null)
.SelectMany(library => library.ReadStreams))
{
yield return readStream;
}
}
protected override bool IsCanceled(IDocumentContainer container, object tag)
{
if (tag == null)
return false;
PeptideLibraries libraries = container.Document.Settings.PeptideSettings.Libraries;
var missingMidasFiles = tag as string[];
if (missingMidasFiles != null)
{
return !missingMidasFiles.SequenceEqual(MidasLibrary.GetMissingFiles(container.Document, new Library[0]));
}
return !libraries.LibrarySpecs.Contains((LibrarySpec)tag);
}
protected override bool LoadBackground(IDocumentContainer container, SrmDocument document, SrmDocument docCurrent)
{
var libraries = docCurrent.Settings.PeptideSettings.Libraries;
var dictLibraries = new Dictionary<string, Library>();
try
{
foreach (LibrarySpec spec in libraries.LibrarySpecsUnloaded)
{
if (spec == null || dictLibraries.ContainsKey(spec.Name))
continue;
var library = LoadLibrary(container, spec);
if (library == null || !ReferenceEquals(document.Id, container.Document.Id))
{
// Loading was cancelled or document changed
EndProcessing(document);
return false;
}
dictLibraries.Add(spec.Name, library);
}
var missingMidasFiles = MidasLibrary.GetMissingFiles(document, libraries.Libraries);
var midasLibPath = MidasLibSpec.GetLibraryFileName(container.DocumentFilePath);
var midasLibSpec = libraries.MidasLibrarySpecs.FirstOrDefault(libSpec => Equals(libSpec.FilePath, midasLibPath));
var newMidasLibSpec = missingMidasFiles.Any() && midasLibSpec == null;
MidasLibrary midasLibrary = null;
var failedMidasFiles = new List<MsDataFilePath>();
if (missingMidasFiles.Any())
{
if (midasLibSpec == null)
{
// Need to add MIDAS LibSpec to document
midasLibSpec = (MidasLibSpec)LibrarySpec.CreateFromPath(MidasLibSpec.GetName(container.DocumentFilePath, libraries.LibrarySpecs), midasLibPath);
}
MidasLibrary.AddSpectra(midasLibSpec, missingMidasFiles.Select(f => new MsDataFilePath(f)).ToArray(), docCurrent, new LoadMonitor(this, container, null), out failedMidasFiles);
if (failedMidasFiles.Count < missingMidasFiles.Length)
{
if (!newMidasLibSpec)
ReloadLibraries(container, midasLibSpec);
midasLibrary = (MidasLibrary) LoadLibrary(midasLibSpec, () => new LoadMonitor(this, container, !newMidasLibSpec ? midasLibSpec : null));
if (midasLibrary != null && !dictLibraries.ContainsKey(midasLibSpec.Name))
dictLibraries.Add(midasLibSpec.Name, midasLibrary);
}
else
{
midasLibSpec = null;
newMidasLibSpec = false;
}
}
SrmDocument docNew;
do
{
// Look for unloaded libraries in the current document that match
// those loaded.
docCurrent = container.Document;
libraries = docCurrent.Settings.PeptideSettings.Libraries;
bool changed = false;
var list = new List<Library>();
foreach (LibrarySpec spec in libraries.LibrarySpecs)
{
if (spec == null)
continue;
Library libraryExisting = libraries.GetLibrary(spec.Name);
Library libraryLoaded;
if ((libraryExisting != null && libraryExisting.IsLoaded) ||
!dictLibraries.TryGetValue(spec.Name, out libraryLoaded))
list.Add(libraryExisting);
else
{
list.Add(libraryLoaded);
changed = true;
}
}
// If nothing changed, end without changing the document.
if (!changed && !newMidasLibSpec && !failedMidasFiles.Any())
{
return false;
}
docNew = docCurrent;
if (newMidasLibSpec)
{
// We need to add this MIDAS LibrarySpec to the document
var libSpecs = libraries.LibrarySpecs.ToList();
libSpecs.Add(midasLibSpec);
docNew = docNew.ChangeSettings(docNew.Settings.ChangePeptideLibraries(libs => libs.ChangeLibrarySpecs(libSpecs)));
libraries = docNew.Settings.PeptideSettings.Libraries;
list.Add(midasLibrary);
docNew.Settings.UpdateLists(container.DocumentFilePath);
// Switch to pick by filter if there are no other libraries
if (libSpecs.Count == 1)
{
libraries = libraries
.ChangeRankId(null)
.ChangePick(PeptidePick.filter);
docNew = docNew.ChangeSettings(docNew.Settings.ChangeTransitionSettings(
settings => settings.ChangeLibraries(settings.Libraries.ChangePick(TransitionLibraryPick.none))));
}
}
libraries = libraries.ChangeLibraries(list.ToArray());
if (missingMidasFiles.Any() && docNew.Settings.HasResults)
{
var newChromatograms = MidasLibrary.UnflagFiles(docNew.Settings.MeasuredResults.Chromatograms, missingMidasFiles.Select(Path.GetFileName)).ToList();
if (!ArrayUtil.ReferencesEqual(docNew.Settings.MeasuredResults.Chromatograms, newChromatograms))
{
docNew = docNew.ChangeMeasuredResults(docNew.Settings.MeasuredResults.ChangeChromatograms(newChromatograms));
}
}
using (var settingsChangeMonitor = new SrmSettingsChangeMonitor(
new LoadMonitor(this, container, null), Resources.LibraryManager_LoadBackground_Updating_library_settings_for__0_, container, docCurrent))
{
try
{
docNew = docNew.ChangeSettings(docNew.Settings.ChangePeptideSettings(
docNew.Settings.PeptideSettings.ChangeLibraries(libraries)), settingsChangeMonitor);
}
catch (InvalidDataException x)
{
settingsChangeMonitor.ChangeProgress(s => s.ChangeErrorException(x));
break;
}
catch (OperationCanceledException)
{
docNew = docCurrent; // Just continue
}
}
}
while (!CompleteProcessing(container, docNew, docCurrent));
}
finally
{
foreach (var library in dictLibraries.Values.Where(lib => lib.ReadStream != null))
{
lock (library.ReadStream)
{
library.ReadStream.CloseStream();
}
}
EndProcessing(docCurrent);
}
return true;
}
public Library LoadLibrary(LibrarySpec spec, Func<ILoadMonitor> getMonitor)
{
LibraryLoadLock loadLock;
lock (_loadedLibraries)
{
Library library;
if (_loadedLibraries.TryGetValue(spec.Name, out library))
{
if (Equals(spec, library.CreateSpec(library.FileNameHint)))
{
return library;
}
else
{
_loadedLibraries.Remove(spec.Name);
}
}
// If the library has not yet been loaded, then create a new lock
// for everyone to wait on until the library has been loaded.
if (!_loadingLibraries.TryGetValue(spec.Name, out loadLock))
{
loadLock = new LibraryLoadLock();
_loadingLibraries.Add(spec.Name, loadLock);
}
}
lock (loadLock)
{
if (!loadLock.IsLoaded)
{
loadLock.Library = spec.LoadLibrary(getMonitor());
loadLock.IsLoaded = true;
}
}
lock (_loadedLibraries)
{
_loadingLibraries.Remove(spec.Name);
if (loadLock.Library != null)
{
// Update the newly loaded library in the dictionary, regardless of whether
// we were the thread that actually did the loading.
_loadedLibraries[spec.Name] = loadLock.Library;
}
return loadLock.Library;
}
}
private Library LoadLibrary(IDocumentContainer container, LibrarySpec spec)
{
return LoadLibrary(spec, () => new LoadMonitor(this, container, spec));
}
public void ReloadLibraries(IDocumentContainer container, params LibrarySpec[] specs)
{
lock (_loadedLibraries)
{
foreach (var spec in specs)
{
_loadedLibraries.Remove(spec.Name);
}
ForDocumentLibraryReload(container, specs.Select(spec => spec.Name).ToArray());
}
}
public void ReleaseLibraries(params LibrarySpec[] specs)
{
lock (_loadedLibraries)
{
foreach (var spec in specs)
{
_loadedLibraries.Remove(spec.Name);
}
}
}
public void UnloadChangedLibraries(IEnumerable<LibrarySpec> specs)
{
lock (_loadedLibraries)
{
foreach (var spec in specs)
{
Library library;
if (_loadedLibraries.TryGetValue(spec.Name, out library))
{
var specCompare = library.CreateSpec(library.FileNameHint);
if (!Equals(spec, specCompare))
{
_loadedLibraries.Remove(spec.Name);
}
}
}
}
}
public Library TryGetLibrary(LibrarySpec spec)
{
lock (_loadedLibraries)
{
Library library;
_loadedLibraries.TryGetValue(spec.Name, out library);
return library;
}
}
public delegate bool BuildFunction(IDocumentContainer documentContainer,
ILibraryBuilder libraryBuilder,
IProgressMonitor monitor,
BuildState buildState);
public sealed class BuildState
{
public BuildState(LibrarySpec librarySpec, BuildFunction buildFunc)
{
LibrarySpec = librarySpec;
BuildFunc = buildFunc;
}
public LibrarySpec LibrarySpec { get; private set; }
public BuildFunction BuildFunc { get; private set; }
public string BuildCommandArgs { get; set; }
public string BuildOutput { get; set; }
public string ExtraMessage { get; set; }
public IrtStandard IrtStandard { get; set; }
}
public void BuildLibrary(IDocumentContainer container, ILibraryBuilder builder, Action<BuildState, bool> callback)
{
var monitor = new LibraryBuildMonitor(this, container);
var buildState = new BuildState(builder.LibrarySpec, BuildLibraryBackground);
ActionUtil.RunAsync(() => callback(buildState, BuildLibraryBackground(container, builder, monitor, buildState)), @"Library Build");
}
public bool BuildLibraryBackground(IDocumentContainer container, ILibraryBuilder builder, IProgressMonitor monitor, BuildState buildState)
{
LocalizationHelper.InitThread();
// Avoid building a library that is loading or allowing the library to be loaded
// while it is building
LibraryLoadLock loadLock;
lock (_loadedLibraries)
{
if (!_loadingLibraries.TryGetValue(builder.LibrarySpec.Name, out loadLock))
{
loadLock = new LibraryLoadLock();
_loadingLibraries.Add(builder.LibrarySpec.Name, loadLock);
}
}
bool success;
lock (loadLock)
{
success = builder.BuildLibrary(monitor);
var iRTCapableBuilder = builder as IiRTCapableLibraryBuilder;
if (null != iRTCapableBuilder)
{
buildState.BuildCommandArgs = iRTCapableBuilder.BuildCommandArgs;
buildState.BuildOutput = iRTCapableBuilder.BuildOutput;
if (!string.IsNullOrEmpty(iRTCapableBuilder.AmbiguousMatchesMessage))
{
buildState.ExtraMessage = iRTCapableBuilder.AmbiguousMatchesMessage;
}
if (iRTCapableBuilder.IrtStandard != null &&
!iRTCapableBuilder.IrtStandard.Name.Equals(IrtStandard.EMPTY.Name))
{
buildState.IrtStandard = iRTCapableBuilder.IrtStandard;
}
}
}
lock (_loadedLibraries)
{
_loadingLibraries.Remove(builder.LibrarySpec.Name);
if (success)
{
// If the library was already loaded, make sure the new copy
// replaces the load in the library load cache.
string name = builder.LibrarySpec.Name;
_loadedLibraries.Remove(name);
// If the current document contains the newly built library,
// make sure it is reloaded into the document, by resetting all
// library-specs. Do this inside the lock to avoid library loading
// happening during this check.
ForDocumentLibraryReload(container, new[] {name});
}
return success;
}
}
private static void ForDocumentLibraryReload(IDocumentContainer container, string[] specs)
{
var docOriginal = container.Document;
if (docOriginal == null)
return;
var librarySettings = docOriginal.Settings.PeptideSettings.Libraries;
if (!librarySettings.HasLibraries)
return;
int iSpec = librarySettings.LibrarySpecs.IndexOf(spec => spec != null && specs.Contains(spec.Name));
if (iSpec == -1 || librarySettings.Libraries[iSpec] == null)
return;
SrmDocument docNew;
do
{
docOriginal = container.Document;
var settings =
docOriginal.Settings.ChangePeptideLibraries(
lib =>
{
var listLib = new List<Library>(lib.Libraries);
int i = lib.LibrarySpecs.IndexOf(spec => specs.Contains(spec.Name));
if (i != -1)
listLib[i] = null;
return lib.ChangeLibraries(listLib);
});
docNew = docOriginal.ChangeSettings(settings);
} while (!container.SetDocument(docNew, docOriginal));
}
private class LibraryBuildMonitor : IProgressMonitor
{
private readonly LibraryManager _manager;
// Might want this someday...
// ReSharper disable NotAccessedField.Local
private readonly IDocumentContainer _container;
// ReSharper restore NotAccessedField.Local
public LibraryBuildMonitor(LibraryManager manager, IDocumentContainer container)
{
_manager = manager;
_container = container;
}
// TODO: Some way to cancel a library build
public bool IsCanceled
{
get { return false; }
}
public UpdateProgressResponse UpdateProgress(IProgressStatus status)
{
return _manager.UpdateProgress(status);
}
public bool HasUI { get { return false; } }
}
}
/// <summary>
/// Implement on a class for building a specific type of library.
/// </summary>
public interface ILibraryBuilder
{
/// <summary>
/// Build the library with progress monitoring, and the ability
/// to cancel.
/// </summary>
/// <param name="progress">Sink for progress updates, and source of user cancel status</param>
bool BuildLibrary(IProgressMonitor progress);
/// <summary>
/// A <see cref="LibrarySpec"/> referencing the library to be built.
/// </summary>
LibrarySpec LibrarySpec { get; }
}
public enum LibraryRedundancy { best, all, all_redundant }
public abstract class Library : XmlNamedElement
{
protected Library(LibrarySpec spec) : base(spec.Name)
{
FileNameHint = Path.GetFileName(spec.FilePath);
UseExplicitPeakBounds = spec.UseExplicitPeakBounds;
}
/// <summary>
/// Original file name used to create this library, for use in finding
/// the library, if its identifying name is not present in the
/// <see cref="SpectralLibraryList"/>
/// </summary>
public string FileNameHint { get; private set; }
public bool UseExplicitPeakBounds { get; private set; }
/// <summary>
/// Creates the appropriate library spec for this library, given a path
/// to the library.
/// </summary>
/// <param name="path">Path to the library file on disk</param>
/// <returns>A new <see cref="LibrarySpec"/></returns>
public virtual LibrarySpec CreateSpec(string path)
{
return CreateSpec().ChangeFilePath(path)
.ChangeUseExplicitPeakBounds(UseExplicitPeakBounds);
}
protected abstract LibrarySpec CreateSpec();
/// <summary>
/// Returns the filter string to be used for finding a library of this type.
/// </summary>
public abstract string SpecFilter { get; }
/// <summary>
/// Returns the <see cref="IPooledStream"/> for the stream on which this library
/// relies for its data reading.
/// </summary>
public abstract IPooledStream ReadStream { get; }
/// <summary>
/// Returns all open <see cref="IPooledStream"/> associated with the library.
/// Default implementation returns the single stream from <see cref="ReadStream"/>.
/// </summary>
public virtual IEnumerable<IPooledStream> ReadStreams
{
get
{
if (ReadStream != null)
yield return ReadStream;
}
}
/// <summary>
/// True if this library is loaded and may be used to query spectral
/// data. False if it is merely a placeholder loaded from a document
/// which has not yet been connected to the actual library data.
/// </summary>
public bool IsLoaded
{
get { return IsNotLoadedExplained == null; }
}
/// <summary>
/// Same as IsLoaded property, but returns a non-null and hopefully useful message
/// for test purposes when not loaded.
/// </summary>
public abstract string IsNotLoadedExplained { get; }
/// <summary>
/// Determines if this library identifies itself as being the same
/// as another library.
/// </summary>
/// <param name="library">Library to check for identity</param>
/// <returns>True if the libraries have the same identity</returns>
public abstract bool IsSameLibrary(Library library);
/// <summary>
/// Used to determine relative ordering of this library with another
/// in an odered progression of revisions. This check is only valid
/// if <see cref="IsSameLibrary"/> is true for the library parameter.
/// </summary>
/// <param name="library">Library to compare revisions with</param>
/// <returns>0 if revisions are equal,
/// 1 if the given library is new than this,
/// -1 if the given library is older than this</returns>
public abstract int CompareRevisions(Library library);
/// <summary>
/// Determines if the library contains a specific (modified sequence, charge) pair.
/// </summary>
/// <param name="key">A sequence, charge pair</param>
/// <returns>True if the library contains the key</returns>
public abstract bool Contains(LibKey key);
/// <summary>
/// Determines if the library contains any spectra for a peptide, based on its
/// unmodified amino acid sequence.
/// </summary>
/// <param name="target">An unmodified sequence</param>
/// <returns>True if the library contains any spectra for this peptide regardless of modification or charge</returns>
public abstract bool ContainsAny(Target target);
/// <summary>
/// Some details for the library.
/// This can be the library revision, program version,
/// build date or a hyperlink to the library source
/// (e.g. http://peptide.nist.gov/ for NIST libraries)
/// </summary>
public abstract LibraryDetails LibraryDetails { get; }
/// <summary>
/// Only contains paths for files in library
/// Unlike LibraryDetails which contains more information
/// </summary>
public abstract LibraryFiles LibraryFiles { get; }
/// <summary>
/// Attempts to get spectrum header information for a specific
/// (sequence, charge) pair.
/// </summary>
/// <param name="key">A sequence, charge pair</param>
/// <param name="libInfo">The spectrum header information, if successful</param>
/// <returns>True if the library contains the key</returns>
public abstract bool TryGetLibInfo(LibKey key, out SpectrumHeaderInfo libInfo);
/// <summary>
/// Attempts to get spectrum peak information for a specific
/// (sequence, charge) pair.
/// </summary>
/// <param name="key">A sequence, charge pair</param>
/// <param name="spectrum">The spectrum peak information, if successful</param>
/// <returns>True if the spectrum was retrieved successfully</returns>
public abstract bool TryLoadSpectrum(LibKey key, out SpectrumPeaksInfo spectrum);
/// <summary>
/// Loads a spectrum given a key provided by the library.
/// </summary>
/// <param name="spectrumKey">A key that uniquely identifies the spectrum</param>
/// <returns>The requested spectrum peak information</returns>
public abstract SpectrumPeaksInfo LoadSpectrum(object spectrumKey);
public virtual LibraryChromGroup LoadChromatogramData(object spectrumKey)
{
return null;
}
/// <summary>
/// Attempts to get retention time information for a specific
/// (sequence, charge) pair and file.
/// </summary>
/// <param name="key">A sequence, charge pair</param>
/// <param name="filePath">A file for which the retention information is requested</param>
/// <param name="retentionTimes">A list of retention times, if successful</param>
/// <returns>True if retention time information was retrieved successfully</returns>
public abstract bool TryGetRetentionTimes(LibKey key, MsDataFileUri filePath, out double[] retentionTimes);
/// <summary>
/// Attempts to get retention time information for all of the
/// (sequence, charge) pairs identified from a specific file.
/// </summary>
/// <param name="filePath">A file for which the retention time information is requested</param>
/// <param name="retentionTimes"></param>
/// <returns>True if retention time information was retrieved successfully</returns>
public abstract bool TryGetRetentionTimes(MsDataFileUri filePath, out LibraryRetentionTimes retentionTimes);
/// <summary>
/// Attempts to get retention time information for all of the
/// (sequence, charge) pairs identified from a specific file by index.
/// </summary>
/// <param name="fileIndex">Index of a file for which the retention time information is requested</param>
/// <param name="retentionTimes"></param>
/// <returns>True if retention time information was retrieved successfully</returns>
public abstract bool TryGetRetentionTimes(int fileIndex, out LibraryRetentionTimes retentionTimes);
/// <summary>
/// If an explicit peak boundary has been set for any of the peptide sequences, then return
/// that peak boundary.
/// </summary>
public virtual ExplicitPeakBounds GetExplicitPeakBounds(MsDataFileUri filePath, IEnumerable<Target> peptideSequences)
{
return null;
}
/// <summary>
/// Attempts to get iRT information from the library.
/// </summary>
/// <param name="retentionTimes">A list of iRTs, if successful</param>
/// <returns>True if iRT information was retrieved successfully</returns>
public abstract bool TryGetIrts(out LibraryRetentionTimes retentionTimes);
public virtual IEnumerable<double> GetRetentionTimesWithSequences(string filePath, IEnumerable<Target> peptideSequences, ref int? fileIndex)
{
return new double[0];
}
/// <summary>
/// Attempts to get ion mobility information for a specific
/// (sequence, charge) pair and file.
/// </summary>
/// <param name="key">A sequence, charge pair</param>
/// <param name="filePath">A file for which the ion mobility information is requested</param>
/// <param name="ionMobilities">A list of ion mobility info, if successful</param>
/// <returns>True if ion mobility information was retrieved successfully</returns>
public abstract bool TryGetIonMobilityInfos(LibKey key, MsDataFileUri filePath, out IonMobilityAndCCS[] ionMobilities);
/// <summary>
/// Attempts to get ion mobility information for selected
/// (sequence, charge) pairs identified from a specific file.
/// </summary>
/// <param name="targetIons">A list of sequence, charge pairs</param>
/// <param name="filePath">A file for which the ion mobility information is requested</param>
/// <param name="ionMobilities">A list of ion mobility info, if successful</param>
/// <returns>True if ion mobility information was retrieved successfully</returns>
public abstract bool TryGetIonMobilityInfos(LibKey[] targetIons, MsDataFileUri filePath, out LibraryIonMobilityInfo ionMobilities);
/// <summary>
/// Attempts to get ion mobility information for all of the
/// (sequence, charge) pairs identified from a specific file by index.
/// </summary>
/// <param name="targetIons">A list of sequence, charge pairs</param>
/// <param name="fileIndex">Index of a file for which the ion mobility information is requested</param>
/// <param name="ionMobilities">A list of ion mobility info, if successful</param>
/// <returns>True if ion mobility information was retrieved successfully</returns>
public abstract bool TryGetIonMobilityInfos(LibKey[] targetIons, int fileIndex, out LibraryIonMobilityInfo ionMobilities);
/// <summary>
/// Attempts to get ion mobility information for all of the
/// (sequence, charge) pairs identified from all files.
/// </summary>
/// <param name="targetIons">A list of sequence, charge pairs</param>
/// <param name="ionMobilities">A list of ion mobility info, if successful</param>
/// <returns>True if ion mobility information was retrieved successfully</returns>
public abstract bool TryGetIonMobilityInfos(LibKey[] targetIons, out LibraryIonMobilityInfo ionMobilities);
/// <summary>
/// Gets all of the spectrum information for a particular (sequence, charge) pair. This
/// may include redundant spectra. The spectrum points themselves are only loaded as it they
/// requested to give this function acceptable performance.
/// </summary>
/// <param name="key">The sequence, charge pair requested</param>
/// <param name="labelType">An <see cref="IsotopeLabelType"/> for which to get spectra</param>
/// <param name="redundancy">Level of redundancy requested in returned values</param>
/// <returns>An enumeration of <see cref="SpectrumInfo"/></returns>
public abstract IEnumerable<SpectrumInfoLibrary> GetSpectra(LibKey key,
IsotopeLabelType labelType, LibraryRedundancy redundancy);
/// <summary>
/// Returns the number of files or mass spec runs for which this library
/// contains spectra, or null if this is unknown.
/// </summary>
public abstract int? FileCount { get; }
/// <summary>
/// Returns the total number of spectra loaded from the library.
/// </summary>
public abstract int SpectrumCount { get; }
/// <summary>
/// Returns an enumerator for the keys of the spectra loaded from the library.
/// </summary>
public abstract IEnumerable<LibKey> Keys { get; }
/// <summary>
/// Returns a list of <see cref="RetentionTimeSource"/> objects representing
/// the data files that this Library can provide peptide retention time
/// values for.
/// </summary>
public virtual IList<RetentionTimeSource> ListRetentionTimeSources()
{
return new RetentionTimeSource[0];
}
public IEnumerable<IRetentionTimeProvider> RetentionTimeProvidersIrt
{
get
{
LibraryRetentionTimes irts;
if (TryGetIrts(out irts))
yield return irts;
}
}
public IEnumerable<IRetentionTimeProvider> RetentionTimeProviders
{
get
{
var fileCount = FileCount;
if (!fileCount.HasValue)
yield break;
for (var i = 0; i < fileCount.Value; i++)
{
LibraryRetentionTimes retentionTimes;
if (TryGetRetentionTimes(i, out retentionTimes))
yield return retentionTimes;
}
}
}
#region File reading utility functions
protected internal static int GetInt32(byte[] bytes, int index, int offset = 0)
{
int ibyte = offset + index * 4;
return bytes[ibyte] | bytes[ibyte + 1] << 8 | bytes[ibyte + 2] << 16 | bytes[ibyte + 3] << 24;
}
protected static float GetSingle(byte[] bytes, int index)
{
return BitConverter.ToSingle(bytes, index * 4);
}
protected static int ReadSize(Stream stream)
{
byte[] libSize = new byte[4];
ReadComplete(stream, libSize, libSize.Length);
return GetInt32(libSize, 0);
}
protected static string ReadString(Stream stream, int countBytes)
{
byte[] stringBytes = new byte[countBytes];
ReadComplete(stream, stringBytes, countBytes);
return Encoding.UTF8.GetString(stringBytes);
}
protected static void ReadComplete(Stream stream, byte[] buffer, int size)
{
if (stream.Read(buffer, 0, size) != size)
throw new InvalidDataException(Resources.Library_ReadComplete_Data_truncation_in_library_header_File_may_be_corrupted);
}
protected static void SafeReadComplete(Stream stream, ref byte[] buffer, int size)
{
if (size > buffer.Length)
buffer = new byte[size];
if (stream.Read(buffer, 0, size) != size)
throw new InvalidDataException(Resources.Library_ReadComplete_Data_truncation_in_library_header_File_may_be_corrupted);
}
#endregion
protected bool Equals(Library other)
{
return base.Equals(other) && string.Equals(FileNameHint, other.FileNameHint) && UseExplicitPeakBounds == other.UseExplicitPeakBounds;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Library) obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = base.GetHashCode();
hashCode = (hashCode * 397) ^ (FileNameHint != null ? FileNameHint.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ UseExplicitPeakBounds.GetHashCode();
return hashCode;
}
}
#region Implementation of IXmlSerializable
/// <summary>
/// For XML serialization
/// </summary>
protected Library()
{
}
private enum ATTR
{
file_name_hint,
use_explicit_peak_bounds
}
public override void ReadXml(XmlReader reader)
{
// Read tag attributes
base.ReadXml(reader);
FileNameHint = reader.GetAttribute(ATTR.file_name_hint);
UseExplicitPeakBounds = reader.GetBoolAttribute(ATTR.use_explicit_peak_bounds, true);
}
public override void WriteXml(XmlWriter writer)
{
// Write tag attributes
base.WriteXml(writer);
writer.WriteAttributeIfString(ATTR.file_name_hint, FileNameHint);
writer.WriteAttribute(ATTR.use_explicit_peak_bounds, UseExplicitPeakBounds, true);
}
#endregion
}
public interface ICachedSpectrumInfo
{
LibKey Key { get; }
}
public abstract class CachedLibrary<TInfo> : Library
where TInfo : ICachedSpectrumInfo
{
protected CachedLibrary()
{
}
protected CachedLibrary(LibrarySpec spec) : base(spec)
{
}
protected LibKeyMap<TInfo> _libraryEntries;
protected string CachePath { get; set; }
public override string IsNotLoadedExplained
{
get { return (_libraryEntries != null) ? null : @"no library entries"; }
}
public override bool ContainsAny(Target target)
{
return _libraryEntries.ItemsWithUnmodifiedSequence(target).Any();
}
public override bool Contains(LibKey key)
{
return FindEntry(key) != -1;
}
protected int FindExactEntry(LibKey key)
{
if (_libraryEntries == null)
return -1;
return _libraryEntries.IndexOf(key.LibraryKey);
}
protected int FindEntry(LibKey key)
{
if (_libraryEntries == null)
{
return -1;
}
foreach (var entry in _libraryEntries.Index.ItemsMatching(key, true))
{
return entry.OriginalIndex;
}
return -1;
}
protected virtual void SetLibraryEntries(IEnumerable<TInfo> entries)
{
var entryList = ImmutableList.ValueOf(entries);
_libraryEntries = new LibKeyMap<TInfo>(entryList, entryList.Select(entry=>entry.Key.LibraryKey));
}
protected List<TInfo> FilterInvalidLibraryEntries(ref IProgressStatus status, IEnumerable<TInfo> entries)
{
var validEntries = new List<TInfo>();
var invalidKeys = new List<LibKey>();
foreach (var entry in entries)
{
if (!IsValidLibKey(entry.Key))
{
invalidKeys.Add(entry.Key);
}
else
{
validEntries.Add(entry);
}
}
status = WarnInvalidEntries(status, validEntries.Count, invalidKeys);
return validEntries;
}
protected bool IsValidLibKey(LibKey libKey)
{
try
{
var unused = libKey.LibraryKey.CreatePeptideIdentityObj();
return true;
}
catch (Exception)
{
return false;
}
}
protected IProgressStatus WarnInvalidEntries(IProgressStatus progressStatus, int validEntryCount,
ICollection<LibKey> invalidEntries)
{
if (invalidEntries.Count == 0)
{
return progressStatus;
}
var invalidText = TextUtil.LineSeparate(invalidEntries.Take(10).Select(key => key.ToString()));
string warningMessage = string.Format(Resources.CachedLibrary_WarnInvalidEntries_,
Name, invalidEntries.Count, invalidEntries.Count + validEntryCount, invalidText);
progressStatus = progressStatus.ChangeWarningMessage(warningMessage);
return progressStatus;
}
public override bool TryGetLibInfo(LibKey key, out SpectrumHeaderInfo libInfo)
{
var index = FindEntry(key);
if (index != -1)
{
libInfo = CreateSpectrumHeaderInfo(_libraryEntries[index]);
return true;
}
libInfo = null;
return false;
}
protected abstract SpectrumHeaderInfo CreateSpectrumHeaderInfo(TInfo info);
public override bool TryLoadSpectrum(LibKey key, out SpectrumPeaksInfo spectrum)
{
int i = FindEntry(key);
if (i != -1)
{
var spectrumPeaks = ReadSpectrum(_libraryEntries[i]);
if (spectrumPeaks != null)
{
spectrum = new SpectrumPeaksInfo(spectrumPeaks);
return true;
}
}
spectrum = null;
return false;
}
public override SpectrumPeaksInfo LoadSpectrum(object spectrumKey)
{
var spectrumPeaks = ReadSpectrum(_libraryEntries[(int)spectrumKey]);
if (spectrumPeaks == null)
throw new IOException(string.Format(Resources.CachedLibrary_LoadSpectrum_Library_entry_not_found__0__, spectrumKey));
return new SpectrumPeaksInfo(spectrumPeaks);
}
protected abstract SpectrumPeaksInfo.MI[] ReadSpectrum(TInfo info);
public override LibraryChromGroup LoadChromatogramData(object spectrumKey)
{
return ReadChromatogram(_libraryEntries[(int) spectrumKey]);
}
protected virtual LibraryChromGroup ReadChromatogram(TInfo info)
{
return null;
}
public override bool TryGetRetentionTimes(LibKey key, MsDataFileUri filePath, out double[] retentionTimes)
{
// By default, no retention time information is available
retentionTimes = null;
return false;
}
public override bool TryGetRetentionTimes(MsDataFileUri filePath, out LibraryRetentionTimes retentionTimes)
{
// By default, no retention time information is available
retentionTimes = null;
return false;
}
public override bool TryGetRetentionTimes(int fileIndex, out LibraryRetentionTimes retentionTimes)
{
// By default, no retention time information is available
retentionTimes = null;
return false;
}
public override bool TryGetIrts(out LibraryRetentionTimes retentionTimes)
{
// By default, no iRT information is available
retentionTimes = null;
return false;
}
public override bool TryGetIonMobilityInfos(LibKey key, MsDataFileUri filePath, out IonMobilityAndCCS[] ionMobilities)
{
// By default, no ion mobility information is available
ionMobilities = null;
return false;
}
public override bool TryGetIonMobilityInfos(LibKey[] targetIons, MsDataFileUri filePath, out LibraryIonMobilityInfo ionMobilities)
{
// By default, no ion mobility information is available
ionMobilities = null;
return false;
}
public override bool TryGetIonMobilityInfos(LibKey[] targetIons, int fileIndex, out LibraryIonMobilityInfo ionMobilities)
{
// By default, no ion mobility information is available
ionMobilities = null;
return false;
}
public override bool TryGetIonMobilityInfos(LibKey[] targetIons, out LibraryIonMobilityInfo ionMobilities)
{
// By default, no ion mobility information is available
ionMobilities = null;
return false;
}
public override IEnumerable<SpectrumInfoLibrary> GetSpectra(LibKey key, IsotopeLabelType labelType, LibraryRedundancy redundancy)
{
// This base class only handles best match spectra
if (redundancy == LibraryRedundancy.best)
{
int i = FindEntry(key);
if (i != -1)
{
yield return new SpectrumInfoLibrary(this, labelType, i)
{
SpectrumHeaderInfo = CreateSpectrumHeaderInfo(_libraryEntries[i])
};
}
}
}
public override int? FileCount
{
get { return null; }
}
public override int SpectrumCount
{
get { return _libraryEntries == null ? 0 : _libraryEntries.Count; }
}
public override IEnumerable<LibKey> Keys
{
get
{
if (IsLoaded)
foreach (var entry in _libraryEntries)
yield return entry.Key;
}
}
protected IEnumerable<TInfo> LibraryEntriesWithSequences(IEnumerable<Target> peptideSequences)
{
return peptideSequences.SelectMany(LibraryEntriesWithSequence);
}
protected IEnumerable<TInfo> LibraryEntriesWithSequence(Target target)
{
return _libraryEntries.ItemsMatching(new LibKey(target, Adduct.EMPTY).LibraryKey, false);
}
// ReSharper disable PossibleMultipleEnumeration
protected int FindFileInList(MsDataFileUri sourceFile, IEnumerable<string> fileNames)
{
if (fileNames == null)
{
return -1;
}
string sourceFileToString = sourceFile.ToString();
int iFile = 0;
foreach (var fileName in fileNames)
{
if (fileName.Equals(sourceFileToString))
{
return iFile;
}
iFile++;
}
string baseName = sourceFile.GetFileNameWithoutExtension();
iFile = 0;
foreach (var fileName in fileNames)
{
try
{
if (MeasuredResults.IsBaseNameMatch(baseName, Path.GetFileNameWithoutExtension(fileName)))
{
return iFile;
}
}
catch (Exception)
{
// Ignore: Invalid filename
}
iFile++;
}
return -1;
}
// ReSharper restore PossibleMultipleEnumeration
}
public sealed class LibraryRetentionTimes : IRetentionTimeProvider
{
private readonly TargetMap<Tuple<TimeSource, double[]>> _dictPeptideRetentionTimes;
public LibraryRetentionTimes(string path, IDictionary<Target, Tuple<TimeSource, double[]>> dictPeptideRetentionTimes)
{
Name = path;
_dictPeptideRetentionTimes = new TargetMap<Tuple<TimeSource, double[]>>(dictPeptideRetentionTimes);
if (_dictPeptideRetentionTimes.Count == 0)
{
MinRt = MaxRt = 0;
}
else
{
MinRt = _dictPeptideRetentionTimes.SelectMany(p => p.Value.Item2).Min();
MaxRt = _dictPeptideRetentionTimes.SelectMany(p => p.Value.Item2).Max();
}
var listStdev = new List<double>();
foreach (Tuple<TimeSource, double[]> times in _dictPeptideRetentionTimes.Values)
{
if (times.Item2.Length < 2)
continue;
var statTimes = new Statistics(times.Item2);
listStdev.Add(statTimes.StdDev());
}
var statStdev = new Statistics(listStdev);
MeanStdev = statStdev.Mean();
}
public string Name { get; private set; }
public double MinRt { get; private set; }
public double MaxRt { get; private set; }
public double MeanStdev { get; private set; }
/// <summary>
/// Returns all retention times for spectra that were identified to a
/// specific modified peptide sequence.
/// </summary>
public double[] GetRetentionTimes(Target sequence)
{
Tuple<TimeSource, double[]> retentionTimes;
if (_dictPeptideRetentionTimes.TryGetValue(sequence, out retentionTimes))
return retentionTimes.Item2;
return new double[0];
}
/// <summary>
/// Return the average retention time for spectra that were identified to a
/// specific modified peptide sequence, with filtering applied in an attempt
/// to avoid peptides eluting a second time near the end of the gradient.
/// </summary>
public double? GetRetentionTime(Target sequence)
{
double[] retentionTimes = GetRetentionTimes(sequence);
if (retentionTimes.Length == 0)
return null;
if (retentionTimes.Length == 1)
return retentionTimes[0];
double meanTimes = retentionTimes[0];
// Anything 3 times the mean standard deviation away from the mean is suspicious
double maxDelta = MeanStdev*3;
for (int i = 1; i < retentionTimes.Length; i++)
{
double time = retentionTimes[i];
double delta = time - meanTimes;
// If the time is more than the max delta from the other times, and closer
// to the end than to the other times, then do not include it or anything
// after it.
if (delta > maxDelta && delta > MaxRt - time)
{
double[] subsetTimes = new double[i];
Array.Copy(retentionTimes, subsetTimes, i);
retentionTimes = subsetTimes;
break;
}
// Adjust the running mean.
meanTimes += (time - meanTimes)/(i+1);
}
var statTimes = new Statistics(retentionTimes);
return statTimes.Median();
}
public TimeSource? GetTimeSource(Target sequence)
{
Tuple<TimeSource, double[]> value;
if (_dictPeptideRetentionTimes.TryGetValue(sequence, out value))
{
return value.Item1;
}
return null;
}
public IEnumerable<MeasuredRetentionTime> PeptideRetentionTimes
{
get
{
return from sequence in _dictPeptideRetentionTimes.Keys
let time = GetRetentionTime(sequence)
where time.HasValue
select new MeasuredRetentionTime(sequence, time.Value, true);
}
}
public IDictionary<Target, double> GetFirstRetentionTimes()
{
var dict = new Dictionary<Target, double>();
foreach (var entry in _dictPeptideRetentionTimes)
{
if (entry.Value.Item2.Length == 0)
{
continue;
}
dict.Add(entry.Key, entry.Value.Item2.Min());
}
return dict;
}
}
public sealed class LibraryIonMobilityInfo : IIonMobilityInfoProvider
{
private readonly LibKeyMap<IonMobilityAndCCS[]> _dictLibKeyIonMobility;
public static LibraryIonMobilityInfo EMPTY = new LibraryIonMobilityInfo(String.Empty, false, new Dictionary<LibKey, IonMobilityAndCCS[]>());
public LibraryIonMobilityInfo(string path, bool supportMultipleConformers, IDictionary<LibKey, IonMobilityAndCCS[]> dict)
: this(path, supportMultipleConformers, new LibKeyMap<IonMobilityAndCCS[]>(
ImmutableList.ValueOf(dict.Values), dict.Keys.Select(key=>key.LibraryKey)))
{
}
public LibraryIonMobilityInfo(string path, bool supportMultipleConformers, LibKeyMap<IonMobilityAndCCS[]> dictLibKeyIonMobility)
{
Name = path ?? string.Empty;
SupportsMultipleConformers = supportMultipleConformers;
_dictLibKeyIonMobility = dictLibKeyIonMobility;
}
public string Name { get; private set; }
public bool SupportsMultipleConformers { get; private set; } // If false, average any redundancies (as with spectral libraries)
public bool IsEmpty { get { return _dictLibKeyIonMobility == null || _dictLibKeyIonMobility.Count == 0;} }
/// <summary>
/// Return the median measured CCS for spectra that were identified with a
/// specific modified peptide sequence and charge state.
/// </summary>
public double? GetLibraryMeasuredCollisionalCrossSection(LibKey chargedPeptide)
{
IonMobilityAndCCS[] ionMobilities;
if ((!_dictLibKeyIonMobility.TryGetValue(chargedPeptide, out ionMobilities)) || (ionMobilities == null))
return null;
double? ccs = null;
var ccsValues = Array.FindAll(ionMobilities, im => im.HasCollisionalCrossSection);
if (ccsValues.Any())
{
ccs = new Statistics(ccsValues.Select(im => im.CollisionalCrossSectionSqA.Value)).Median();
}
return ccs;
}
/// <summary>
/// Return the median measured ion mobility for spectra that were identified with a
/// specific modified peptide sequence and charge state. Prefer to use median CCS
/// when possible, and calculate IM from that. If only IM values are available, convert
/// to CCS if possible.
/// CONSIDER: when we support multiple conformers, is there maybe some difference magnitude at which we should not be averaging (based on resolving power maybe)?
/// </summary>
public IonMobilityAndCCS GetLibraryMeasuredIonMobilityAndCCS(LibKey chargedPeptide, double mz, IIonMobilityFunctionsProvider ionMobilityFunctionsProvider)
{
IonMobilityAndCCS[] ionMobilities;
if ((!_dictLibKeyIonMobility.TryGetValue(chargedPeptide, out ionMobilities)) || (ionMobilities == null))
return IonMobilityAndCCS.EMPTY;
IonMobilityValue ionMobility = IonMobilityValue.EMPTY;
double? ccs = null;
var ionMobilityInfos = ionMobilityFunctionsProvider != null ? Array.FindAll(ionMobilities, im => im.HasCollisionalCrossSection) : null;
if (ionMobilityInfos != null && ionMobilityInfos.Any() && ionMobilityFunctionsProvider.ProvidesCollisionalCrossSectionConverter)
{
// Use median CCS to calculate an ion mobility value
ccs = new Statistics(ionMobilityInfos.Select(im => im.CollisionalCrossSectionSqA.Value)).Median(); // Median is more tolerant of errors than Average
ionMobility = IonMobilityValue.GetIonMobilityValue(ionMobilityFunctionsProvider.IonMobilityFromCCS(ccs.Value, mz, chargedPeptide.Charge).Mobility,
ionMobilityFunctionsProvider.IonMobilityUnits);
}
else
{
// Use median ion mobility, convert to CCS if available
ionMobilityInfos = Array.FindAll(ionMobilities, dt => dt.HasIonMobilityValue);
if (ionMobilityInfos.Any())
{
var units = ionMobilityInfos.First().IonMobility.Units;
var medianValue = new Statistics(ionMobilityInfos.Select(im => im.IonMobility.Mobility.Value)).Median(); // Median is more tolerant of errors than Average
ionMobility = IonMobilityValue.GetIonMobilityValue(medianValue, units);
if (ionMobilityFunctionsProvider != null && ionMobilityFunctionsProvider.ProvidesCollisionalCrossSectionConverter)
{
ccs = ionMobilityFunctionsProvider.CCSFromIonMobility(ionMobility, mz, chargedPeptide.Charge);
}
else // No mobility -> conversion provided, just return median CCS
{
var ccsValues = ionMobilityInfos.Where(im => im.HasCollisionalCrossSection)
.Select(im => im.CollisionalCrossSectionSqA.Value).ToArray();
if (ccsValues.Any())
{
ccs = new Statistics(ccsValues).Median(); // Median is more tolerant of errors than Average
}
}
}
}
if (!ionMobility.HasValue)
return IonMobilityAndCCS.EMPTY;
var highEnergyDriftTimeOffsetMsec = new Statistics(ionMobilityInfos.Where(im => im.HighEnergyIonMobilityValueOffset.HasValue).Select(im => im.HighEnergyIonMobilityValueOffset.Value)).Median(); // Median is more tolerant of errors than Average
return IonMobilityAndCCS.GetIonMobilityAndCCS(ionMobility, ccs, highEnergyDriftTimeOffsetMsec);
}
public IDictionary<LibKey, IonMobilityAndCCS[]> GetIonMobilityDict()
{
return _dictLibKeyIonMobility.AsDictionary();
}
}
public abstract class LibrarySpec : XmlNamedElement
{
public static readonly PeptideRankId PEP_RANK_COPIES =
new PeptideRankId(@"Spectrum count", () => Resources.LibrarySpec_PEP_RANK_COPIES_Spectrum_count);
public static readonly PeptideRankId PEP_RANK_TOTAL_INTENSITY =
new PeptideRankId(@"Total intensity", () => Resources.LibrarySpec_PEP_RANK_TOTAL_INTENSITY_Total_intensity);
public static readonly PeptideRankId PEP_RANK_PICKED_INTENSITY =
new PeptideRankId(@"Picked intensity", () => Resources.LibrarySpec_PEP_RANK_PICKED_INTENSITY_Picked_intensity);
public static LibrarySpec CreateFromPath(string name, string path)
{
if (PathEx.HasExtension(path, BiblioSpecLiteSpec.EXT))
return new BiblioSpecLiteSpec(name, path);
else if (PathEx.HasExtension(path, BiblioSpecLibSpec.EXT))
return new BiblioSpecLibSpec(name, path);
else if (PathEx.HasExtension(path, ChromatogramLibrarySpec.EXT))
return new ChromatogramLibrarySpec(name, path);
else if (PathEx.HasExtension(path, XHunterLibSpec.EXT))
return new XHunterLibSpec(name, path);
else if (PathEx.HasExtension(path, NistLibSpec.EXT))
return new NistLibSpec(name, path);
else if (PathEx.HasExtension(path, SpectrastSpec.EXT))
return new SpectrastSpec(name, path);
else if (PathEx.HasExtension(path, MidasLibSpec.EXT))
return new MidasLibSpec(name, path);
else if (PathEx.HasExtension(path, EncyclopeDiaSpec.EXT))
return new EncyclopeDiaSpec(name, path);
return null;
}
protected LibrarySpec(string name, string path)
: base(name)
{
FilePath = path;
UseExplicitPeakBounds = true;
}
[Track]
public AuditLogPath FilePathAuditLog
{
get { return AuditLogPath.Create(FilePath); }
}
public string FilePath { get; private set; }
/// <summary>
/// Returns the filter string to be used for finding a library of this type.
/// </summary>
public abstract string Filter { get; }
/// <summary>
/// True if this library spec was created in order to open the current document
/// only, and should not be stored long term in the global settings.
/// </summary>
public bool IsDocumentLocal { get; private set; }
/// <summary>
/// True if this the document-specific library spec, and should not be stored
/// in the global settings.
/// </summary>
public bool IsDocumentLibrary { get; private set; }
public abstract Library LoadLibrary(ILoadMonitor loader);
public abstract IEnumerable<PeptideRankId> PeptideRankIds { get; }
[Track(defaultValues:typeof(DefaultValuesTrue))]
public bool UseExplicitPeakBounds { get; private set; }
#region Property change methods
public LibrarySpec ChangeFilePath(string prop)
{
return ChangeProp(ImClone(this), im => im.FilePath = prop);
}
public LibrarySpec ChangeDocumentLocal(bool prop)
{
return ChangeProp(ImClone(this), im => im.IsDocumentLocal = prop);
}
public LibrarySpec ChangeDocumentLibrary(bool prop)
{
return ChangeProp(ImClone(this), im => im.IsDocumentLibrary = prop).ChangeDocumentLocal(prop);
}
public LibrarySpec ChangeUseExplicitPeakBounds(bool prop)
{
return ChangeProp(ImClone(this), im => im.UseExplicitPeakBounds = prop);
}
#endregion
#region Implementation of IXmlSerializable
/// <summary>
/// For XML serialization
/// </summary>
protected LibrarySpec()
{
}
private enum ATTR
{
file_path,
use_explicit_peak_bounds
}
public override void ReadXml(XmlReader reader)
{
// Read tag attributes
base.ReadXml(reader);
FilePath = reader.GetAttribute(ATTR.file_path);
UseExplicitPeakBounds = reader.GetBoolAttribute(ATTR.use_explicit_peak_bounds, true);
// Consume tag
reader.Read();
}
public override void WriteXml(XmlWriter writer)
{
if (IsDocumentLocal)
throw new InvalidOperationException(Resources.LibrarySpec_WriteXml_Document_local_library_specs_cannot_be_persisted_to_XML);
if (IsDocumentLibrary)
throw new InvalidOperationException(Resources.LibrarySpec_WriteXml_Document_library_specs_cannot_be_persisted_to_XML_);
// Write tag attributes
base.WriteXml(writer);
writer.WriteAttributeString(ATTR.file_path, FilePath);
writer.WriteAttribute(ATTR.use_explicit_peak_bounds, UseExplicitPeakBounds, true);
}
#endregion
#region object overrides
public bool Equals(LibrarySpec other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return base.Equals(other) &&
Equals(other.FilePath, FilePath) &&
other.IsDocumentLocal.Equals(IsDocumentLocal) &&
other.IsDocumentLibrary.Equals(IsDocumentLibrary) &&
other.UseExplicitPeakBounds.Equals(UseExplicitPeakBounds);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as LibrarySpec);
}
public override int GetHashCode()
{
unchecked
{
int result = base.GetHashCode();
result = (result*397) ^ FilePath.GetHashCode();
result = (result*397) ^ IsDocumentLocal.GetHashCode();
result = (result*397) ^ IsDocumentLibrary.GetHashCode();
return result;
}
}
#endregion
}
/// <summary>
/// Identity class for a type peptide ranking, with values for
/// displaying in the user interface, and persisting to XML.
/// </summary>
public sealed class PeptideRankId : IAuditLogObject
{
public static readonly PeptideRankId PEPTIDE_RANK_NONE = new PeptideRankId(string.Empty, () => string.Empty);
private Func<string> _labelFunc;
public PeptideRankId(string value, Func<string> labelFunc)
{
Value = value;
_labelFunc = labelFunc;
}
/// <summary>
/// Display text for user interface.
/// </summary>
public string Label { get { return _labelFunc(); } }
/// <summary>
/// Name for us in XML.
/// </summary>
public string Value { get; private set; }
public override string ToString() { return Label; }
public string AuditLogText { get { return Label; } }
public bool IsName { get { return true; } }
private bool Equals(PeptideRankId other)
{
return string.Equals(Label, other.Label) && string.Equals(Value, other.Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is PeptideRankId && Equals((PeptideRankId) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Label != null ? Label.GetHashCode() : 0) * 397) ^ (Value != null ? Value.GetHashCode() : 0);
}
}
}
public abstract class SpectrumHeaderInfo : Immutable, IXmlSerializable
{
protected SpectrumHeaderInfo(string libraryName)
{
LibraryName = libraryName;
}
public string LibraryName { get; private set; }
public SpectrumHeaderInfo ChangeLibraryName(string prop)
{
return ChangeProp(ImClone(this), im => im.LibraryName = prop);
}
/// <summary>
/// Value used in ranking peptides.
/// </summary>
/// <param name="rankId">Indentifier of the value to return</param>
/// <returns>The value to use in ranking</returns>
public virtual float GetRankValue(PeptideRankId rankId)
{
// If super class has not provided a number of copies, return 1.
if (ReferenceEquals(rankId, LibrarySpec.PEP_RANK_COPIES))
return 1;
return float.MinValue;
}
public abstract IEnumerable<KeyValuePair<PeptideRankId, string>> RankValues { get; }
public string Protein { get; protected set; } // Some .blib and .clib files provide a protein accession (or Molecule List Name for small molecules)
#region Implementation of IXmlSerializable
/// <summary>
/// For XML serialization
/// </summary>
protected SpectrumHeaderInfo()
{
}
private enum ATTR
{
library_name,
protein
}
public XmlSchema GetSchema()
{
return null;
}
public virtual void ReadXml(XmlReader reader)
{
// Read tag attributes
LibraryName = reader.GetAttribute(ATTR.library_name);
Protein = reader.GetAttribute(ATTR.protein);
}
public virtual void WriteXml(XmlWriter writer)
{
// Write tag attributes
writer.WriteAttributeString(ATTR.library_name, LibraryName);
writer.WriteAttributeIfString(ATTR.protein, Protein);
}
#endregion
#region object overrides
public bool Equals(SpectrumHeaderInfo obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return Equals(obj.LibraryName, LibraryName) &&
Equals(obj.Protein, Protein);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (SpectrumHeaderInfo)) return false;
return Equals((SpectrumHeaderInfo) obj);
}
public override int GetHashCode()
{
return LibraryName.GetHashCode();
}
#endregion
}
public sealed class TransitionLibInfo
{
public TransitionLibInfo(int rank, float intensity)
{
Rank = rank;
Intensity = intensity;
}
public int Rank { get; private set; }
public float Intensity { get; private set; }
#region object overrides
public bool Equals(TransitionLibInfo obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.Intensity == Intensity && obj.Rank == Rank;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (TransitionLibInfo)) return false;
return Equals((TransitionLibInfo) obj);
}
public override int GetHashCode()
{
unchecked
{
return (Intensity.GetHashCode()*397) ^ Rank;
}
}
#endregion
}
public sealed class SpectrumPeaksInfo
{
public SpectrumPeaksInfo(MI[] spectrum)
{
Peaks = spectrum;
}
/// <summary>
/// This array must be highly performant. Making this class
/// <see cref="Immutable"/>, and using a <see cref="ReadOnlyCollection{T}"/>
/// caused iteration of this list to show up as a hotspot in
/// a profiler.
/// </summary>
public MI[] Peaks { get; private set; }
public IEnumerable<double> MZs
{
get
{
foreach (var mi in Peaks)
yield return mi.Mz;
}
}
public IEnumerable<double> Intensities
{
get
{
foreach (var mi in Peaks)
yield return mi.Intensity;
}
}
public IEnumerable<IEnumerable<SpectrumPeakAnnotation>> Annotations
{
get
{
foreach (var mi in Peaks)
yield return mi.Annotations;
}
}
private bool Equals(SpectrumPeaksInfo other)
{
return ArrayUtil.EqualsDeep(Peaks, other.Peaks);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is SpectrumPeaksInfo other && Equals(other);
}
public override int GetHashCode()
{
return (Peaks != null ? Peaks.GetHashCode() : 0);
}
public struct MI
{
private bool _notQuantitative;
private List<SpectrumPeakAnnotation> _annotations; // A peak may have multiple annotations
public double Mz { get; set; }
public float Intensity { get; set; }
public bool Quantitative {
get { return !_notQuantitative; }
set { _notQuantitative = !value; }
}
public List<SpectrumPeakAnnotation> Annotations
{
get { return _annotations; }
set { _annotations = value; }
}
public MI ChangeAnnotations(List<SpectrumPeakAnnotation> newAnnotations)
{
if (!CollectionUtil.EqualsDeep(newAnnotations, Annotations))
{
// Because this is a struct, it does not need to be cloned
// This operation will not affect the memory of the original object
var result = this;
result._annotations = newAnnotations;
return result;
}
return this;
}
public MI ChangeIntensity(float intensity)
{
var result = this;
result.Intensity = intensity;
return result;
}
public SpectrumPeakAnnotation AnnotationsFirstOrDefault
{
get { return Annotations == null || Annotations.Count == 0 ?
SpectrumPeakAnnotation.EMPTY :
Annotations[0] ?? SpectrumPeakAnnotation.EMPTY; }
}
public IEnumerable<SpectrumPeakAnnotation> GetAnnotationsEnumerator()
{
if (Annotations == null || Annotations.Count == 0)
{
yield return SpectrumPeakAnnotation.EMPTY;
}
else
{
foreach (var spectrumPeakAnnotation in Annotations)
{
yield return spectrumPeakAnnotation ?? SpectrumPeakAnnotation.EMPTY;
}
}
}
public CustomIon AnnotationsAggregateDescriptionIon
{
get
{
if (Annotations != null)
{
var aggregateName = AnnotationsFirstOrDefault.Ion.Name ?? string.Empty;
var nAnnotations = Annotations.Count;
for (var i = 1; i < nAnnotations; i++)
{
var name = Annotations[i].Ion.Name;
if (!string.IsNullOrEmpty(name))
{
aggregateName += @"/" + name;
}
}
if (!string.IsNullOrEmpty(aggregateName))
{
return AnnotationsFirstOrDefault.Ion.ChangeName(aggregateName);
}
}
return AnnotationsFirstOrDefault.Ion;
}
}
public bool Equals(MI other)
{
return _notQuantitative == other._notQuantitative &&
ArrayUtil.EqualsDeep(_annotations, other._annotations) && Mz.Equals(other.Mz) &&
Intensity.Equals(other.Intensity);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is MI other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = _notQuantitative.GetHashCode();
hashCode = (hashCode * 397) ^ (_annotations != null ? _annotations.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Mz.GetHashCode();
hashCode = (hashCode * 397) ^ Intensity.GetHashCode();
return hashCode;
}
}
}
}
public class SmallMoleculeLibraryAttributes : IEquatable<SmallMoleculeLibraryAttributes>
{
public static SmallMoleculeLibraryAttributes EMPTY = new SmallMoleculeLibraryAttributes(null, null, null, null, null, null);
public static int nItems = 4;
public bool IsEmpty
{
get
{
return ReferenceEquals(this, EMPTY);
}
}
// Helper for library caches
public static SmallMoleculeLibraryAttributes FromBytes(byte[] buf, int offset)
{
var itemLengths = new int[nItems];
var itemStarts = new int[nItems];
for (var i = 0; i < nItems; i++)
{
// read item length
itemLengths[i] = Library.GetInt32(buf, i, offset);
itemStarts[i] = i == 0 ? offset + nItems * sizeof(int) : itemStarts[i - 1] + itemLengths[i - 1];
}
return Create(
Encoding.UTF8.GetString(buf, itemStarts[0], itemLengths[0]),
Encoding.UTF8.GetString(buf, itemStarts[1], itemLengths[1]),
Encoding.UTF8.GetString(buf, itemStarts[2], itemLengths[2]),
Encoding.UTF8.GetString(buf, itemStarts[3], itemLengths[3]));
}
public static void ParseMolecularFormulaOrMassesString(string molecularFormulaOrMassesString,
out string molecularFormula, out TypedMass? massMono, out TypedMass? massAverage)
{
if (molecularFormulaOrMassesString != null && molecularFormulaOrMassesString.Contains(CustomMolecule.MASS_SPLITTER))
{
var parts = molecularFormulaOrMassesString.Split(CustomMolecule.MASS_SPLITTER); // We didn't have a formula so we saved masses
massMono = new TypedMass(double.Parse(parts[0], CultureInfo.InvariantCulture), MassType.Monoisotopic);
massAverage = new TypedMass(double.Parse(parts[1], CultureInfo.InvariantCulture), MassType.Average);
molecularFormula = null;
}
else
{
massMono = null;
massAverage = null;
molecularFormula = molecularFormulaOrMassesString;
}
}
public static string FormatChemicalFormulaOrMassesString(string chemicalFormula, TypedMass? massMono, TypedMass? massAverage) // For serialization - represents formula or masses, depending on what's available
{
if (!string.IsNullOrEmpty(chemicalFormula))
{
return chemicalFormula;
}
if (massMono != null && massAverage != null)
{
Assume.IsTrue(massMono.Value.IsMonoIsotopic());
Assume.IsTrue(massAverage.Value.IsAverage());
return CustomMolecule.FormattedMasses(massMono.Value.Value, massAverage.Value.Value); // Format as dd.ddd/dd.ddd
}
return string.Empty;
}
public static byte[] ToBytes(SmallMoleculeLibraryAttributes attributes)
{
attributes = attributes ?? EMPTY;
// Encode as <length><item><length><item>etc
var items = new List<byte[]>
{
Encoding.UTF8.GetBytes(attributes.MoleculeName ?? string.Empty),
Encoding.UTF8.GetBytes(attributes.ChemicalFormulaOrMassesString ?? string.Empty), // If no formula provided, encode monoMass and averageMass instead
Encoding.UTF8.GetBytes(attributes.InChiKey ?? string.Empty),
Encoding.UTF8.GetBytes(attributes.OtherKeys ?? string.Empty)
};
Assume.IsTrue(Equals(nItems,items.Count));
var results = new byte[items.Sum(item => item.Length + sizeof(int))];
var index = 0;
foreach (var item in items)
{
Array.Copy(BitConverter.GetBytes(item.Length), 0, results, index, sizeof(int));
index += sizeof(int);
}
foreach (var item in items)
{
Array.Copy(item, 0, results, index, item.Length);
index += item.Length;
}
return results;
}
public static SmallMoleculeLibraryAttributes Create(string moleculeName, string chemicalFormula, TypedMass? massMono, TypedMass? massAverage,
string inChiKey, string otherKeys)
{
if (string.IsNullOrEmpty(moleculeName) && string.IsNullOrEmpty(chemicalFormula) &&
massMono == null && massAverage == null &&
string.IsNullOrEmpty(inChiKey) && string.IsNullOrEmpty(otherKeys))
{
return EMPTY;
}
return new SmallMoleculeLibraryAttributes(moleculeName, chemicalFormula, massMono, massAverage, inChiKey, otherKeys);
}
public static SmallMoleculeLibraryAttributes Create(string moleculeName, string chemicalFormulaOrMassesString,
string inChiKey, IDictionary<string, string> otherKeys)
{
return Create(moleculeName, chemicalFormulaOrMassesString, inChiKey, otherKeys == null ? string.Empty : string.Join(@"\t", otherKeys.Select(kvp => kvp.Key + @":" + kvp.Value)));
}
public static SmallMoleculeLibraryAttributes Create(string moleculeName, string chemicalFormulaOrMassesString,
string inChiKey, string otherKeys)
{
ParseMolecularFormulaOrMassesString(chemicalFormulaOrMassesString,
out var chemicalFormula, out var massMono, out var massAverage);
if (string.IsNullOrEmpty(moleculeName) && string.IsNullOrEmpty(chemicalFormula) &&
massMono == null && massAverage == null &&
string.IsNullOrEmpty(inChiKey) && string.IsNullOrEmpty(otherKeys))
{
return EMPTY;
}
return new SmallMoleculeLibraryAttributes(moleculeName, chemicalFormula, massMono, massAverage, inChiKey, otherKeys);
}
private SmallMoleculeLibraryAttributes(string moleculeName, string chemicalFormula, TypedMass? massMono, TypedMass? massAverage, string inChiKey, string otherKeys)
{
MoleculeName = moleculeName;
ChemicalFormulaOrMassesString = FormatChemicalFormulaOrMassesString(chemicalFormula, massMono, massAverage); // If no formula provided, encode monoMass and averageMass instead
InChiKey = inChiKey;
OtherKeys = otherKeys;
}
public string MoleculeName { get; private set; }
public string ChemicalFormulaOrMassesString { get; private set; } // If no formula provided, encodes monoMass and averageMass instead as <mono>-slash-<average>
public string ChemicalFormula => ChemicalFormulaOrMassesString != null && !ChemicalFormulaOrMassesString.Contains(CustomMolecule.MASS_SPLITTER) // Returns null if ChemicalFormulaOrMassesString encodes masses instead of formula
? ChemicalFormulaOrMassesString
: null;
public string InChiKey { get; private set; }
public string OtherKeys { get; private set; }
public string GetPreferredKey()
{
return CreateMoleculeID().PrimaryAccessionValue ?? MoleculeName;
}
public string Validate()
{
return string.IsNullOrEmpty(ChemicalFormulaOrMassesString) ||
(string.IsNullOrEmpty(MoleculeName) && string.IsNullOrEmpty(InChiKey) && string.IsNullOrEmpty(OtherKeys))
? Resources.SmallMoleculeLibraryAttributes_Validate_A_small_molecule_is_defined_by_a_chemical_formula_and_at_least_one_of_Name__InChiKey__or_other_keys__HMDB_etc_
: null;
}
public MoleculeAccessionNumbers CreateMoleculeID()
{
return new MoleculeAccessionNumbers(OtherKeys, InChiKey);
}
public List<KeyValuePair<string,string>> LocalizedKeyValuePairs
{
get
{
var smallMolLines = new List<KeyValuePair<string, string>>();
if (!string.IsNullOrEmpty(MoleculeName))
{
smallMolLines.Add(new KeyValuePair<string, string> (Resources.SmallMoleculeLibraryAttributes_KeyValuePairs_Name, MoleculeName));
}
ParseMolecularFormulaOrMassesString(ChemicalFormulaOrMassesString, out var chemicalFormula, out var massMono, out var massAverage);
if (!string.IsNullOrEmpty(chemicalFormula))
{
smallMolLines.Add(new KeyValuePair<string, string> (Resources.SmallMoleculeLibraryAttributes_KeyValuePairs_Formula, chemicalFormula));
}
if (massMono != null)
{
smallMolLines.Add(new KeyValuePair<string, string>(Resources.SmallMoleculeLibraryAttributes_KeyValuePairs_Monoisotopic_mass, massMono.ToString()));
}
if (massAverage != null)
{
smallMolLines.Add(new KeyValuePair<string, string>(Resources.SmallMoleculeLibraryAttributes_KeyValuePairs_Average_mass, chemicalFormula));
}
if (!string.IsNullOrEmpty(InChiKey))
{
smallMolLines.Add(new KeyValuePair<string, string> (Resources.SmallMoleculeLibraryAttributes_KeyValuePairs_InChIKey, InChiKey));
}
if (!string.IsNullOrEmpty(OtherKeys))
{
// Add a separate line for each molecule accession number
var accessionNumDict = MoleculeAccessionNumbers.FormatAccessionNumbers(OtherKeys);
smallMolLines.AddRange(accessionNumDict);
}
return smallMolLines;
}
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((SmallMoleculeLibraryAttributes)obj);
}
public bool Equals(SmallMoleculeLibraryAttributes other)
{
if (other == null)
return false;
return Equals(MoleculeName, other.MoleculeName) &&
Equals(ChemicalFormulaOrMassesString, other.ChemicalFormulaOrMassesString) &&
Equals(InChiKey, other.InChiKey) &&
Equals(OtherKeys, other.OtherKeys);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (MoleculeName != null ? MoleculeName.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (ChemicalFormulaOrMassesString != null ? ChemicalFormulaOrMassesString.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (InChiKey != null ? InChiKey.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (OtherKeys != null ? OtherKeys.GetHashCode() : 0);
return hashCode;
}
}
public override string ToString()
{
return GetPreferredKey();
}
}
/// <summary>
/// Transfer format for library spectra
/// </summary>
public class SpectrumMzInfo
{
public string SourceFile { get; set; }
public LibKey Key { get; set; }
public string Protein { get; set; } // Also used as Molecule List Name for small molecules
public SmallMoleculeLibraryAttributes SmallMoleculeLibraryAttributes { get { return Key.SmallMoleculeLibraryAttributes; } }
public IonMobilityAndCCS IonMobility { get; set; }
public double PrecursorMz { get; set; }
public double? RetentionTime { get; set; }
public IsotopeLabelType Label { get; set; }
public SpectrumPeaksInfo SpectrumPeaks { get; set; }
public List<IonMobilityAndRT> RetentionTimes { get; set; } // (File, RT, IM, IsBest)
public const double PRECURSOR_MZ_TOL = 0.001;
public class IonMobilityAndRT
{
public string SourceFile { get; private set; }
public IonMobilityAndCCS IonMobility { get; private set; }
public double? RetentionTime { get; private set; }
public bool IsBest { get; private set; }
public IonMobilityAndRT(string sourceFile, IonMobilityAndCCS ionMobility, double? retentionTime,
bool isBest)
{
SourceFile = sourceFile;
IonMobility = ionMobility;
RetentionTime = retentionTime;
IsBest = isBest;
}
}
/// <summary>
/// Combine two spectra, for when transition list import has alternating light-heavy transitions,
/// that need to be re-united with their groups at the end.
/// </summary>
public SpectrumMzInfo CombineSpectrumInfo(SpectrumMzInfo infoOther, out List<TransitionImportErrorInfo> spectrumErrors)
{
spectrumErrors = new List<TransitionImportErrorInfo>();
if (infoOther == null)
return this;
if ((PrecursorMz - infoOther.PrecursorMz) > PRECURSOR_MZ_TOL || !Equals(Label, infoOther.Label) ||
!Equals(Key, infoOther.Key))
{
for (int i = 0; i < infoOther.SpectrumPeaks.Peaks.Length; ++i)
{
spectrumErrors.Add(new TransitionImportErrorInfo(string.Format(Resources.SpectrumMzInfo_CombineSpectrumInfo_Two_incompatible_transition_groups_for_sequence__0___precursor_m_z__1__,
Key.Target,
Key.Target,
PrecursorMz),
null, null, null));
}
return this;
}
var peaks = SpectrumPeaks.Peaks;
var peaksOther = infoOther.SpectrumPeaks.Peaks;
var newPeaks = peaks.Concat(peaksOther).ToArray();
return new SpectrumMzInfo
{
SourceFile = infoOther.SourceFile,
Key = infoOther.Key,
Label = infoOther.Label,
PrecursorMz = infoOther.PrecursorMz,
IonMobility = infoOther.IonMobility,
RetentionTime = infoOther.RetentionTime,
SpectrumPeaks = new SpectrumPeaksInfo(newPeaks)
};
}
public static List<SpectrumMzInfo> RemoveDuplicateSpectra(List<SpectrumMzInfo> librarySpectra)
{
var uniqueSpectra = new List<SpectrumMzInfo>();
var spectraGroups = librarySpectra.GroupBy(spectrum => spectrum.Key);
foreach (var spectraGroup in spectraGroups)
{
var spectraGroupList = spectraGroup.ToList();
spectraGroupList.Sort(CompareSpectrumMzLabels);
uniqueSpectra.Add(spectraGroupList[0]);
}
return uniqueSpectra;
}
/// <summary>
/// Order by isotope label type (e.g. light, heavy, ...)
/// </summary>
public static int CompareSpectrumMzLabels(SpectrumMzInfo info1, SpectrumMzInfo info2)
{
return info1.Label.CompareTo(info2.Label);
}
public static List<SpectrumMzInfo> GetInfoFromLibrary(Library library)
{
var spectrumMzInfos = new List<SpectrumMzInfo>();
foreach (var key in library.Keys)
{
var info = library.GetSpectra(key, null, LibraryRedundancy.best).FirstOrDefault();
if (info == null)
{
throw new IOException(string.Format(Resources.SpectrumMzInfo_GetInfoFromLibrary_Library_spectrum_for_sequence__0__is_missing_, key.Target));
}
spectrumMzInfos.Add(new SpectrumMzInfo
{
SourceFile = info.FileName,
Key = key,
SpectrumPeaks = info.SpectrumPeaksInfo,
Protein = info.Protein
});
}
return spectrumMzInfos;
}
public static List<SpectrumMzInfo> MergeWithOverwrite(List<SpectrumMzInfo> originalSpectra, List<SpectrumMzInfo> overwriteSpectra)
{
var finalSpectra = new List<SpectrumMzInfo>(overwriteSpectra);
var dictOriginalSpectra = originalSpectra.ToDictionary(spectrum => spectrum.Key);
var dictOverwriteSpectra = overwriteSpectra.ToDictionary(spectrum => spectrum.Key);
finalSpectra.AddRange(from spectrum in dictOriginalSpectra where !dictOverwriteSpectra.ContainsKey(spectrum.Key) select spectrum.Value);
return finalSpectra;
}
}
public abstract class SpectrumInfo
{
public SpectrumInfo(IsotopeLabelType labelType, bool isBest)
{
LabelType = labelType;
IsBest = isBest;
}
protected bool Equals(SpectrumInfo other)
{
return Equals(LabelType, other.LabelType) && string.Equals(Name, other.Name) && IsBest == other.IsBest &&
Equals(SpectrumPeaksInfo, other.SpectrumPeaksInfo) &&
Equals(ChromatogramData, other.ChromatogramData);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((SpectrumInfo) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (LabelType != null ? LabelType.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ IsBest.GetHashCode();
hashCode = (hashCode * 397) ^ (SpectrumPeaksInfo != null ? SpectrumPeaksInfo.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (ChromatogramData != null ? ChromatogramData.GetHashCode() : 0);
return hashCode;
}
}
public IsotopeLabelType LabelType { get; protected set; }
public abstract string Name { get; }
public bool IsBest { get; protected set; }
public abstract SpectrumPeaksInfo SpectrumPeaksInfo { get; }
public abstract LibraryChromGroup ChromatogramData { get; }
}
public class SpectrumInfoLibrary : SpectrumInfo
{
private Library _library;
// Cache peaks and chromatograms to avoid loading every time
// CONSIDER: Synchronization required?
private SpectrumPeaksInfo _peaksInfo;
private LibraryChromGroup _chromGroup;
public SpectrumInfoLibrary(Library library, IsotopeLabelType labelType, object spectrumKey):
this(library, labelType, null, null, null, null, true, spectrumKey)
{
}
public SpectrumInfoLibrary(Library library, IsotopeLabelType labelType, string filePath,
double? retentionTime, IonMobilityAndCCS ionMobilityInfo, string protein, bool isBest, object spectrumKey) :
base(labelType, true)
{
_library = library;
LabelType = labelType;
SpectrumKey = spectrumKey;
FilePath = filePath;
RetentionTime = retentionTime;
IonMobilityInfo = ionMobilityInfo ?? IonMobilityAndCCS.EMPTY;
Protein = protein;
IsBest = isBest;
}
public object SpectrumKey { get; private set; }
public override string Name
{
get { return _library.Name; }
}
public override SpectrumPeaksInfo SpectrumPeaksInfo
{
get { return _peaksInfo = _peaksInfo ?? _library.LoadSpectrum(SpectrumKey); }
}
public override LibraryChromGroup ChromatogramData
{
get { return _chromGroup = _chromGroup ?? _library.LoadChromatogramData(SpectrumKey); }
}
public SpectrumHeaderInfo SpectrumHeaderInfo { get; set; }
public string FilePath { get; private set; }
public string FileName
{
get
{
try {
return Path.GetFileName(FilePath);
}
catch {
return FilePath;
}
}
}
public double? RetentionTime { get; set; }
public IonMobilityAndCCS IonMobilityInfo { get; private set; }
public string Protein { get; private set; } // Also used as Molecule List Name for small molecules
}
public class SpectrumInfoProsit : SpectrumInfo
{
public static readonly string NAME = @"Prosit";
private SpectrumPeaksInfo _peaksInfo;
public SpectrumInfoProsit(PrositMS2Spectra ms2Spectrum, TransitionGroupDocNode precursor, IsotopeLabelType labelType, int nce)
: base(labelType, true)
{
_peaksInfo = ms2Spectrum?.GetSpectrum(precursor).SpectrumPeaks;
Precursor = precursor;
NCE = nce;
}
public override string Name
{
get { return NAME; }
}
public override SpectrumPeaksInfo SpectrumPeaksInfo
{
get { return _peaksInfo; }
}
public override LibraryChromGroup ChromatogramData
{
get { return null; }
}
public TransitionGroupDocNode Precursor { get; }
public int NCE { get; }
}
public class LibraryChromGroup
{
private IList<ChromData> _chromDatas = ImmutableList.Empty<ChromData>();
public double StartTime { get; set; }
public double EndTime { get; set; }
public double RetentionTime { get; set; }
public double? CCS { get; set; }
public float[] Times { get; set; }
public IList<ChromData> ChromDatas { get { return _chromDatas; } set { _chromDatas = ImmutableList.ValueOf(value); } }
protected bool Equals(LibraryChromGroup other)
{
return ArrayUtil.EqualsDeep(_chromDatas, other._chromDatas) && StartTime.Equals(other.StartTime) &&
EndTime.Equals(other.EndTime) && RetentionTime.Equals(other.RetentionTime) &&
Equals(CCS, other.CCS) &&
ArrayUtil.EqualsDeep(Times, other.Times);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((LibraryChromGroup) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (_chromDatas != null ? _chromDatas.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ StartTime.GetHashCode();
hashCode = (hashCode * 397) ^ EndTime.GetHashCode();
hashCode = (hashCode * 397) ^ RetentionTime.GetHashCode();
hashCode = (hashCode * 397) ^ (CCS??0).GetHashCode();
hashCode = (hashCode * 397) ^ (Times != null ? Times.GetHashCode() : 0);
return hashCode;
}
}
public class ChromData
{
public double Mz { get; set; }
public double Height { get; set; }
public float[] Intensities { get; set; }
public Adduct Charge { get; set; }
public IonType IonType { get; set; }
public int Ordinal { get; set; }
public int MassIndex { get; set; }
public string FragmentName { get; set; } // Small molecule use
public IonMobilityValue IonMobility { get; set; }
protected bool Equals(ChromData other)
{
return Mz.Equals(other.Mz) && Height.Equals(other.Height) && Equals(Intensities, other.Intensities) &&
Charge == other.Charge && IonType == other.IonType && Ordinal == other.Ordinal &&
Equals(IonMobility, other.IonMobility) &&
Equals(FragmentName, other.FragmentName) &&
MassIndex == other.MassIndex;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((ChromData) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Mz.GetHashCode();
hashCode = (hashCode * 397) ^ Height.GetHashCode();
hashCode = (hashCode * 397) ^ (Intensities != null ? Intensities.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Charge.GetHashCode();
hashCode = (hashCode * 397) ^ (string.IsNullOrEmpty(FragmentName) ? 0 : FragmentName.GetHashCode());
hashCode = (hashCode * 397) ^ (int) IonType;
hashCode = (hashCode * 397) ^ Ordinal;
hashCode = (hashCode * 397) ^ MassIndex;
hashCode = (hashCode * 397) ^ (IonMobility != null ? IonMobility.GetHashCode() : 0);
return hashCode;
}
}
}
}
/// <summary>
/// Links to spectral library sources
/// </summary>
public sealed class LibraryLink
{
public static readonly LibraryLink PEPTIDEATLAS = new LibraryLink(@"PeptideAtlas", @"http://www.peptideatlas.org/speclib/");
public static readonly LibraryLink NIST = new LibraryLink(@"NIST", @"http://peptide.nist.gov/");
public static readonly LibraryLink GPM = new LibraryLink(@"GPM", @"ftp://ftp.thegpm.org/projects/xhunter/libs/");
private LibraryLink(string name, string href)
{
Name = name;
Link = href;
}
public string Name { get; private set; }
public string Link { get; private set; }
// This appears in stack traces when we report unhandled parsing issues
public override string ToString()
{
var result = new List<string>();
if (!string.IsNullOrEmpty(Name))
result.Add($@"LinkName: {Name} ");
if (!string.IsNullOrEmpty(Link))
result.Add($@"LinkURL: {Link} ");
return TextUtil.LineSeparate(result);
}
}
public sealed class LibraryFiles
{
private IEnumerable<string> _filePaths;
public IEnumerable<string> FilePaths
{
get { return _filePaths ?? (_filePaths = new List<string>()); }
set { _filePaths = value; }
}
}
/// <summary>
/// Some spectrum library details that can be displayed in a dialog box.
/// This can be the format of the library (e.g. BiblioSpec, SpectraST etc.),
/// a library revision (when available), number of peptides etc.
/// Optionally, appropriate links to spectral library sources can also be included.
/// </summary>
public sealed class LibraryDetails
{
private readonly IList<LibraryLink> _libLinks;
private IEnumerable<SpectrumSourceFileDetails> _dataFiles;
public LibraryDetails()
{
_libLinks = new List<LibraryLink>();
}
public void AddLink(LibraryLink link)
{
_libLinks.Add(link);
}
public string Id { get; set; }
// e.g. BiblioSpec, SpectraST etc.
public string Format { get; set; }
// library revision
public string Revision { get; set; }
// version of the program that generated the library
public string Version { get; set; }
public int SpectrumCount { get; set; }
public int UniquePeptideCount { get; set; }
public int TotalPsmCount { get; set; }
public IEnumerable<SpectrumSourceFileDetails> DataFiles
{
get { return _dataFiles ?? (_dataFiles = new List<SpectrumSourceFileDetails>()); }
set { _dataFiles = value; }
}
public IEnumerable<LibraryLink> LibLinks
{
get { return _libLinks; }
}
// This appears in stack traces when we report unhandled parsing issues
public override string ToString()
{
var lines = new List<string>();
if (!string.IsNullOrEmpty(Format))
lines.Add($@"Format: {Format}");
if (!string.IsNullOrEmpty(Id))
lines.Add($@"LSID: {Id}");
if (!string.IsNullOrEmpty(Revision))
lines.Add($@"FileRevision: {Revision}");
if (!string.IsNullOrEmpty(Version))
lines.Add($@"SchemaVersion: {Version}");
if (_dataFiles != null && _dataFiles.Any())
lines.AddRange(_dataFiles.Select(df => df.ToString()));
if (_libLinks != null && _libLinks.Any())
lines.AddRange(_libLinks.Select(link => link.ToString()));
return TextUtil.LineSeparate(lines);
}
}
/// <summary>
/// Key for use in dictionaries that store library header information in
/// memory.
/// </summary>
public struct LibKey
{
public static LibKey EMPTY = new LibKey(SmallMoleculeLibraryAttributes.EMPTY, Adduct.EMPTY);
public LibKey(LibraryKey libraryKey) : this()
{
LibraryKey = libraryKey;
}
public LibKey(string sequence, int charge) : this()
{
LibraryKey = (LibraryKey) CrosslinkSequenceParser.TryParseCrosslinkLibraryKey(sequence, charge)
?? new PeptideLibraryKey(sequence, charge);
}
public LibKey(SmallMoleculeLibraryAttributes attributes, Adduct adduct) : this()
{
LibraryKey = new MoleculeLibraryKey(attributes, adduct);
}
public LibKey(string primaryKey, Adduct adduct) : this()
{
if (adduct.IsProteomic)
{
LibraryKey = (LibraryKey)
CrosslinkSequenceParser.TryParseCrosslinkLibraryKey(primaryKey, adduct.AdductCharge)
?? new PeptideLibraryKey(primaryKey, adduct.AdductCharge);
}
else
{
LibraryKey = new MoleculeLibraryKey(SmallMoleculeLibraryAttributes.Create(primaryKey, null, null, string.Empty), adduct);
}
}
[Track]
public LibraryKey LibraryKey { get; private set; }
public LibKey(double precursorMz,
double? retentionTime = null)
: this() // TODO(bspratt) probably should add ion mobility
{
LibraryKey = new PrecursorLibraryKey(precursorMz, retentionTime);
}
public LibKey(Target target, Adduct adduct)
: this()
{
if (target.IsProteomic)
{
LibraryKey = (LibraryKey)
CrosslinkSequenceParser.TryParseCrosslinkLibraryKey(target.Sequence, adduct.AdductCharge)
?? new PeptideLibraryKey(target.Sequence, adduct.AdductCharge);
}
else
LibraryKey = new MoleculeLibraryKey(target.Molecule.GetSmallMoleculeLibraryAttributes(), adduct);
}
public LibKey(Target target, int charge) : this(target.Sequence, charge)
{
}
public bool IsProteomicKey { get { return LibraryKey is PeptideLibraryKey; } }
public bool IsSmallMoleculeKey { get { return LibraryKey is MoleculeLibraryKey; } }
public bool IsPrecursorKey { get { return LibraryKey is PrecursorLibraryKey; } }
public bool HasRetentionTime { get { return IsPrecursorKey && ((PrecursorLibraryKey)LibraryKey).RetentionTime.HasValue; } }
public string Sequence
{
get
{
var peptideKey = LibraryKey as PeptideLibraryKey;
return peptideKey == null ? null : peptideKey.ModifiedSequence;
}
}
public Target Target
{
get
{
return LibraryKey.Target;
}
}
public SmallMoleculeLibraryAttributes SmallMoleculeLibraryAttributes
{
get
{
var moleculeLibraryKey = LibraryKey as MoleculeLibraryKey;
return moleculeLibraryKey == null
? SmallMoleculeLibraryAttributes.EMPTY
: moleculeLibraryKey.SmallMoleculeLibraryAttributes;
}
}
public int Charge { get
{
return IsProteomicKey
? ((PeptideLibraryKey) LibraryKey).Charge
: (IsPrecursorKey ? 0 : ((MoleculeLibraryKey) LibraryKey).Adduct.AdductCharge);
} }
public Adduct Adduct
{
get
{
return LibraryKey.Adduct;
}
}
public bool IsModified { get
{
var key = LibraryKey as PeptideLibraryKey;
return key != null && key.HasModifications;
} }
public double? PrecursorMz
{
get
{
var key = LibraryKey as PrecursorLibraryKey;
return key != null ? key.Mz : default(double?);
}
}
public double? RetentionTime
{
get
{
var key = LibraryKey as PrecursorLibraryKey;
return key != null ? key.RetentionTime : default(double?);
}
}
public bool HasModifications
{
get
{
var peptideKey = LibraryKey as PeptideLibraryKey;
return peptideKey != null && peptideKey.HasModifications;
}
}
public int ModificationCount
{
get
{
var peptideKey = LibraryKey as PeptideLibraryKey;
return peptideKey != null ? peptideKey.ModificationCount : 0;
}
}
public static implicit operator LibraryKey(LibKey libKey)
{
return libKey.LibraryKey;
}
#region object overrides
public bool Equals(LibKey obj)
{
return LibraryKey.IsEquivalentTo(obj.LibraryKey);
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj.GetType() != typeof(LibKey)) return false;
return Equals((LibKey)obj); // N.B. for equality we ignore any small molecule metadata
}
public override int GetHashCode()
{
return LibraryKey.GetEquivalencyHashCode();
}
public override string ToString()
{
return LibraryKey.ToString();
}
#endregion
public void Write(Stream outStream)
{
LibraryKey.Write(outStream);
}
public static LibKey Read(ValueCache valueCache, Stream inStream)
{
return new LibKey(LibraryKey.Read(valueCache, inStream));
}
}
public class SpectrumSourceFileDetails
{
public SpectrumSourceFileDetails(string filePath, string idFilePath = null)
{
FilePath = filePath;
IdFilePath = idFilePath;
CutoffScores = new Dictionary<string, double?>();
BestSpectrum = 0;
MatchedSpectrum = 0;
}
public string FilePath { get; private set; }
public string IdFilePath { get; set; }
public Dictionary<string, double?> CutoffScores { get; private set; }
public int BestSpectrum { get; set; }
public int MatchedSpectrum { get; set; }
public override string ToString()
{
var result = new List<string>();
if (!string.IsNullOrEmpty(IdFilePath))
result.Add($@"IdFilePath: {IdFilePath}");
if (!string.IsNullOrEmpty(FilePath))
result.Add($@"FilePath: {FilePath}");
return TextUtil.LineSeparate(result);
}
}
}
| 1 | 14,649 | More proof that this check is needed always. | ProteoWizard-pwiz | .cs |
@@ -86,9 +86,7 @@ lbann_comm::~lbann_comm() {
}
}
#ifdef LBANN_HAS_ALUMINUM
- for (auto&& c : al_comms) {
- delete c.second;
- }
+ m_al_comms.clear();
allreduces::Finalize();
#endif
} | 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. <[email protected]>
//
// 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_comm .hpp .cpp - LBANN communication utilities
////////////////////////////////////////////////////////////////////////////////
#include "lbann/comm.hpp"
#include "lbann/utils/timer.hpp"
#include "lbann/utils/exception.hpp"
#include "mpi.h"
#include "omp.h"
#include <sstream>
#include <thread>
namespace lbann {
// Error utility macro
#ifdef LBANN_DEBUG
#define checkMPI(mpi_call) { \
const int status = mpi_call; \
if(status != MPI_SUCCESS) { \
char error_string[MPI_MAX_ERROR_STRING]; \
int error_string_len; \
MPI_Error_string(status, error_string, &error_string_len); \
std::cerr << "MPI error: " << std::string(error_string, error_string_len) << "\n"; \
std::cerr << "Error at " << __FILE__ << ":" << __LINE__ << "\n"; \
throw lbann_exception("MPI error"); \
} \
}
#else
#define checkMPI(status) status
#endif // #ifdef LBANN_DEBUG
lbann_comm::lbann_comm(int ppm, const El::mpi::Comm world) :
world_comm(world), grid(nullptr), procs_per_model(ppm), num_model_barriers(0),
num_intermodel_barriers(0), num_global_barriers(0), bytes_sent(0),
bytes_received(0) {
#ifdef LBANN_HAS_ALUMINUM
// Don't have argc/argv here, but MPI should already be init'd.
int argc_dummy = 0;
char** argv_dummy = nullptr;
allreduces::Initialize(argc_dummy, argv_dummy);
#endif
// Set up the initial model split
split_models(procs_per_model);
// Initialize node communicators
setup_node_comm();
procs_per_node = El::mpi::Size(node_comm);
rank_in_node = El::mpi::Rank(node_comm);
// Setup threads
setup_threads();
}
lbann_comm::~lbann_comm() {
delete grid;
El::mpi::Free(model_comm);
El::mpi::Free(intermodel_comm);
El::mpi::Free(node_comm);
for (auto&& buf_vec : collective_bufs) {
for (auto&& buf : buf_vec.second) {
delete[] buf;
}
}
#ifdef LBANN_HAS_ALUMINUM
for (auto&& c : al_comms) {
delete c.second;
}
allreduces::Finalize();
#endif
}
void lbann_comm::split_models(int ppm) {
int world_size = El::mpi::Size(get_world_comm());
procs_per_model = ppm;
if (ppm == 0) {
procs_per_model = world_size;
}
// Check if parameters are valid
if (procs_per_model > world_size) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: Not enough processes to create one model; procs_per_model: " +
std::to_string(procs_per_model) + " is larger than world_size: " +
std::to_string(world_size));
}
if (world_size % procs_per_model != 0) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: Procs per model does not divide total number of procs; procs_per_model: " +
std::to_string(procs_per_model) + " total number of procs (world size): " +
std::to_string(world_size));
}
num_models = world_size / procs_per_model;
model_rank = El::mpi::Rank(get_world_comm()) / procs_per_model;
rank_in_model = El::mpi::Rank(get_world_comm()) % procs_per_model;
// Initialize model and intermodel communicators
El::mpi::Split(get_world_comm(), model_rank, rank_in_model, model_comm);
El::mpi::Split(get_world_comm(), rank_in_model, model_rank,
intermodel_comm);
// Initialize Elemental grid
if (grid != nullptr) {
delete grid;
}
grid = new Grid(model_comm);
}
void lbann_comm::intermodel_sum_matrix(Mat& mat) {
bytes_sent += sizeof(DataType) * mat.Height() * mat.Width();
El::AllReduce(mat, intermodel_comm, El::mpi::SUM);
bytes_received += sizeof(DataType) * mat.Height() * mat.Width();
}
void lbann_comm::intermodel_sum_matrix(AbsDistMat& mat) {
allreduce(mat, intermodel_comm, El::mpi::SUM);
}
void lbann_comm::allreduce(AbsDistMat& m, const El::mpi::Comm c,
El::mpi::Op op) {
bytes_sent += sizeof(DataType) * m.LocalHeight() * m.LocalWidth();
#ifdef LBANN_HAS_ALUMINUM
if (m.LocalHeight() != m.LDim()) {
throw lbann_exception("Aluminum does not support allreduces on"
" non-contiguous matrices");
}
allreduces::Allreduce<allreduces::MPIBackend>(
m.Buffer(), m.LocalHeight()*m.LocalWidth(),
mpi_op_to_al_op(op), *get_al_comm(c));
#else
El::AllReduce(m, c, op);
#endif
bytes_received += sizeof(DataType) * m.LocalHeight() * m.LocalWidth() * (El::mpi::Size(c) - 1);
}
#ifdef LBANN_HAS_ALUMINUM
void lbann_comm::nb_allreduce(AbsDistMat& m, const El::mpi::Comm c,
allreduces::MPIBackend::req_type& req,
El::mpi::Op op) {
bytes_sent += sizeof(DataType) * m.LocalHeight() * m.LocalWidth();
if (m.LocalHeight() != m.LDim()) {
throw lbann_exception("Aluminum does not support allreduces on"
" non-contiguous matrices");
}
allreduces::NonblockingAllreduce<allreduces::MPIBackend>(
m.Buffer(), m.LocalHeight()*m.LocalWidth(),
mpi_op_to_al_op(op), *get_al_comm(c), req);
bytes_received += sizeof(DataType) * m.LocalHeight() * m.LocalWidth() * (El::mpi::Size(c) - 1);
}
#endif
void lbann_comm::intermodel_broadcast_matrix(Mat& mat, int root) {
El::Broadcast(mat, intermodel_comm, root);
}
void lbann_comm::intermodel_broadcast_matrix(AbsDistMat& mat, int root) {
El::Broadcast(mat, intermodel_comm, root);
}
void lbann_comm::intermodel_barrier() {
++num_intermodel_barriers;
barrier(intermodel_comm);
}
void lbann_comm::model_barrier() {
++num_model_barriers;
barrier(model_comm);
}
void lbann_comm::global_barrier() {
++num_global_barriers;
barrier(get_world_comm());
}
void lbann_comm::barrier(const El::mpi::Comm c) {
El::mpi::Barrier(c);
}
void lbann_comm::send(const Mat& mat, int model, int rank) {
send(mat.LockedBuffer(), mat.Height() * mat.Width(), model, rank);
}
void lbann_comm::send(const DistMat& mat, int model, int rank) {
send(mat.LockedBuffer(), mat.LocalHeight() * mat.LocalWidth(), model, rank);
}
void lbann_comm::nb_send(const Mat& mat, int model, int rank,
El::mpi::Request<DataType>& req) {
nb_send(mat.LockedBuffer(), mat.Height() * mat.Width(), model, rank, req);
}
void lbann_comm::nb_send(const DistMat& mat, int model, int rank,
El::mpi::Request<DataType>& req) {
nb_send(mat.LockedBuffer(), mat.LocalHeight() * mat.LocalWidth(), model,
rank, req);
}
void lbann_comm::recv(Mat& mat, int model, int rank) {
recv(mat.Buffer(), mat.Height() * mat.Width(), model, rank);
}
void lbann_comm::recv(DistMat& mat, int model, int rank) {
recv(mat.Buffer(), mat.LocalHeight() * mat.LocalWidth(), model, rank);
}
void lbann_comm::recv(Mat& mat) {
recv(mat.Buffer(), mat.Height() * mat.Width());
}
void lbann_comm::recv(DistMat& mat) {
recv(mat.Buffer(), mat.LocalHeight() * mat.LocalWidth());
}
void lbann_comm::nb_recv(Mat& mat, int model, int rank,
El::mpi::Request<DataType>& req) {
nb_recv(mat.Buffer(), mat.Height() * mat.Width(), model, rank, req);
}
void lbann_comm::nb_recv(DistMat& mat, int model, int rank,
El::mpi::Request<DataType>& req) {
nb_recv(mat.Buffer(), mat.LocalHeight() * mat.LocalWidth(), model, rank, req);
}
void lbann_comm::nb_recv(Mat& mat, El::mpi::Request<DataType>& req) {
nb_recv(mat.Buffer(), mat.Height() * mat.Width(), req);
}
void lbann_comm::nb_recv(DistMat& mat, El::mpi::Request<DataType>& req) {
nb_recv(mat.Buffer(), mat.LocalHeight() * mat.LocalWidth(), req);
}
void lbann_comm::intermodel_allreduce(
Mat& mat, int max_recv_count,
std::function<uint8_t *(Mat&, El::IR, El::IR, int&, bool, int)> send_transform,
std::function<int(uint8_t *, Mat&)> recv_transform,
std::function<int(uint8_t *, Mat&, bool)> recv_apply_transform,
const lbann_comm::allreduce_options opts) {
// Determine which algorithm to actually use.
lbann_comm::allreduce_algorithm algo = opts.algo;
if (algo == allreduce_algorithm::DEFAULT) {
algo = get_default_allreduce_algorithm();
}
const int nprocs = get_num_models();
const El::Int small_message_threshold = 64*64;
if (algo == allreduce_algorithm::DYNAMIC) {
// For small messages and power-of-2 number of processes, use RD.
if (!(nprocs & (nprocs - 1)) &&
mat.Height() * mat.Width() <= small_message_threshold) {
algo = allreduce_algorithm::RECURSIVE_DOUBLING;
} else {
algo = allreduce_algorithm::PAIRWISE_EXCHANGE_RING;
}
}
switch (algo) {
case allreduce_algorithm::RECURSIVE_DOUBLING:
recursive_doubling_allreduce_pow2(
intermodel_comm, mat, max_recv_count,
send_transform, recv_apply_transform, opts);
break;
case allreduce_algorithm::PAIRWISE_EXCHANGE_RING:
pe_ring_allreduce(
intermodel_comm, mat, max_recv_count, send_transform,
recv_transform, recv_apply_transform, opts);
break;
case allreduce_algorithm::RING:
ring_allreduce(
intermodel_comm, mat, max_recv_count, send_transform,
recv_transform, recv_apply_transform, opts);
break;
case allreduce_algorithm::RABENSEIFNER:
rabenseifner_allreduce(
intermodel_comm, mat, max_recv_count, send_transform,
recv_transform, recv_apply_transform, opts);
break;
case allreduce_algorithm::DEFAULT:
case allreduce_algorithm::DYNAMIC:
default:
throw lbann_exception("intermodel_allreduce: bad algorithm");
break;
}
}
void lbann_comm::recursive_doubling_allreduce_pow2(
const El::mpi::Comm comm, Mat& mat, int max_recv_count,
std::function<uint8_t *(Mat&, El::IR, El::IR, int&, bool, int)> send_transform,
std::function<int(uint8_t *, Mat&, bool)> recv_apply_transform,
const lbann_comm::allreduce_options opts) {
double ar_start = get_time();
const int rank = El::mpi::Rank(comm);
const unsigned int nprocs = El::mpi::Size(comm);
if (nprocs == 1) {
return; // Nothing to do.
}
// This implementation requires a power-of-2 number of processes.
if (nprocs & (nprocs - 1)) {
throw lbann_exception("lbann_comm: recursive doubling allreduce requires"
" a power-of-2 number of participating processes");
}
uint8_t *max_recv_buf = get_collective_buffer(max_recv_count);
uint8_t *recv_buf = max_recv_buf;
unsigned int mask = 1;
while (mask < nprocs) {
int partner = rank ^ mask; // The rank we exchange with this step.
const bool is_local = opts.no_local_trans &&
is_rank_node_local(partner, comm);
// Transform the data we want to send.
double send_trans_start = get_time();
int send_size;
int recv_size = max_recv_count;
uint8_t *send_buf = nullptr;
if (is_local) {
send_buf = (uint8_t *) mat.Buffer();
send_size = sizeof(DataType) * mat.Height() * mat.Width();
recv_size = send_size;
recv_buf = get_collective_buffer(recv_size);
} else {
send_buf = send_transform(mat, El::ALL, El::ALL, send_size, false, 0);
recv_buf = max_recv_buf;
}
ar_send_transform_time += get_time() - send_trans_start;
bytes_sent += send_size;
ar_bytes_sent += send_size;
double sendrecv_start = get_time();
El::mpi::SendRecv(send_buf, send_size, partner,
recv_buf, recv_size, partner, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
// Transform and reduce the received data.
double recv_apply_trans_start = get_time();
recv_size = recv_apply_transform(recv_buf, mat, is_local);
ar_recv_apply_transform_time += get_time() - recv_apply_trans_start;
bytes_received += recv_size;
ar_bytes_received += recv_size;
mask <<= 1;
}
ar_time += get_time() - ar_start;
}
void lbann_comm::pe_ring_allreduce(
const El::mpi::Comm comm, Mat& mat, int max_recv_count,
std::function<uint8_t *(Mat&, El::IR, El::IR, int&, bool, int)> send_transform,
std::function<int(uint8_t *, Mat&)> recv_transform,
std::function<int(uint8_t *, Mat&, bool)> recv_apply_transform,
const lbann_comm::allreduce_options opts) {
double ar_start = get_time();
const int rank = El::mpi::Rank(comm);
const int nprocs = El::mpi::Size(comm);
if (nprocs == 1) {
return; // Nothing to do.
}
// Compute the number of columns each processor sends.
// If it doesn't divide evenly, give one extra to the earlier ranks.
const El::Int cols_per_proc = mat.Width() / nprocs;
const El::Int cols_remainder = mat.Width() % nprocs;
// Compute the lengths/ends of the slices.
std::vector<El::Int> slice_lengths(nprocs, cols_per_proc);
for (int i = 0; i < cols_remainder; ++i) {
slice_lengths[i] += 1;
}
std::vector<El::Int> slice_ends(nprocs);
std::partial_sum(slice_lengths.begin(), slice_lengths.end(),
slice_ends.begin());
std::vector<uint8_t *> max_recv_buffers(opts.max_reduces, nullptr);
for (size_t i = 0; i < max_recv_buffers.size(); ++i) {
max_recv_buffers[i] = get_collective_buffer(max_recv_count, i);
}
// Local slice of our accumulated data.
auto accum_view = mat(El::ALL, El::IR(slice_ends[rank] - slice_lengths[rank],
slice_ends[rank]));
// Do a pairwise-exchange reduce-scatter.
double rs_start = get_time();
for (int outer_step = 1;
outer_step < nprocs;
outer_step += opts.max_reduces) {
const int reduces_this_step = std::min(opts.max_reduces,
nprocs - outer_step);
std::vector<El::mpi::Request<uint8_t>> send_reqs(reduces_this_step);
std::vector<El::mpi::Request<uint8_t>> recv_reqs(reduces_this_step);
std::vector<uint8_t *> recv_buffers(max_recv_buffers);
int num_local_recvs = 0;
std::vector<bool> local_recvs(reduces_this_step, false);
for (int step = outer_step; step < outer_step + reduces_this_step; ++step) {
const int reduce_idx = step - outer_step;
// Compute where we send to/receive from.
const int dst = (rank + step) % nprocs;
const int src = (rank - step + nprocs) % nprocs;
const bool is_send_local = opts.no_local_trans &&
is_rank_node_local(dst, comm);
const bool is_recv_local = opts.no_local_trans &&
is_rank_node_local(src, comm);
// Post the receive.
double recv_start = get_time();
int recv_size = max_recv_count;
if (is_recv_local) {
recv_size = sizeof(DataType) * accum_view.Height() * accum_view.Width();
recv_buffers[reduce_idx] = get_collective_buffer(recv_size,
num_local_recvs);
++num_local_recvs;
local_recvs[reduce_idx] = is_recv_local;
}
El::mpi::IRecv(recv_buffers[reduce_idx], recv_size, src, comm,
recv_reqs[reduce_idx]);
double recv_tot = get_time() - recv_start;
ar_recv_time += recv_tot;
ar_rs_recv_time += recv_tot;
// Transform the data we send. We do not look at the same chunk of data
// twice.
double send_trans_start = get_time();
int send_size;
uint8_t *send_buf = nullptr;
if (is_send_local) {
auto send_view = mat(El::ALL,
El::IR(slice_ends[dst] - slice_lengths[dst], slice_ends[dst]));
send_buf = (uint8_t *) send_view.Buffer();
send_size = sizeof(DataType) * send_view.Height() * send_view.Width();
} else {
send_buf = send_transform(
mat, El::ALL, El::IR(slice_ends[dst] - slice_lengths[dst], slice_ends[dst]),
send_size, true, reduce_idx);
}
ar_send_transform_time += get_time() - send_trans_start;
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_rs_bytes_sent += send_size;
// Post the send.
double send_start = get_time();
El::mpi::ISend(send_buf, send_size, dst, comm, send_reqs[reduce_idx]);
double send_tot = get_time() - send_start;
ar_send_time += send_tot;
ar_rs_send_time += send_tot;
}
// Complete the receives (in any order).
// We need to extract the raw MPI_Request because Elemental does not support
// MPI_Waitany.
std::vector<MPI_Request> raw_reqs(reduces_this_step);
for (int i = 0; i < reduces_this_step; ++i) {
raw_reqs[i] = recv_reqs[i].backend;
}
for (int i = 0; i < reduces_this_step; ++i) {
int completed_idx;
double recv_start = get_time();
MPI_Waitany(reduces_this_step, raw_reqs.data(), &completed_idx,
MPI_STATUS_IGNORE);
double recv_tot = get_time() - recv_start;
ar_recv_time += recv_tot;
ar_rs_recv_time += recv_tot;
double recv_apply_trans_start = get_time();
int recv_size = recv_apply_transform(
recv_buffers[completed_idx], accum_view, local_recvs[completed_idx]);
ar_recv_apply_transform_time += get_time() - recv_apply_trans_start;
bytes_received += recv_size;
ar_bytes_received += recv_size;
ar_rs_bytes_received += recv_size;
}
// Complete all the sends.
double send_start = get_time();
El::mpi::WaitAll(reduces_this_step, send_reqs.data(), MPI_STATUSES_IGNORE);
double send_tot = get_time() - send_start;
ar_send_time += send_tot;
ar_rs_send_time += send_tot;
}
uint8_t *recv_buf = max_recv_buffers[0]; // Get a regular recv buffer.
ar_rs_time += get_time() - rs_start;
// Do a ring allgather.
double ag_start = get_time();
const int src = (rank - 1 + nprocs) % nprocs;
const int dst = (rank + 1) % nprocs;
// Apply the transform to our locally-accumulated slice of the data.
// Since the same data is cycled to every process, we do not do the
// no_local_trans here.
int send_size;
// Do the first step where we forward our local data.
{
double send_trans_start = get_time();
uint8_t *send_buf = send_transform(
mat, El::ALL, El::IR(slice_ends[rank] - slice_lengths[rank], slice_ends[rank]),
send_size, false, 0);
ar_send_transform_time += get_time() - send_trans_start;
const int data_src = (rank - 1 + nprocs) % nprocs;
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_ag_bytes_sent += send_size;
auto recv_view = mat(El::ALL,
El::IR(slice_ends[data_src] - slice_lengths[data_src],
slice_ends[data_src]));
// If we can, receive directly into the destination matrix.
if (opts.id_recv) {
recv_buf = (uint8_t *) recv_view.Buffer();
max_recv_count = sizeof(DataType) * recv_view.Height() * recv_view.Width();
}
double sendrecv_start = get_time();
El::mpi::SendRecv(send_buf, send_size, dst,
recv_buf, max_recv_count, src, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
ar_ag_send_time += sendrecv_tot;
ar_ag_recv_time += sendrecv_tot;
double recv_trans_start = get_time();
int recv_size = 0;
if (opts.id_recv) {
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
} else {
recv_size = recv_transform(recv_buf, recv_view);
}
ar_recv_transform_time += get_time() - recv_trans_start;
bytes_received += recv_size;
ar_bytes_received += recv_size;
ar_ag_bytes_received += send_size;
send_size = recv_size;
}
// Now do the remaining nprocs - 2 steps.
// We always send from recv_buf and receive to recv_buf2, swapping
// pointers to avoid copying.
uint8_t *recv_buf2 = nullptr;
if (!opts.id_recv) {
recv_buf2 = get_collective_buffer(max_recv_count, 1);
}
for (int step = 1; step < nprocs - 1; ++step) {
// Compute where the data we get is coming from.
const int data_src = (rank - step - 1 + nprocs) % nprocs;
auto recv_view = mat(El::ALL,
El::IR(slice_ends[data_src] - slice_lengths[data_src],
slice_ends[data_src]));
if (opts.id_recv) {
recv_buf2 = (uint8_t *) recv_view.Buffer();
max_recv_count = sizeof(DataType) * recv_view.Height() * recv_view.Width();
}
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_ag_bytes_sent += send_size;
double sendrecv_start = get_time();
El::mpi::SendRecv(recv_buf, send_size, dst,
recv_buf2, max_recv_count, src, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
ar_ag_send_time += sendrecv_tot;
ar_ag_recv_time += sendrecv_tot;
double recv_trans_start = get_time();
int recv_size = 0;
if (opts.id_recv) {
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
} else {
recv_size = recv_transform(recv_buf2, recv_view);
}
ar_recv_transform_time += get_time() - recv_trans_start;
bytes_received += recv_size;
// Swap the send and receive buffers.
std::swap(recv_buf, recv_buf2);
send_size = recv_size;
ar_bytes_received += recv_size;
ar_ag_bytes_received += send_size;
}
ar_ag_time += get_time() - ag_start;
ar_time += get_time() - ar_start;
}
void lbann_comm::ring_allreduce(
const El::mpi::Comm comm, Mat& mat, int max_recv_count,
std::function<uint8_t *(Mat&, El::IR, El::IR, int&, bool, int)> send_transform,
std::function<int(uint8_t *, Mat&)> recv_transform,
std::function<int(uint8_t *, Mat&, bool)> recv_apply_transform,
const lbann_comm::allreduce_options opts) {
double ar_start = get_time();
const int rank = El::mpi::Rank(comm);
const int nprocs = El::mpi::Size(comm);
if (nprocs == 1) {
return; // Nothing to do.
}
// Compute the number of columns each processor sends.
const El::Int cols_per_proc = mat.Width() / nprocs;
const El::Int cols_remainder = mat.Width() % nprocs;
// Compute the lengths/ends of the slices.
std::vector<El::Int> slice_lengths(nprocs, cols_per_proc);
for (int i = 0; i < cols_remainder; ++i) {
slice_lengths[i] += 1;
}
std::vector<El::Int> slice_ends(nprocs);
std::partial_sum(slice_lengths.begin(), slice_lengths.end(),
slice_ends.begin());
uint8_t *max_recv_buf = get_collective_buffer(max_recv_count);
uint8_t *recv_buf = max_recv_buf;
// Compute source/destination in the ring.
const int src = (rank - 1 + nprocs) % nprocs;
const int dst = (rank + 1) % nprocs;
const bool is_send_local = opts.no_local_trans &&
is_rank_node_local(dst, comm);
const bool is_recv_local = opts.no_local_trans &&
is_rank_node_local(src, comm);
// Do a ring-based reduce-scatter.
// This is like the pairwise-exchange reduce-scatter except instead of
// rank i accumulating only slice i, the slices are cycled around and
// each node accumulates its portion into the slice when it passes
// through. After the nprocs-1 steps slice k will be on rank
// (k + nprocs - 1) % nprocs.
double rs_start = get_time();
for (int step = 0; step < nprocs - 1; ++step) {
// Compute the slices to send/recv.
const int send_slice = (rank - step + nprocs) % nprocs;
const int recv_slice = (rank - step - 1 + nprocs) % nprocs;
// Transform the data to send.
double send_trans_start = get_time();
int send_size;
int recv_size = max_recv_count;
uint8_t *send_buf = nullptr;
if (is_send_local) {
auto send_view = mat(El::ALL,
El::IR(slice_ends[dst] - slice_lengths[dst], slice_ends[dst]));
send_buf = (uint8_t *) send_view.Buffer();
send_size = sizeof(DataType) * send_view.Height() * send_view.Width();
} else {
send_buf = send_transform(mat, El::ALL,
El::IR(slice_ends[send_slice] - slice_lengths[send_slice],
slice_ends[send_slice]), send_size, false, 0);
}
auto recv_view = mat(El::ALL,
El::IR(slice_ends[recv_slice] - slice_lengths[recv_slice], slice_ends[recv_slice]));
if (is_recv_local) {
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
recv_buf = get_collective_buffer(recv_size);
} else {
recv_buf = max_recv_buf;
}
ar_send_transform_time += get_time() - send_trans_start;
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_rs_bytes_sent += send_size;
double sendrecv_start = get_time();
El::mpi::SendRecv(send_buf, send_size, dst,
recv_buf, recv_size, src, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
ar_rs_send_time += sendrecv_tot;
ar_rs_recv_time += sendrecv_tot;
double recv_apply_trans_start = get_time();
recv_size = recv_apply_transform(recv_buf, recv_view, is_recv_local);
ar_recv_apply_transform_time += get_time() - recv_apply_trans_start;
bytes_received += recv_size;
ar_bytes_received += recv_size;
ar_rs_bytes_received += recv_size;
}
recv_buf = max_recv_buf; // Ensure we're back to the original.
ar_rs_time += get_time() - rs_start;
// Do a ring allgather, first applying the transform to local data.
double ag_start = get_time();
int send_size;
{
const int send_slice = (rank + 1) % nprocs;
const int recv_slice = rank;
double send_trans_start = get_time();
uint8_t *send_buf = send_transform(
mat, El::ALL, El::IR(slice_ends[send_slice] - slice_lengths[send_slice],
slice_ends[send_slice]), send_size, false, 0);
ar_send_transform_time += get_time() - send_trans_start;
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_ag_bytes_sent += send_size;
auto recv_view = mat(El::ALL,
El::IR(slice_ends[recv_slice] - slice_lengths[recv_slice],
slice_ends[recv_slice]));
// If we can, receive directly into the destination matrix.
if (opts.id_recv) {
recv_buf = (uint8_t *) recv_view.Buffer();
max_recv_count = sizeof(DataType) * recv_view.Height() * recv_view.Width();
}
double sendrecv_start = get_time();
El::mpi::SendRecv(send_buf, send_size, dst,
recv_buf, max_recv_count, src, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
ar_ag_send_time += sendrecv_tot;
ar_ag_recv_time += sendrecv_tot;
double recv_trans_start = get_time();
int recv_size = 0;
if (opts.id_recv) {
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
} else {
recv_size = recv_transform(recv_buf, recv_view);
}
ar_recv_transform_time += get_time() - recv_trans_start;
send_size = recv_size;
bytes_received += recv_size;
ar_bytes_received += recv_size;
ar_ag_bytes_received += recv_size;
}
uint8_t *recv_buf2 = nullptr;
if (!opts.id_recv) {
recv_buf2 = get_collective_buffer(max_recv_count, 1);
}
for (int step = 1; step < nprocs - 1; ++step) {
const int recv_slice = (rank - step + nprocs) % nprocs;
auto recv_view = mat(El::ALL,
El::IR(slice_ends[recv_slice] - slice_lengths[recv_slice],
slice_ends[recv_slice]));
if (opts.id_recv) {
recv_buf2 = (uint8_t *) recv_view.Buffer();
max_recv_count = sizeof(DataType) * recv_view.Height() * recv_view.Width();
}
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_ag_bytes_sent += send_size;
double sendrecv_start = get_time();
El::mpi::SendRecv(recv_buf, send_size, dst,
recv_buf2, max_recv_count, src, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
ar_ag_send_time += sendrecv_tot;
ar_ag_recv_time += sendrecv_tot;
double recv_trans_start = get_time();
int recv_size = 0;
if (opts.id_recv) {
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
} else {
recv_size = recv_transform(recv_buf2, recv_view);
}
ar_recv_transform_time += get_time() - recv_trans_start;
// Swap the send and receive buffers.
std::swap(recv_buf, recv_buf2);
send_size = recv_size;
bytes_received += recv_size;
ar_bytes_received += recv_size;
ar_ag_bytes_received += recv_size;
}
ar_ag_time += get_time() - ag_start;
ar_time += get_time() - ar_start;
}
void lbann_comm::rabenseifner_allreduce(
const El::mpi::Comm comm, Mat& mat, int max_recv_count,
std::function<uint8_t *(Mat&, El::IR, El::IR, int&, bool, int)> send_transform,
std::function<int(uint8_t *, Mat&)> recv_transform,
std::function<int(uint8_t *, Mat&, bool)> recv_apply_transform,
const lbann_comm::allreduce_options opts) {
double ar_start = get_time();
const int rank = El::mpi::Rank(comm);
const unsigned int nprocs = El::mpi::Size(comm);
if (nprocs == 1) {
return; // Nothing to do.
}
// This implementation requires a power-of-2 number of processes.
if (nprocs & (nprocs - 1)) {
throw lbann_exception("lbann_comm: Rabenseifner allreduce requires"
" a power-of-2 number of participating processes");
}
// Compute the slices on each processor.
const El::Int cols_per_proc = mat.Width() / nprocs;
const El::Int cols_remainder = mat.Width() % nprocs;
// Compute the lengths/ends of the slices.
std::vector<El::Int> slice_lengths(nprocs, cols_per_proc);
for (int i = 0; i < cols_remainder; ++i) {
slice_lengths[i] += 1;
}
std::vector<El::Int> slice_ends(nprocs);
std::partial_sum(slice_lengths.begin(), slice_lengths.end(),
slice_ends.begin());
// Do a recursive-halving reduce-scatter.
// In each step here a process sends all the data needed for the other
// "half" of the processes. i.e. each process sends half their data in the
// first step, a quarter in the second step, etc.
double rs_start = get_time();
unsigned int partner_mask = nprocs >> 1;
unsigned int slice_mask = 1;
unsigned int send_idx = 0;
unsigned int recv_idx = 0;
unsigned int last_idx = nprocs;
uint8_t *recv_buf = get_collective_buffer(max_recv_count);
while (partner_mask > 0) {
int partner = rank ^ partner_mask; // The rank we exchange with this step.
const bool is_local = opts.no_local_trans &&
is_rank_node_local(partner, comm);
// Determine the range of data to send/recv.
El::IR send_range, recv_range;
if (rank < partner) {
send_idx = recv_idx + nprocs / (slice_mask*2);
send_range = El::IR(slice_ends[send_idx] - slice_lengths[send_idx],
slice_ends[last_idx-1]);
recv_range = El::IR(slice_ends[recv_idx] - slice_lengths[recv_idx],
slice_ends[send_idx-1]);
} else {
recv_idx = send_idx + nprocs / (slice_mask*2);
send_range = El::IR(slice_ends[send_idx] - slice_lengths[send_idx],
slice_ends[recv_idx-1]);
recv_range = El::IR(slice_ends[recv_idx] - slice_lengths[recv_idx],
slice_ends[last_idx-1]);
}
auto recv_view = mat(El::ALL, recv_range);
// Transform the data to send.
double send_trans_start = get_time();
int send_size;
int recv_size = max_recv_count;
uint8_t *send_buf = nullptr;
if (is_local) {
auto send_view = mat(El::ALL, send_range);
send_buf = (uint8_t *) send_view.Buffer();
send_size = sizeof(DataType) * send_view.Height() * send_view.Width();
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
} else {
send_buf = send_transform(mat, El::ALL, send_range, send_size, false, 0);
}
ar_send_transform_time += get_time() - send_trans_start;
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_rs_bytes_sent += send_size;
double sendrecv_start = get_time();
El::mpi::SendRecv(send_buf, send_size, partner,
recv_buf, recv_size, partner, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
ar_rs_send_time += sendrecv_tot;
ar_rs_recv_time += sendrecv_tot;
// Transform the received data.
double recv_apply_trans_start = get_time();
recv_size = recv_apply_transform(recv_buf, recv_view, is_local);
ar_recv_apply_transform_time += get_time() - recv_apply_trans_start;
bytes_received += recv_size;
ar_bytes_received += recv_size;
ar_rs_bytes_received += send_size;
// Update info for next iteration.
// Except last_idx when needed for the allgather.
send_idx = recv_idx;
partner_mask >>= 1;
slice_mask <<= 1;
if (partner_mask > 0) {
last_idx = recv_idx + nprocs / (slice_mask);
}
}
ar_rs_time += get_time() - rs_start;
// Do a recursive-doubling algather.
double ag_start = get_time();
slice_mask >>= 1;
partner_mask = 1;
// Now do the remaining steps.
while (partner_mask < nprocs) {
int partner = rank ^ partner_mask;
const bool is_local = opts.no_local_trans &&
is_rank_node_local(partner, comm);
// Determine range to send/recv.
El::IR send_range, recv_range;
if (rank < partner) {
if (slice_mask != nprocs / 2) {
last_idx = last_idx + nprocs / (slice_mask*2);
}
recv_idx = send_idx + nprocs / (slice_mask*2);
send_range = El::IR(slice_ends[send_idx] - slice_lengths[send_idx],
slice_ends[recv_idx-1]);
recv_range = El::IR(slice_ends[recv_idx] - slice_lengths[recv_idx],
slice_ends[last_idx-1]);
} else {
recv_idx = send_idx - nprocs / (slice_mask*2);
send_range = El::IR(slice_ends[send_idx] - slice_lengths[send_idx],
slice_ends[last_idx-1]);
recv_range = El::IR(slice_ends[recv_idx] - slice_lengths[recv_idx],
slice_ends[send_idx-1]);
}
auto recv_view = mat(El::ALL, recv_range);
// Transform the data to send.
double send_trans_start = get_time();
int send_size;
int recv_size = max_recv_count;
uint8_t *send_buf = nullptr;
if (is_local) {
auto send_view = mat(El::ALL, send_range);
send_buf = (uint8_t *) send_view.Buffer();
send_size = sizeof(DataType) * send_view.Height() * send_view.Width();
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
} else {
send_buf = send_transform(mat, El::ALL, send_range, send_size, false, 0);
}
ar_send_transform_time += get_time() - send_trans_start;
if (opts.id_recv || is_local) {
recv_buf = (uint8_t *) recv_view.Buffer();
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
}
bytes_sent += send_size;
ar_bytes_sent += send_size;
ar_ag_bytes_sent += send_size;
double sendrecv_start = get_time();
El::mpi::SendRecv(send_buf, send_size, partner,
recv_buf, recv_size, partner, comm);
double sendrecv_tot = get_time() - sendrecv_start;
ar_send_time += sendrecv_tot;
ar_recv_time += sendrecv_tot;
ar_ag_send_time += sendrecv_tot;
ar_ag_recv_time += sendrecv_tot;
double recv_trans_start = get_time();
if (opts.id_recv) {
recv_size = sizeof(DataType) * recv_view.Height() * recv_view.Width();
} else {
recv_size = recv_transform(recv_buf, recv_view);
}
ar_recv_transform_time += get_time() - recv_trans_start;
bytes_received += recv_size;
ar_bytes_received += recv_size;
ar_ag_bytes_received += send_size;
// Update for the next iteration.
if (rank > partner) {
send_idx = recv_idx;
}
partner_mask <<= 1;
slice_mask >>= 1;
}
ar_ag_time += get_time() - ag_start;
ar_time += get_time() - ar_start;
}
void lbann_comm::setup_node_comm() {
// Get string specifying compute node
char node_name[MPI_MAX_PROCESSOR_NAME];
int node_name_len;
checkMPI(MPI_Get_processor_name(node_name, &node_name_len));
const std::string node_string(node_name);
// Hash node names and split MPI processes
int hash = std::hash<std::string>()(node_string);
hash = hash >= 0 ? hash : -hash; // Make sure hash is non-negative
El::mpi::Comm hash_comm;
El::mpi::Split(get_world_comm(), hash,
El::mpi::Rank(get_world_comm()), hash_comm);
const int hash_comm_size = El::mpi::Size(hash_comm);
// Compare node names and split MPI processes
auto *node_name_list = new char[hash_comm_size*MPI_MAX_PROCESSOR_NAME];
checkMPI(MPI_Allgather(node_name, MPI_MAX_PROCESSOR_NAME, MPI_CHAR,
node_name_list, MPI_MAX_PROCESSOR_NAME, MPI_CHAR,
hash_comm.comm));
int node_num = El::mpi::Rank(hash_comm);
for(int i=0; i<hash_comm_size; ++i) {
const std::string other_node_string(node_name_list + i*MPI_MAX_PROCESSOR_NAME);
if(node_string == other_node_string) {
node_num = i;
break;
}
}
delete[] node_name_list;
El::mpi::Split(hash_comm, node_num, El::mpi::Rank(get_world_comm()),
node_comm);
El::mpi::Free(hash_comm);
// Set up list of ranks that are local.
int node_comm_size = El::mpi::Size(node_comm);
for (int i = 0; i < node_comm_size; ++i) {
world_ranks_on_node.push_back(
El::mpi::Translate(node_comm, i, get_world_comm()));
}
}
void lbann_comm::setup_threads() {
const char* env_num_threads = getenv("OMP_NUM_THREADS");
if (env_num_threads != nullptr){
threads_per_proc = std::atoi(env_num_threads);
}
else {
threads_per_proc = std::thread::hardware_concurrency() / procs_per_node;
}
reset_threads();
}
void lbann_comm::reset_threads() {
if (threads_per_proc != omp_get_max_threads()) {
omp_set_num_threads(threads_per_proc);
}
}
uint8_t *lbann_comm::get_collective_buffer(size_t size, size_t idx) {
auto buf_iter = collective_bufs.find(size);
if (buf_iter == collective_bufs.end()) {
if (idx != 0) {
throw lbann_exception("get_collective_buffer: non-contiguous index");
}
collective_bufs.emplace(std::make_pair(size, std::vector<uint8_t *>()));
collective_bufs[size].push_back(new uint8_t[size]);
return collective_bufs[size][0];
} else {
if (collective_bufs[size].size() > idx) {
return collective_bufs[size][idx];
} else {
if (collective_bufs[size].size() != idx) {
throw lbann_exception("get_collective_buffer: non-contiguous index");
}
collective_bufs[size].push_back(new uint8_t[size]);
return collective_bufs[size][idx];
}
}
}
#ifdef LBANN_HAS_ALUMINUM
allreduces::MPICommunicator* lbann_comm::get_al_comm(El::mpi::Comm c) {
if (!al_comms.count(c.comm)) {
al_comms[c.comm] = new allreduces::MPICommunicator(c.comm);
}
return al_comms[c.comm];
}
allreduces::ReductionOperator lbann_comm::mpi_op_to_al_op(El::mpi::Op op) {
switch (op.op) {
case MPI_SUM:
return allreduces::ReductionOperator::sum;
case MPI_PROD:
return allreduces::ReductionOperator::prod;
case MPI_MIN:
return allreduces::ReductionOperator::min;
case MPI_MAX:
return allreduces::ReductionOperator::max;
default:
throw lbann_exception("Reduction operator not supported in Aluminum");
}
}
#endif
} // namespace lbann
| 1 | 12,474 | `m_al_comms` now contains smart pointers. | LLNL-lbann | cpp |
@@ -80,6 +80,10 @@ namespace AutoRest.CSharp
{
return "new " + type.Name + "()";
}
+ if (type is EnumType && (type as EnumType).ModelAsString)
+ {
+ return Instance.QuoteValue(defaultValue);
+ }
if (primaryType != null)
{
if (primaryType.KnownPrimaryType == KnownPrimaryType.String) | 1 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using AutoRest.Core;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.Core.Utilities.Collections;
namespace AutoRest.CSharp
{
public class CodeNamerCs : CodeNamer
{
/// <summary>
/// Initializes a new instance of CSharpCodeNamingFramework.
/// </summary>
public CodeNamerCs()
{
ReservedWords.AddRange(
new[]
{
"abstract", "as", "async", "await", "base",
"bool", "break", "byte", "case", "catch",
"char", "checked", "class", "const", "continue",
"decimal", "default", "delegate", "do", "double",
"dynamic", "else", "enum", "event", "explicit",
"extern", "false", "finally", "fixed", "float",
"for", "foreach", "from", "global", "goto",
"if", "implicit", "in", "int", "interface",
"internal", "is", "lock", "long", "namespace",
"new", "null", "object", "operator", "out",
"override", "params", "private", "protected", "public",
"readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string",
"struct", "switch", "this", "throw", "true",
"try", "typeof", "uint", "ulong", "unchecked",
"unsafe", "ushort", "using", "virtual", "void",
"volatile", "while", "yield", "var"
});
}
/// <summary>
/// Returns true when the name comparison is a special case and should not
/// be used to determine name conflicts.
/// </summary>
/// <param name="whoIsAsking">the identifier that is checking to see if there is a conflict</param>
/// <param name="reservedName">the identifier that would normally be reserved.</param>
/// <returns></returns>
public override bool IsSpecialCase(IIdentifier whoIsAsking, IIdentifier reservedName)
{
if (whoIsAsking is Property && reservedName is CompositeType)
{
var parent = (whoIsAsking as IChild)?.Parent as IIdentifier;
if (ReferenceEquals(parent, reservedName))
{
return false;
}
// special case: properties can have the same name as a compositetype
// unless it is the same name as a parent.
return true;
}
return false;
}
public override string EscapeDefaultValue(string defaultValue, IModelType type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
var primaryType = type as PrimaryType;
if (defaultValue != null)
{
if (type is CompositeType)
{
return "new " + type.Name + "()";
}
if (primaryType != null)
{
if (primaryType.KnownPrimaryType == KnownPrimaryType.String)
{
return Instance.QuoteValue(defaultValue);
}
if (primaryType.KnownPrimaryType == KnownPrimaryType.Boolean)
{
return defaultValue.ToLowerInvariant();
}
if ((primaryType.KnownPrimaryType == KnownPrimaryType.Date) ||
(primaryType.KnownPrimaryType == KnownPrimaryType.DateTime) ||
(primaryType.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123) ||
(primaryType.KnownPrimaryType == KnownPrimaryType.TimeSpan) ||
(primaryType.KnownPrimaryType == KnownPrimaryType.ByteArray) ||
(primaryType.KnownPrimaryType == KnownPrimaryType.Base64Url) ||
(primaryType.KnownPrimaryType == KnownPrimaryType.UnixTime))
{
return
$"Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<{primaryType.Name}>"+
$"({Instance.QuoteValue($"\"{defaultValue}\"")}, this.Client.SerializationSettings)";
}
}
}
return defaultValue;
}
}
}
| 1 | 23,607 | Did you do a test run with the compare script? I'm nervous about what happens on all the generators... | Azure-autorest | java |
@@ -390,6 +390,19 @@ func (c *client) initClient() {
}
}
+// RemoteAddress expose the Address of the client connection,
+// nil when not connected or unknown
+func (c *client) RemoteAddress() net.Addr {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if c.nc == nil {
+ return nil
+ }
+
+ return c.nc.RemoteAddr()
+}
+
// Helper function to report errors.
func (c *client) reportErrRegisterAccount(acc *Account, err error) {
if err == ErrTooManyAccountConnections { | 1 | // Copyright 2012-2018 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"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"math/rand"
"net"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/jwt"
)
// Type of client connection.
const (
// CLIENT is an end user.
CLIENT = iota
// ROUTER is another router in the cluster.
ROUTER
// GATEWAY is a link between 2 clusters.
GATEWAY
// SYSTEM is an internal system client.
SYSTEM
)
const (
// ClientProtoZero is the original Client protocol from 2009.
// http://nats.io/documentation/internals/nats-protocol/
ClientProtoZero = iota
// ClientProtoInfo signals a client can receive more then the original INFO block.
// This can be used to update clients on other cluster members, etc.
ClientProtoInfo
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const (
// Scratch buffer size for the processMsg() calls.
msgScratchSize = 1024
msgHeadProto = "RMSG "
msgHeadProtoLen = len(msgHeadProto)
)
// For controlling dynamic buffer sizes.
const (
startBufSize = 512 // For INFO/CONNECT block
minBufSize = 64 // Smallest to shrink to for PING/PONG
maxBufSize = 65536 // 64k
shortsToShrink = 2
)
// Represent client booleans with a bitmask
type clientFlag byte
// Some client state represented as flags
const (
connectReceived clientFlag = 1 << iota // The CONNECT proto has been received
infoReceived // The INFO protocol has been received
firstPongSent // The first PONG has been sent
handshakeComplete // For TLS clients, indicate that the handshake is complete
clearConnection // Marks that clearConnection has already been called.
flushOutbound // Marks client as having a flushOutbound call in progress.
noReconnect // Indicate that on close, this connection should not attempt a reconnect
)
// set the flag (would be equivalent to set the boolean to true)
func (cf *clientFlag) set(c clientFlag) {
*cf |= c
}
// clear the flag (would be equivalent to set the boolean to false)
func (cf *clientFlag) clear(c clientFlag) {
*cf &= ^c
}
// isSet returns true if the flag is set, false otherwise
func (cf clientFlag) isSet(c clientFlag) bool {
return cf&c != 0
}
// setIfNotSet will set the flag `c` only if that flag was not already
// set and return true to indicate that the flag has been set. Returns
// false otherwise.
func (cf *clientFlag) setIfNotSet(c clientFlag) bool {
if *cf&c == 0 {
*cf |= c
return true
}
return false
}
// ClosedState is the reason client was closed. This will
// be passed into calls to clearConnection, but will only
// be stored in ConnInfo for monitoring.
type ClosedState int
const (
ClientClosed = ClosedState(iota + 1)
AuthenticationTimeout
AuthenticationViolation
TLSHandshakeError
SlowConsumerPendingBytes
SlowConsumerWriteDeadline
WriteError
ReadError
ParseError
StaleConnection
ProtocolViolation
BadClientProtocolVersion
WrongPort
MaxAccountConnectionsExceeded
MaxConnectionsExceeded
MaxPayloadExceeded
MaxControlLineExceeded
MaxSubscriptionsExceeded
DuplicateRoute
RouteRemoved
ServerShutdown
AuthenticationExpired
WrongGateway
)
type client struct {
// Here first because of use of atomics, and memory alignment.
stats
mpay int32
msubs int
mu sync.Mutex
kind int
cid uint64
opts clientOpts
start time.Time
nonce []byte
nc net.Conn
ncs string
out outbound
srv *Server
acc *Account
user *NkeyUser
host string
port int
subs map[string]*subscription
perms *permissions
mperms *msgDeny
darray []string
in readCache
pcd map[*client]struct{}
atmr *time.Timer
ping pinfo
msgb [msgScratchSize]byte
last time.Time
parseState
rtt time.Duration
rttStart time.Time
route *route
gw *gateway
debug bool
trace bool
echo bool
flags clientFlag // Compact booleans into a single field. Size will be increased when needed.
}
// Struct for PING initiation from the server.
type pinfo struct {
tmr *time.Timer
out int
}
// outbound holds pending data for a socket.
type outbound struct {
p []byte // Primary write buffer
s []byte // Secondary for use post flush
nb net.Buffers // net.Buffers for writev IO
sz int // limit size per []byte, uses variable BufSize constants, start, min, max.
sws int // Number of short writes, used for dyanmic resizing.
pb int64 // Total pending/queued bytes.
pm int64 // Total pending/queued messages.
sg *sync.Cond // Flusher conditional for signaling.
fsp int // Flush signals that are pending from readLoop's pcd.
mp int64 // snapshot of max pending.
wdl time.Duration // Snapshot fo write deadline.
lft time.Duration // Last flush time.
}
type perm struct {
allow *Sublist
deny *Sublist
}
type permissions struct {
sub perm
pub perm
pcache map[string]bool
}
// msgDeny is used when a user permission for subscriptions has a deny
// clause but a subscription could be made that is of broader scope.
// e.g. deny = "foo", but user subscribes to "*". That subscription should
// succeed but no message sent on foo should be delivered.
type msgDeny struct {
deny *Sublist
dcache map[string]bool
}
// routeTarget collects information regarding routes and queue groups for
// sending information to a remote.
type routeTarget struct {
sub *subscription
qs []byte
_qs [32]byte
}
const (
maxResultCacheSize = 512
maxDenyPermCacheSize = 256
maxPermCacheSize = 128
pruneSize = 32
routeTargetInit = 8
)
// Used in readloop to cache hot subject lookups and group statistics.
type readCache struct {
// These are for clients who are bound to a single account.
genid uint64
results map[string]*SublistResult
// This is for routes and gateways to have their own L1 as well that is account aware.
pacache map[string]*perAccountCache
// This is for when we deliver messages across a route. We use this structure
// to make sure to only send one message and properly scope to queues as needed.
rts []routeTarget
prand *rand.Rand
msgs int
bytes int
subs int
rsz int // Read buffer size
srs int // Short reads, used for dynamic buffer resizing.
}
const (
maxPerAccountCacheSize = 32768
prunePerAccountCacheSize = 512
)
// perAccountCache is for L1 semantics for inbound messages from a route or gateway to mimic the performance of clients.
type perAccountCache struct {
acc *Account
results *SublistResult
genid uint64
}
func (c *client) String() (id string) {
return c.ncs
}
func (c *client) GetOpts() *clientOpts {
return &c.opts
}
// GetTLSConnectionState returns the TLS ConnectionState if TLS is enabled, nil
// otherwise. Implements the ClientAuth interface.
func (c *client) GetTLSConnectionState() *tls.ConnectionState {
tc, ok := c.nc.(*tls.Conn)
if !ok {
return nil
}
state := tc.ConnectionState()
return &state
}
// This is the main subscription struct that indicates
// interest in published messages.
// FIXME(dlc) - This is getting bloated for normal subs, need
// to optionally have an opts section for non-normal stuff.
type subscription struct {
client *client
im *streamImport // This is for import stream support.
shadow []*subscription // This is to track shadowed accounts.
subject []byte
queue []byte
sid []byte
nm int64
max int64
qw int32
}
type clientOpts struct {
Echo bool `json:"echo"`
Verbose bool `json:"verbose"`
Pedantic bool `json:"pedantic"`
TLSRequired bool `json:"tls_required"`
Nkey string `json:"nkey,omitempty"`
JWT string `json:"jwt,omitempty"`
Sig string `json:"sig,omitempty"`
Authorization string `json:"auth_token,omitempty"`
Username string `json:"user,omitempty"`
Password string `json:"pass,omitempty"`
Name string `json:"name"`
Lang string `json:"lang"`
Version string `json:"version"`
Protocol int `json:"protocol"`
Account string `json:"account,omitempty"`
AccountNew bool `json:"new_account,omitempty"`
// Routes only
Import *SubjectPermission `json:"import,omitempty"`
Export *SubjectPermission `json:"export,omitempty"`
}
var defaultOpts = clientOpts{Verbose: true, Pedantic: true, Echo: true}
func init() {
rand.Seed(time.Now().UnixNano())
}
// Lock should be held
func (c *client) initClient() {
s := c.srv
c.cid = atomic.AddUint64(&s.gcid, 1)
// Outbound data structure setup
c.out.sz = startBufSize
c.out.sg = sync.NewCond(&c.mu)
opts := s.getOpts()
// Snapshots to avoid mutex access in fast paths.
c.out.wdl = opts.WriteDeadline
c.out.mp = opts.MaxPending
c.subs = make(map[string]*subscription)
c.echo = true
c.debug = (atomic.LoadInt32(&c.srv.logging.debug) != 0)
c.trace = (atomic.LoadInt32(&c.srv.logging.trace) != 0)
// This is a scratch buffer used for processMsg()
// The msg header starts with "RMSG ", which can be used
// for both local and routes.
// in bytes that is [82 77 83 71 32].
c.msgb = [msgScratchSize]byte{82, 77, 83, 71, 32}
// This is to track pending clients that have data to be flushed
// after we process inbound msgs from our own connection.
c.pcd = make(map[*client]struct{})
// snapshot the string version of the connection
var conn string
if ip, ok := c.nc.(*net.TCPConn); ok {
addr := ip.RemoteAddr().(*net.TCPAddr)
c.host = addr.IP.String()
c.port = addr.Port
conn = fmt.Sprintf("%s:%d", addr.IP, addr.Port)
}
switch c.kind {
case CLIENT:
c.ncs = fmt.Sprintf("%s - cid:%d", conn, c.cid)
case ROUTER:
c.ncs = fmt.Sprintf("%s - rid:%d", conn, c.cid)
case GATEWAY:
c.ncs = fmt.Sprintf("%s - gid:%d", conn, c.cid)
case SYSTEM:
c.ncs = "SYSTEM"
}
}
// Helper function to report errors.
func (c *client) reportErrRegisterAccount(acc *Account, err error) {
if err == ErrTooManyAccountConnections {
c.maxAccountConnExceeded()
return
}
c.Errorf("Problem registering with account [%s]", acc.Name)
c.sendErr("Failed Account Registration")
}
// RegisterWithAccount will register the given user with a specific
// account. This will change the subject namespace.
func (c *client) registerWithAccount(acc *Account) error {
if acc == nil || acc.sl == nil {
return ErrBadAccount
}
// If we were previously registered, usually to $G, do accounting here to remove.
if c.acc != nil {
if prev := c.acc.removeClient(c); prev == 1 && c.srv != nil {
c.srv.decActiveAccounts()
}
}
// Check if we have a max connections violation
if acc.MaxTotalConnectionsReached() {
return ErrTooManyAccountConnections
}
// Add in new one.
if prev := acc.addClient(c); prev == 0 && c.srv != nil {
c.srv.incActiveAccounts()
}
c.mu.Lock()
c.acc = acc
c.applyAccountLimits()
c.mu.Unlock()
return nil
}
// Helper to determine if we have exceeded max subs.
func (c *client) subsExceeded() bool {
return c.msubs != jwt.NoLimit && len(c.subs) > c.msubs
}
// Helper to determine if we have met or exceeded max subs.
func (c *client) subsAtLimit() bool {
return c.msubs != jwt.NoLimit && len(c.subs) >= c.msubs
}
// Apply account limits
// Lock is held on entry.
// FIXME(dlc) - Should server be able to override here?
func (c *client) applyAccountLimits() {
if c.acc == nil {
return
}
// Set here, will need to fo checks for NoLimit.
if c.acc.msubs != jwt.NoLimit {
c.msubs = c.acc.msubs
}
if c.acc.mpay != jwt.NoLimit {
c.mpay = c.acc.mpay
}
opts := c.srv.getOpts()
// We check here if the server has an option set that is lower than the account limit.
if c.mpay != jwt.NoLimit && opts.MaxPayload != 0 && int32(opts.MaxPayload) < c.acc.mpay {
c.Errorf("Max Payload set to %d from server config which overrides %d from account claims", opts.MaxPayload, c.acc.mpay)
c.mpay = int32(opts.MaxPayload)
}
// We check here if the server has an option set that is lower than the account limit.
if c.msubs != jwt.NoLimit && opts.MaxSubs != 0 && opts.MaxSubs < c.acc.msubs {
c.Errorf("Max Subscriptions set to %d from server config which overrides %d from account claims", opts.MaxSubs, c.acc.msubs)
c.msubs = opts.MaxSubs
}
if c.subsExceeded() {
go func() {
c.maxSubsExceeded()
time.Sleep(20 * time.Millisecond)
c.closeConnection(MaxSubscriptionsExceeded)
}()
}
}
// RegisterUser allows auth to call back into a new client
// with the authenticated user. This is used to map
// any permissions into the client and setup accounts.
func (c *client) RegisterUser(user *User) {
// Register with proper account and sublist.
if user.Account != nil {
if err := c.registerWithAccount(user.Account); err != nil {
c.reportErrRegisterAccount(user.Account, err)
return
}
}
c.mu.Lock()
defer c.mu.Unlock()
// Assign permissions.
if user.Permissions == nil {
// Reset perms to nil in case client previously had them.
c.perms = nil
c.mperms = nil
return
}
c.setPermissions(user.Permissions)
}
// RegisterNkey allows auth to call back into a new nkey
// client with the authenticated user. This is used to map
// any permissions into the client and setup accounts.
func (c *client) RegisterNkeyUser(user *NkeyUser) {
// Register with proper account and sublist.
if user.Account != nil {
if err := c.registerWithAccount(user.Account); err != nil {
c.reportErrRegisterAccount(user.Account, err)
return
}
}
c.mu.Lock()
defer c.mu.Unlock()
c.user = user
// Assign permissions.
if user.Permissions == nil {
// Reset perms to nil in case client previously had them.
c.perms = nil
c.mperms = nil
return
}
c.setPermissions(user.Permissions)
}
// Initializes client.perms structure.
// Lock is held on entry.
func (c *client) setPermissions(perms *Permissions) {
if perms == nil {
return
}
c.perms = &permissions{}
c.perms.pcache = make(map[string]bool)
// Loop over publish permissions
if perms.Publish != nil {
if len(perms.Publish.Allow) > 0 {
c.perms.pub.allow = NewSublist()
}
for _, pubSubject := range perms.Publish.Allow {
sub := &subscription{subject: []byte(pubSubject)}
c.perms.pub.allow.Insert(sub)
}
if len(perms.Publish.Deny) > 0 {
c.perms.pub.deny = NewSublist()
}
for _, pubSubject := range perms.Publish.Deny {
sub := &subscription{subject: []byte(pubSubject)}
c.perms.pub.deny.Insert(sub)
}
}
// Loop over subscribe permissions
if perms.Subscribe != nil {
if len(perms.Subscribe.Allow) > 0 {
c.perms.sub.allow = NewSublist()
}
for _, subSubject := range perms.Subscribe.Allow {
sub := &subscription{subject: []byte(subSubject)}
c.perms.sub.allow.Insert(sub)
}
if len(perms.Subscribe.Deny) > 0 {
c.perms.sub.deny = NewSublist()
// Also hold onto this array for later.
c.darray = perms.Subscribe.Deny
}
for _, subSubject := range perms.Subscribe.Deny {
sub := &subscription{subject: []byte(subSubject)}
c.perms.sub.deny.Insert(sub)
}
}
}
// Check to see if we have an expiration for the user JWT via base claims.
// FIXME(dlc) - Clear on connect with new JWT.
func (c *client) checkExpiration(claims *jwt.ClaimsData) {
if claims.Expires == 0 {
return
}
tn := time.Now().Unix()
if claims.Expires < tn {
return
}
expiresAt := time.Duration(claims.Expires - tn)
c.setExpirationTimer(expiresAt * time.Second)
}
// This will load up the deny structure used for filtering delivered
// messages based on a deny clause for subscriptions.
// Lock should be held.
func (c *client) loadMsgDenyFilter() {
c.mperms = &msgDeny{NewSublist(), make(map[string]bool)}
for _, sub := range c.darray {
c.mperms.deny.Insert(&subscription{subject: []byte(sub)})
}
}
// writeLoop is the main socket write functionality.
// Runs in its own Go routine.
func (c *client) writeLoop() {
defer c.srv.grWG.Done()
// Used to check that we did flush from last wake up.
waitOk := true
// Main loop. Will wait to be signaled and then will use
// buffered outbound structure for efficient writev to the underlying socket.
for {
c.mu.Lock()
if waitOk && (c.out.pb == 0 || c.out.fsp > 0) && len(c.out.nb) == 0 && !c.flags.isSet(clearConnection) {
// Wait on pending data.
c.out.sg.Wait()
}
// Flush data
waitOk = c.flushOutbound()
isClosed := c.flags.isSet(clearConnection)
c.mu.Unlock()
if isClosed {
return
}
}
}
// readLoop is the main socket read functionality.
// Runs in its own Go routine.
func (c *client) readLoop() {
// Grab the connection off the client, it will be cleared on a close.
// We check for that after the loop, but want to avoid a nil dereference
c.mu.Lock()
nc := c.nc
s := c.srv
c.in.rsz = startBufSize
defer s.grWG.Done()
if c.gw != nil && c.gw.outbound {
defer c.gatewayOutboundConnectionReadLoopExited()
}
c.mu.Unlock()
if nc == nil {
return
}
// Start read buffer.
b := make([]byte, c.in.rsz)
for {
n, err := nc.Read(b)
if err != nil {
if err == io.EOF {
c.closeConnection(ClientClosed)
} else {
c.closeConnection(ReadError)
}
return
}
// Grab for updates for last activity.
last := time.Now()
// Clear inbound stats cache
c.in.msgs = 0
c.in.bytes = 0
c.in.subs = 0
// Main call into parser for inbound data. This will generate callouts
// to process messages, etc.
if err := c.parse(b[:n]); err != nil {
// handled inline
if err != ErrMaxPayload && err != ErrAuthentication {
c.Errorf("%s", err.Error())
c.closeConnection(ProtocolViolation)
}
return
}
// Updates stats for client and server that were collected
// from parsing through the buffer.
if c.in.msgs > 0 {
atomic.AddInt64(&c.inMsgs, int64(c.in.msgs))
atomic.AddInt64(&c.inBytes, int64(c.in.bytes))
atomic.AddInt64(&s.inMsgs, int64(c.in.msgs))
atomic.AddInt64(&s.inBytes, int64(c.in.bytes))
}
// Budget to spend in place flushing outbound data.
// Client will be checked on several fronts to see
// if applicable. Routes will never wait in place.
budget := 500 * time.Microsecond
if c.kind == ROUTER {
budget = 0
}
// Check pending clients for flush.
for cp := range c.pcd {
// Queue up a flush for those in the set
cp.mu.Lock()
// Update last activity for message delivery
cp.last = last
cp.out.fsp--
if budget > 0 && cp.flushOutbound() {
budget -= cp.out.lft
} else {
cp.flushSignal()
}
cp.mu.Unlock()
delete(c.pcd, cp)
}
// Update activity, check read buffer size.
c.mu.Lock()
nc := c.nc
// Activity based on interest changes or data/msgs.
if c.in.msgs > 0 || c.in.subs > 0 {
c.last = last
}
if n >= cap(b) {
c.in.srs = 0
} else if n < cap(b)/2 { // divide by 2 b/c we want less than what we would shrink to.
c.in.srs++
}
// Update read buffer size as/if needed.
if n >= cap(b) && cap(b) < maxBufSize {
// Grow
c.in.rsz = cap(b) * 2
b = make([]byte, c.in.rsz)
} else if n < cap(b) && cap(b) > minBufSize && c.in.srs > shortsToShrink {
// Shrink, for now don't accelerate, ping/pong will eventually sort it out.
c.in.rsz = cap(b) / 2
b = make([]byte, c.in.rsz)
}
c.mu.Unlock()
// Check to see if we got closed, e.g. slow consumer
if nc == nil {
return
}
}
}
// collapsePtoNB will place primary onto nb buffer as needed in prep for WriteTo.
// This will return a copy on purpose.
func (c *client) collapsePtoNB() net.Buffers {
if c.out.p != nil {
p := c.out.p
c.out.p = nil
return append(c.out.nb, p)
}
return c.out.nb
}
// This will handle the fixup needed on a partial write.
// Assume pending has been already calculated correctly.
func (c *client) handlePartialWrite(pnb net.Buffers) {
nb := c.collapsePtoNB()
// The partial needs to be first, so append nb to pnb
c.out.nb = append(pnb, nb...)
}
// flushOutbound will flush outbound buffer to a client.
// Will return if data was attempted to be written.
// Lock must be held
func (c *client) flushOutbound() bool {
if c.flags.isSet(flushOutbound) {
return false
}
c.flags.set(flushOutbound)
defer c.flags.clear(flushOutbound)
// Check for nothing to do.
if c.nc == nil || c.srv == nil || c.out.pb == 0 {
return true // true because no need to queue a signal.
}
// Snapshot opts
srv := c.srv
// Place primary on nb, assign primary to secondary, nil out nb and secondary.
nb := c.collapsePtoNB()
c.out.p, c.out.nb, c.out.s = c.out.s, nil, nil
// For selecting primary replacement.
cnb := nb
// In case it goes away after releasing the lock.
nc := c.nc
attempted := c.out.pb
apm := c.out.pm
// Do NOT hold lock during actual IO
c.mu.Unlock()
// flush here
now := time.Now()
// FIXME(dlc) - writev will do multiple IOs past 1024 on
// most platforms, need to account for that with deadline?
nc.SetWriteDeadline(now.Add(c.out.wdl))
// Actual write to the socket.
n, err := nb.WriteTo(nc)
nc.SetWriteDeadline(time.Time{})
lft := time.Since(now)
// Re-acquire client lock
c.mu.Lock()
// Update flush time statistics
c.out.lft = lft
// Subtract from pending bytes and messages.
c.out.pb -= n
c.out.pm -= apm // FIXME(dlc) - this will not be accurate.
// Check for partial writes
if n != attempted && n > 0 {
c.handlePartialWrite(nb)
} else if n >= int64(c.out.sz) {
c.out.sws = 0
}
if err != nil {
if n == 0 {
c.out.pb -= attempted
}
if ne, ok := err.(net.Error); ok && ne.Timeout() {
// report slow consumer error
sce := true
if tlsConn, ok := c.nc.(*tls.Conn); ok {
if !tlsConn.ConnectionState().HandshakeComplete {
// Likely a TLSTimeout error instead...
c.clearConnection(TLSHandshakeError)
// Would need to coordinate with tlstimeout()
// to avoid double logging, so skip logging
// here, and don't report a slow consumer error.
sce = false
}
}
if sce {
atomic.AddInt64(&srv.slowConsumers, 1)
c.clearConnection(SlowConsumerWriteDeadline)
c.Noticef("Slow Consumer Detected: WriteDeadline of %v Exceeded", c.out.wdl)
}
} else {
c.clearConnection(WriteError)
c.Debugf("Error flushing: %v", err)
}
return true
}
// Adjust based on what we wrote plus any pending.
pt := int(n + c.out.pb)
// Adjust sz as needed downward, keeping power of 2.
// We do this at a slower rate, hence the pt*4.
if pt < c.out.sz && c.out.sz > minBufSize {
c.out.sws++
if c.out.sws > shortsToShrink {
c.out.sz >>= 1
}
}
// Adjust sz as needed upward, keeping power of 2.
if pt > c.out.sz && c.out.sz < maxBufSize {
c.out.sz <<= 1
}
// Check to see if we can reuse buffers.
if len(cnb) > 0 {
oldp := cnb[0][:0]
if cap(oldp) >= c.out.sz {
// Replace primary or secondary if they are nil, reusing same buffer.
if c.out.p == nil {
c.out.p = oldp
} else if c.out.s == nil || cap(c.out.s) < c.out.sz {
c.out.s = oldp
}
}
}
return true
}
// flushSignal will use server to queue the flush IO operation to a pool of flushers.
// Lock must be held.
func (c *client) flushSignal() {
c.out.sg.Signal()
}
func (c *client) traceMsg(msg []byte) {
if !c.trace {
return
}
// FIXME(dlc), allow limits to printable payload.
c.Tracef("<<- MSG_PAYLOAD: [%q]", msg[:len(msg)-LEN_CR_LF])
}
func (c *client) traceInOp(op string, arg []byte) {
c.traceOp("<<- %s", op, arg)
}
func (c *client) traceOutOp(op string, arg []byte) {
c.traceOp("->> %s", op, arg)
}
func (c *client) traceOp(format, op string, arg []byte) {
if !c.trace {
return
}
opa := []interface{}{}
if op != "" {
opa = append(opa, op)
}
if arg != nil {
opa = append(opa, string(arg))
}
c.Tracef(format, opa)
}
// Process the information messages from Clients and other Routes.
func (c *client) processInfo(arg []byte) error {
info := Info{}
if err := json.Unmarshal(arg, &info); err != nil {
return err
}
switch c.kind {
case ROUTER:
c.processRouteInfo(&info)
case GATEWAY:
c.processGatewayInfo(&info)
}
return nil
}
func (c *client) processErr(errStr string) {
switch c.kind {
case CLIENT:
c.Errorf("Client Error %s", errStr)
case ROUTER:
c.Errorf("Route Error %s", errStr)
case GATEWAY:
c.Errorf("Gateway Error %s", errStr)
}
c.closeConnection(ParseError)
}
// Password pattern matcher.
var passPat = regexp.MustCompile(`"?\s*pass\S*?"?\s*[:=]\s*"?(([^",\r\n}])*)`)
// removePassFromTrace removes any notion of passwords from trace
// messages for logging.
func removePassFromTrace(arg []byte) []byte {
if !bytes.Contains(arg, []byte(`pass`)) {
return arg
}
// Take a copy of the connect proto just for the trace message.
var _arg [4096]byte
buf := append(_arg[:0], arg...)
m := passPat.FindAllSubmatchIndex(buf, -1)
if len(m) == 0 {
return arg
}
redactedPass := []byte("[REDACTED]")
for _, i := range m {
if len(i) < 4 {
continue
}
start := i[2]
end := i[3]
// Replace password substring.
buf = append(buf[:start], append(redactedPass, buf[end:]...)...)
break
}
return buf
}
func (c *client) processConnect(arg []byte) error {
if c.trace {
c.traceInOp("CONNECT", removePassFromTrace(arg))
}
c.mu.Lock()
// If we can't stop the timer because the callback is in progress...
if !c.clearAuthTimer() {
// wait for it to finish and handle sending the failure back to
// the client.
for c.nc != nil {
c.mu.Unlock()
time.Sleep(25 * time.Millisecond)
c.mu.Lock()
}
c.mu.Unlock()
return nil
}
c.last = time.Now()
kind := c.kind
srv := c.srv
// Moved unmarshalling of clients' Options under the lock.
// The client has already been added to the server map, so it is possible
// that other routines lookup the client, and access its options under
// the client's lock, so unmarshalling the options outside of the lock
// would cause data RACEs.
if err := json.Unmarshal(arg, &c.opts); err != nil {
c.mu.Unlock()
return err
}
// Indicate that the CONNECT protocol has been received, and that the
// server now knows which protocol this client supports.
c.flags.set(connectReceived)
// Capture these under lock
c.echo = c.opts.Echo
proto := c.opts.Protocol
verbose := c.opts.Verbose
lang := c.opts.Lang
account := c.opts.Account
accountNew := c.opts.AccountNew
c.mu.Unlock()
if srv != nil {
// Applicable to clients only:
// As soon as c.opts is unmarshalled and if the proto is at
// least ClientProtoInfo, we need to increment the following counter.
// This is decremented when client is removed from the server's
// clients map.
if kind == CLIENT && proto >= ClientProtoInfo {
srv.mu.Lock()
srv.cproto++
srv.mu.Unlock()
}
// Check for Auth
if ok := srv.checkAuthentication(c); !ok {
c.authViolation()
return ErrAuthentication
}
// Check for Account designation
if account != "" {
var acc *Account
var wasNew bool
var err error
if !srv.NewAccountsAllowed() {
acc, err = srv.LookupAccount(account)
if err != nil {
c.Errorf(err.Error())
c.sendErr("Account Not Found")
return err
} else if accountNew && acc != nil {
c.Errorf(ErrAccountExists.Error())
c.sendErr(ErrAccountExists.Error())
return ErrAccountExists
}
} else {
// We can create this one on the fly.
acc, wasNew = srv.LookupOrRegisterAccount(account)
if accountNew && !wasNew {
c.Errorf(ErrAccountExists.Error())
c.sendErr(ErrAccountExists.Error())
return ErrAccountExists
}
}
// If we are here we can register ourselves with the new account.
if err := c.registerWithAccount(acc); err != nil {
c.reportErrRegisterAccount(acc, err)
return ErrBadAccount
}
} else if c.acc == nil {
// By default register with the global account.
c.registerWithAccount(srv.gacc)
}
}
switch kind {
case CLIENT:
// Check client protocol request if it exists.
if proto < ClientProtoZero || proto > ClientProtoInfo {
c.sendErr(ErrBadClientProtocol.Error())
c.closeConnection(BadClientProtocolVersion)
return ErrBadClientProtocol
}
if verbose {
c.sendOK()
}
case ROUTER:
// Delegate the rest of processing to the route
return c.processRouteConnect(srv, arg, lang)
case GATEWAY:
// Delegate the rest of processing to the gateway
return c.processGatewayConnect(arg)
}
return nil
}
func (c *client) sendErrAndErr(err string) {
c.sendErr(err)
c.Errorf(err)
}
func (c *client) sendErrAndDebug(err string) {
c.sendErr(err)
c.Debugf(err)
}
func (c *client) authTimeout() {
c.sendErrAndDebug("Authentication Timeout")
c.closeConnection(AuthenticationTimeout)
}
func (c *client) authExpired() {
c.sendErrAndDebug("User Authentication Expired")
c.closeConnection(AuthenticationExpired)
}
func (c *client) accountAuthExpired() {
c.sendErrAndDebug("Account Authentication Expired")
c.closeConnection(AuthenticationExpired)
}
func (c *client) authViolation() {
var hasTrustedNkeys, hasNkeys, hasUsers bool
if s := c.srv; s != nil {
s.mu.Lock()
hasTrustedNkeys = len(s.trustedKeys) > 0
hasNkeys = s.nkeys != nil
hasUsers = s.users != nil
s.mu.Unlock()
}
if hasTrustedNkeys {
c.Errorf("%v", ErrAuthentication)
} else if hasNkeys {
c.Errorf("%s - Nkey %q",
ErrAuthentication.Error(),
c.opts.Nkey)
} else if hasUsers {
c.Errorf("%s - User %q",
ErrAuthentication.Error(),
c.opts.Username)
} else {
c.Errorf(ErrAuthentication.Error())
}
c.sendErr("Authorization Violation")
c.closeConnection(AuthenticationViolation)
}
func (c *client) maxAccountConnExceeded() {
c.sendErrAndErr(ErrTooManyAccountConnections.Error())
c.closeConnection(MaxAccountConnectionsExceeded)
}
func (c *client) maxConnExceeded() {
c.sendErrAndErr(ErrTooManyConnections.Error())
c.closeConnection(MaxConnectionsExceeded)
}
func (c *client) maxSubsExceeded() {
c.sendErrAndErr(ErrTooManySubs.Error())
}
func (c *client) maxPayloadViolation(sz int, max int32) {
c.Errorf("%s: %d vs %d", ErrMaxPayload.Error(), sz, max)
c.sendErr("Maximum Payload Violation")
c.closeConnection(MaxPayloadExceeded)
}
// queueOutbound queues data for client/route connections.
// Return if the data is referenced or not. If referenced, the caller
// should not reuse the `data` array.
// Lock should be held.
func (c *client) queueOutbound(data []byte) bool {
// Assume data will not be referenced
referenced := false
// Add to pending bytes total.
c.out.pb += int64(len(data))
// Check for slow consumer via pending bytes limit.
// ok to return here, client is going away.
if c.out.pb > c.out.mp {
c.clearConnection(SlowConsumerPendingBytes)
atomic.AddInt64(&c.srv.slowConsumers, 1)
c.Noticef("Slow Consumer Detected: MaxPending of %d Exceeded", c.out.mp)
return referenced
}
if c.out.p == nil && len(data) < maxBufSize {
if c.out.sz == 0 {
c.out.sz = startBufSize
}
if c.out.s != nil && cap(c.out.s) >= c.out.sz {
c.out.p = c.out.s
c.out.s = nil
} else {
// FIXME(dlc) - make power of 2 if less than maxBufSize?
c.out.p = make([]byte, 0, c.out.sz)
}
}
// Determine if we copy or reference
available := cap(c.out.p) - len(c.out.p)
if len(data) > available {
// We can fit into existing primary, but message will fit in next one
// we allocate or utilize from the secondary. So copy what we can.
if available > 0 && len(data) < c.out.sz {
c.out.p = append(c.out.p, data[:available]...)
data = data[available:]
}
// Put the primary on the nb if it has a payload
if len(c.out.p) > 0 {
c.out.nb = append(c.out.nb, c.out.p)
c.out.p = nil
}
// Check for a big message, and if found place directly on nb
// FIXME(dlc) - do we need signaling of ownership here if we want len(data) < maxBufSize
if len(data) > maxBufSize {
c.out.nb = append(c.out.nb, data)
referenced = true
} else {
// We will copy to primary.
if c.out.p == nil {
// Grow here
if (c.out.sz << 1) <= maxBufSize {
c.out.sz <<= 1
}
if len(data) > c.out.sz {
c.out.p = make([]byte, 0, len(data))
} else {
if c.out.s != nil && cap(c.out.s) >= c.out.sz { // TODO(dlc) - Size mismatch?
c.out.p = c.out.s
c.out.s = nil
} else {
c.out.p = make([]byte, 0, c.out.sz)
}
}
}
c.out.p = append(c.out.p, data...)
}
} else {
c.out.p = append(c.out.p, data...)
}
return referenced
}
// Assume the lock is held upon entry.
func (c *client) sendProto(info []byte, doFlush bool) {
if c.nc == nil {
return
}
c.queueOutbound(info)
if !(doFlush && c.flushOutbound()) {
c.flushSignal()
}
}
// Assume the lock is held upon entry.
func (c *client) sendPong() {
c.traceOutOp("PONG", nil)
c.sendProto([]byte("PONG\r\n"), true)
}
// Assume the lock is held upon entry.
func (c *client) sendPing() {
c.rttStart = time.Now()
c.ping.out++
c.traceOutOp("PING", nil)
c.sendProto([]byte("PING\r\n"), true)
}
// Generates the INFO to be sent to the client with the client ID included.
// info arg will be copied since passed by value.
// Assume lock is held.
func (c *client) generateClientInfoJSON(info Info) []byte {
info.CID = c.cid
// Generate the info json
b, _ := json.Marshal(info)
pcs := [][]byte{[]byte("INFO"), b, []byte(CR_LF)}
return bytes.Join(pcs, []byte(" "))
}
// Assume the lock is held upon entry.
func (c *client) sendInfo(info []byte) {
c.sendProto(info, true)
}
func (c *client) sendErr(err string) {
c.mu.Lock()
c.traceOutOp("-ERR", []byte(err))
c.sendProto([]byte(fmt.Sprintf("-ERR '%s'\r\n", err)), true)
c.mu.Unlock()
}
func (c *client) sendOK() {
c.mu.Lock()
c.traceOutOp("OK", nil)
// Can not autoflush this one, needs to be async.
c.sendProto([]byte("+OK\r\n"), false)
// FIXME(dlc) - ??
c.pcd[c] = needFlush
c.mu.Unlock()
}
func (c *client) processPing() {
c.mu.Lock()
c.traceInOp("PING", nil)
if c.nc == nil {
c.mu.Unlock()
return
}
c.sendPong()
// If not a CLIENT, we are done
if c.kind != CLIENT {
c.mu.Unlock()
return
}
// The CONNECT should have been received, but make sure it
// is so before proceeding
if !c.flags.isSet(connectReceived) {
c.mu.Unlock()
return
}
// If we are here, the CONNECT has been received so we know
// if this client supports async INFO or not.
var (
checkClusterChange bool
srv = c.srv
)
// For older clients, just flip the firstPongSent flag if not already
// set and we are done.
if c.opts.Protocol < ClientProtoInfo || srv == nil {
c.flags.setIfNotSet(firstPongSent)
} else {
// This is a client that supports async INFO protocols.
// If this is the first PING (so firstPongSent is not set yet),
// we will need to check if there was a change in cluster topology.
checkClusterChange = !c.flags.isSet(firstPongSent)
}
c.mu.Unlock()
if checkClusterChange {
srv.mu.Lock()
c.mu.Lock()
// Now that we are under both locks, we can flip the flag.
// This prevents sendAsyncInfoToClients() and and code here
// to send a double INFO protocol.
c.flags.set(firstPongSent)
// If there was a cluster update since this client was created,
// send an updated INFO protocol now.
if srv.lastCURLsUpdate >= c.start.UnixNano() {
c.sendInfo(c.generateClientInfoJSON(srv.copyInfo()))
}
c.mu.Unlock()
srv.mu.Unlock()
}
}
func (c *client) processPong() {
c.traceInOp("PONG", nil)
c.mu.Lock()
c.ping.out = 0
c.rtt = time.Since(c.rttStart)
srv := c.srv
reorderGWs := c.kind == GATEWAY && c.gw.outbound
c.mu.Unlock()
if reorderGWs {
srv.gateway.orderOutboundConnections()
}
}
func (c *client) processPub(trace bool, arg []byte) error {
if trace {
c.traceInOp("PUB", arg)
}
// Unroll splitArgs to avoid runtime/heap issues
a := [MAX_PUB_ARGS][]byte{}
args := a[:0]
start := -1
for i, b := range arg {
switch b {
case ' ', '\t':
if start >= 0 {
args = append(args, arg[start:i])
start = -1
}
default:
if start < 0 {
start = i
}
}
}
if start >= 0 {
args = append(args, arg[start:])
}
c.pa.arg = arg
switch len(args) {
case 2:
c.pa.subject = args[0]
c.pa.reply = nil
c.pa.size = parseSize(args[1])
c.pa.szb = args[1]
case 3:
c.pa.subject = args[0]
c.pa.reply = args[1]
c.pa.size = parseSize(args[2])
c.pa.szb = args[2]
default:
return fmt.Errorf("processPub Parse Error: '%s'", arg)
}
if c.pa.size < 0 {
return fmt.Errorf("processPub Bad or Missing Size: '%s'", arg)
}
maxPayload := atomic.LoadInt32(&c.mpay)
if maxPayload != jwt.NoLimit && int32(c.pa.size) > maxPayload {
c.maxPayloadViolation(c.pa.size, maxPayload)
return ErrMaxPayload
}
if c.opts.Pedantic && !IsValidLiteralSubject(string(c.pa.subject)) {
c.sendErr("Invalid Publish Subject")
}
return nil
}
func splitArg(arg []byte) [][]byte {
a := [MAX_MSG_ARGS][]byte{}
args := a[:0]
start := -1
for i, b := range arg {
switch b {
case ' ', '\t', '\r', '\n':
if start >= 0 {
args = append(args, arg[start:i])
start = -1
}
default:
if start < 0 {
start = i
}
}
}
if start >= 0 {
args = append(args, arg[start:])
}
return args
}
func (c *client) processSub(argo []byte) (err error) {
c.traceInOp("SUB", argo)
// Indicate activity.
c.in.subs++
// Copy so we do not reference a potentially large buffer
// FIXME(dlc) - make more efficient.
arg := make([]byte, len(argo))
copy(arg, argo)
args := splitArg(arg)
sub := &subscription{client: c}
switch len(args) {
case 2:
sub.subject = args[0]
sub.queue = nil
sub.sid = args[1]
case 3:
sub.subject = args[0]
sub.queue = args[1]
sub.sid = args[2]
default:
return fmt.Errorf("processSub Parse Error: '%s'", arg)
}
c.mu.Lock()
// Grab connection type.
kind := c.kind
if c.nc == nil && kind != SYSTEM {
c.mu.Unlock()
return nil
}
// Check permissions if applicable.
if kind == ROUTER {
if !c.canExport(string(sub.subject)) {
c.mu.Unlock()
return nil
}
} else if kind == CLIENT && !c.canSubscribe(string(sub.subject)) {
c.mu.Unlock()
c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
c.Errorf("Subscription Violation - User %q, Subject %q, SID %s",
c.opts.Username, sub.subject, sub.sid)
return nil
}
// Check if we have a maximum on the number of subscriptions.
if c.subsAtLimit() {
c.mu.Unlock()
c.maxSubsExceeded()
return nil
}
sid := string(sub.sid)
acc := c.acc
updateGWs := false
// Subscribe here.
if c.subs[sid] == nil {
c.subs[sid] = sub
if acc != nil && acc.sl != nil {
err = acc.sl.Insert(sub)
if err != nil {
delete(c.subs, sid)
} else {
updateGWs = c.srv.gateway.enabled
}
}
}
c.mu.Unlock()
if err != nil {
c.sendErr("Invalid Subject")
return nil
} else if c.opts.Verbose && kind != SYSTEM {
c.sendOK()
}
if acc != nil {
if err := c.addShadowSubscriptions(acc, sub); err != nil {
c.Errorf(err.Error())
}
// If we are routing and this is a local sub, add to the route map for the associated account.
if kind == CLIENT || kind == SYSTEM {
c.srv.updateRouteSubscriptionMap(acc, sub, 1)
if updateGWs {
c.srv.gatewayUpdateSubInterest(acc.Name, sub, 1)
}
}
}
return nil
}
// If the client's account has stream imports and there are matches for
// this subscription's subject, then add shadow subscriptions in
// other accounts that can export this subject.
func (c *client) addShadowSubscriptions(acc *Account, sub *subscription) error {
if acc == nil {
return ErrMissingAccount
}
var (
rims [32]*streamImport
ims = rims[:0]
rfroms [32]*streamImport
froms = rfroms[:0]
tokens []string
tsa [32]string
hasWC bool
)
acc.mu.RLock()
// Loop over the import subjects. We have 3 scenarios. If we exact
// match or we know the proposed subject is a strict subset of the
// import we can subscribe to the subscription's subject directly.
// The third scenario is where the proposed subject has a wildcard
// and may not be an exact subset, but is a match. Therefore we have to
// subscribe to the import subject, not the subscription's subject.
for _, im := range acc.imports.streams {
if im.invalid {
continue
}
subj := string(sub.subject)
if subj == im.prefix+im.from {
ims = append(ims, im)
continue
}
if tokens == nil {
tokens = tsa[:0]
start := 0
for i := 0; i < len(subj); i++ {
// This is not perfect, but the test below will
// be more exact, this is just to trigger the
// additional test.
if subj[i] == pwc || subj[i] == fwc {
hasWC = true
} else if subj[i] == btsep {
tokens = append(tokens, subj[start:i])
start = i + 1
}
}
tokens = append(tokens, subj[start:])
}
if isSubsetMatch(tokens, im.prefix+im.from) {
ims = append(ims, im)
} else if hasWC {
if subjectIsSubsetMatch(im.prefix+im.from, subj) {
froms = append(froms, im)
}
}
}
acc.mu.RUnlock()
var shadow []*subscription
if len(ims) > 0 || len(froms) > 0 {
shadow = make([]*subscription, 0, len(ims)+len(froms))
}
// Now walk through collected importMaps
for _, im := range ims {
// We will create a shadow subscription.
nsub, err := c.addShadowSub(sub, im, false)
if err != nil {
return err
}
shadow = append(shadow, nsub)
}
// Now walk through importMaps that we need to subscribe
// exactly to the from property.
for _, im := range froms {
// We will create a shadow subscription.
nsub, err := c.addShadowSub(sub, im, true)
if err != nil {
return err
}
shadow = append(shadow, nsub)
}
if shadow != nil {
c.mu.Lock()
sub.shadow = shadow
c.mu.Unlock()
}
return nil
}
// Add in the shadow subscription.
func (c *client) addShadowSub(sub *subscription, im *streamImport, useFrom bool) (*subscription, error) {
nsub := *sub // copy
nsub.im = im
if useFrom {
nsub.subject = []byte(im.from)
} else if im.prefix != "" {
// redo subject here to match subject in the publisher account space.
// Just remove prefix from what they gave us. That maps into other space.
nsub.subject = sub.subject[len(im.prefix):]
}
c.Debugf("Creating import subscription on %q from account %q", nsub.subject, im.acc.Name)
if err := im.acc.sl.Insert(&nsub); err != nil {
errs := fmt.Sprintf("Could not add shadow import subscription for account %q", im.acc.Name)
c.Debugf(errs)
return nil, fmt.Errorf(errs)
}
// Update our route map here.
c.srv.updateRouteSubscriptionMap(im.acc, &nsub, 1)
return &nsub, nil
}
// canSubscribe determines if the client is authorized to subscribe to the
// given subject. Assumes caller is holding lock.
func (c *client) canSubscribe(subject string) bool {
if c.perms == nil {
return true
}
allowed := true
// Check allow list. If no allow list that means all are allowed. Deny can overrule.
if c.perms.sub.allow != nil {
r := c.perms.sub.allow.Match(subject)
allowed = len(r.psubs) != 0
}
// If we have a deny list and we think we are allowed, check that as well.
if allowed && c.perms.sub.deny != nil {
r := c.perms.sub.deny.Match(subject)
allowed = len(r.psubs) == 0
// We use the actual subscription to signal us to spin up the deny mperms
// and cache. We check if the subject is a wildcard that contains any of
// the deny clauses.
// FIXME(dlc) - We could be smarter and track when these go away and remove.
if allowed && c.mperms == nil && subjectHasWildcard(subject) {
// Whip through the deny array and check if this wildcard subject is within scope.
for _, sub := range c.darray {
tokens := strings.Split(sub, tsep)
if isSubsetMatch(tokens, sub) {
c.loadMsgDenyFilter()
break
}
}
}
}
return allowed
}
// Low level unsubscribe for a given client.
func (c *client) unsubscribe(acc *Account, sub *subscription, force bool) {
c.mu.Lock()
defer c.mu.Unlock()
if !force && sub.max > 0 && sub.nm < sub.max {
c.Debugf(
"Deferring actual UNSUB(%s): %d max, %d received",
string(sub.subject), sub.max, sub.nm)
return
}
c.traceOp("<-> %s", "DELSUB", sub.sid)
delete(c.subs, string(sub.sid))
if c.kind != CLIENT && c.kind != SYSTEM {
c.removeReplySubTimeout(sub)
}
if acc != nil {
acc.sl.Remove(sub)
}
// Check to see if we have shadow subscriptions.
for _, nsub := range sub.shadow {
if err := nsub.im.acc.sl.Remove(nsub); err != nil {
c.Debugf("Could not remove shadow import subscription for account %q", nsub.im.acc.Name)
} else if c.kind == CLIENT || c.kind == SYSTEM && c.srv != nil {
c.srv.updateRouteSubscriptionMap(nsub.im.acc, nsub, -1)
}
}
sub.shadow = nil
}
func (c *client) processUnsub(arg []byte) error {
c.traceInOp("UNSUB", arg)
args := splitArg(arg)
var sid []byte
max := -1
switch len(args) {
case 1:
sid = args[0]
case 2:
sid = args[0]
max = parseSize(args[1])
default:
return fmt.Errorf("processUnsub Parse Error: '%s'", arg)
}
// Indicate activity.
c.in.subs++
var sub *subscription
unsub := false
ok := false
c.mu.Lock()
// Grab connection type.
kind := c.kind
var acc *Account
updateGWs := false
if sub, ok = c.subs[string(sid)]; ok {
acc = c.acc
if max > 0 {
sub.max = int64(max)
} else {
// Clear it here to override
sub.max = 0
unsub = true
}
updateGWs = c.srv.gateway.enabled
}
c.mu.Unlock()
if c.opts.Verbose {
c.sendOK()
}
if unsub {
c.unsubscribe(acc, sub, false)
if acc != nil && kind == CLIENT || kind == SYSTEM {
c.srv.updateRouteSubscriptionMap(acc, sub, -1)
if updateGWs {
c.srv.gatewayUpdateSubInterest(acc.Name, sub, -1)
}
}
}
return nil
}
// checkDenySub will check if we are allowed to deliver this message in the
// presence of deny clauses for subscriptions. Deny clauses will not prevent
// larger scoped wildcard subscriptions, so we need to check at delivery time.
// Lock should be held.
func (c *client) checkDenySub(subject string) bool {
if denied, ok := c.mperms.dcache[subject]; ok {
return denied
} else if r := c.mperms.deny.Match(subject); len(r.psubs) != 0 {
c.mperms.dcache[subject] = true
return true
} else {
c.mperms.dcache[subject] = false
}
if len(c.mperms.dcache) > maxDenyPermCacheSize {
c.pruneDenyCache()
}
return false
}
func (c *client) msgHeader(mh []byte, sub *subscription, reply []byte) []byte {
if len(sub.sid) > 0 {
mh = append(mh, sub.sid...)
mh = append(mh, ' ')
}
if reply != nil {
mh = append(mh, reply...)
mh = append(mh, ' ')
}
mh = append(mh, c.pa.szb...)
mh = append(mh, _CRLF_...)
return mh
}
// Used to treat maps as efficient set
var needFlush = struct{}{}
func (c *client) deliverMsg(sub *subscription, mh, msg []byte) bool {
if sub.client == nil {
return false
}
client := sub.client
client.mu.Lock()
// Check echo
if c == client && !client.echo {
client.mu.Unlock()
return false
}
// Check if we have a subscribe deny clause. This will trigger us to check the subject
// for a match against the denied subjects.
if client.mperms != nil && client.checkDenySub(string(c.pa.subject)) {
client.mu.Unlock()
return false
}
srv := client.srv
sub.nm++
// Check if we should auto-unsubscribe.
if sub.max > 0 {
if client.kind == ROUTER && sub.nm >= sub.max {
// The only router based messages that we will see here are remoteReplies.
// We handle these slightly differently.
defer client.removeReplySub(sub)
} else {
// For routing..
shouldForward := client.kind == CLIENT || client.kind == SYSTEM && client.srv != nil
// If we are at the exact number, unsubscribe but
// still process the message in hand, otherwise
// unsubscribe and drop message on the floor.
if sub.nm == sub.max {
client.Debugf("Auto-unsubscribe limit of %d reached for sid '%s'", sub.max, string(sub.sid))
// Due to defer, reverse the code order so that execution
// is consistent with other cases where we unsubscribe.
if shouldForward {
defer srv.updateRouteSubscriptionMap(client.acc, sub, -1)
}
defer client.unsubscribe(client.acc, sub, true)
} else if sub.nm > sub.max {
client.Debugf("Auto-unsubscribe limit [%d] exceeded", sub.max)
client.mu.Unlock()
client.unsubscribe(client.acc, sub, true)
if shouldForward {
srv.updateRouteSubscriptionMap(client.acc, sub, -1)
}
return false
}
}
}
// Update statistics
// The msg includes the CR_LF, so pull back out for accounting.
msgSize := int64(len(msg) - LEN_CR_LF)
// No atomic needed since accessed under client lock.
// Monitor is reading those also under client's lock.
client.outMsgs++
client.outBytes += msgSize
atomic.AddInt64(&srv.outMsgs, 1)
atomic.AddInt64(&srv.outBytes, msgSize)
// Check for internal subscription.
if client.kind == SYSTEM {
s := client.srv
client.mu.Unlock()
s.deliverInternalMsg(sub, c.pa.subject, c.pa.reply, msg[:msgSize])
return true
}
// Check for closed connection
if client.nc == nil {
client.mu.Unlock()
return false
}
// Queue to outbound buffer
client.queueOutbound(mh)
client.queueOutbound(msg)
client.out.pm++
// Check outbound threshold and queue IO flush if needed.
if client.out.pm > 1 && client.out.pb > maxBufSize*2 {
client.flushSignal()
}
if c.trace {
client.traceOutOp(string(mh[:len(mh)-LEN_CR_LF]), nil)
}
// Increment the flush pending signals if we are setting for the first time.
if _, ok := c.pcd[client]; !ok {
client.out.fsp++
}
client.mu.Unlock()
// Remember for when we return to the top of the loop.
c.pcd[client] = needFlush
return true
}
// pruneDenyCache will prune the deny cache via randomly
// deleting items. Doing so pruneSize items at a time.
// Lock must be held for this one since it is shared under
// deliverMsg.
func (c *client) pruneDenyCache() {
r := 0
for subject := range c.mperms.dcache {
delete(c.mperms.dcache, subject)
if r++; r > pruneSize {
break
}
}
}
// prunePubPermsCache will prune the cache via randomly
// deleting items. Doing so pruneSize items at a time.
func (c *client) prunePubPermsCache() {
r := 0
for subject := range c.perms.pcache {
delete(c.perms.pcache, subject)
if r++; r > pruneSize {
break
}
}
}
// pubAllowed checks on publish permissioning.
func (c *client) pubAllowed(subject string) bool {
if c.perms == nil || (c.perms.pub.allow == nil && c.perms.pub.deny == nil) {
return true
}
// Check if published subject is allowed if we have permissions in place.
allowed, ok := c.perms.pcache[subject]
if ok {
return allowed
}
// Cache miss, check allow then deny as needed.
if c.perms.pub.allow != nil {
r := c.perms.pub.allow.Match(subject)
allowed = len(r.psubs) != 0
} else {
// No entries means all are allowed. Deny will overrule as needed.
allowed = true
}
// If we have a deny list and are currently allowed, check that as well.
if allowed && c.perms.pub.deny != nil {
r := c.perms.pub.deny.Match(subject)
allowed = len(r.psubs) == 0
}
// Update our cache here.
c.perms.pcache[string(subject)] = allowed
// Prune if needed.
if len(c.perms.pcache) > maxPermCacheSize {
c.prunePubPermsCache()
}
return allowed
}
// Used to mimic client like replies.
const (
replyPrefix = "_R_."
replyPrefixLen = len(replyPrefix)
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
base = 62
)
// newServiceReply is used when rewriting replies that cross account boundaries.
// These will look like _R_.XXXXXXXX.
func (c *client) newServiceReply() []byte {
// Check to see if we have our own rand yet. Global rand
// has contention with lots of clients, etc.
if c.in.prand == nil {
c.in.prand = rand.New(rand.NewSource(time.Now().UnixNano()))
}
var b = [15]byte{'_', 'R', '_', '.'}
rn := c.in.prand.Int63()
for i, l := replyPrefixLen, rn; i < len(b); i++ {
b[i] = digits[l%base]
l /= base
}
return b[:]
}
// Test whether a reply subject is a service import reply.
func isServiceReply(reply []byte) bool {
return len(reply) > 3 && string(reply[:4]) == replyPrefix
}
// This will decide to call the client code or router code.
func (c *client) processInboundMsg(msg []byte) {
switch c.kind {
case CLIENT:
c.processInboundClientMsg(msg)
case ROUTER:
c.processInboundRoutedMsg(msg)
case GATEWAY:
c.processInboundGatewayMsg(msg)
}
}
// processInboundClientMsg is called to process an inbound msg from a client.
func (c *client) processInboundClientMsg(msg []byte) {
// Update statistics
// The msg includes the CR_LF, so pull back out for accounting.
c.in.msgs++
c.in.bytes += len(msg) - LEN_CR_LF
if c.trace {
c.traceMsg(msg)
}
// Check pub permissions
if c.perms != nil && (c.perms.pub.allow != nil || c.perms.pub.deny != nil) && !c.pubAllowed(string(c.pa.subject)) {
c.pubPermissionViolation(c.pa.subject)
return
}
// Now check for reserved replies. These are used for service imports.
if isServiceReply(c.pa.reply) {
c.replySubjectViolation(c.pa.reply)
return
}
if c.opts.Verbose {
c.sendOK()
}
// Mostly under testing scenarios.
if c.srv == nil || c.acc == nil {
return
}
// Match the subscriptions. We will use our own L1 map if
// it's still valid, avoiding contention on the shared sublist.
var r *SublistResult
var ok bool
genid := atomic.LoadUint64(&c.acc.sl.genid)
if genid == c.in.genid && c.in.results != nil {
r, ok = c.in.results[string(c.pa.subject)]
} else {
// Reset our L1 completely.
c.in.results = make(map[string]*SublistResult)
c.in.genid = genid
}
// Go back to the sublist data structure.
if !ok {
r = c.acc.sl.Match(string(c.pa.subject))
c.in.results[string(c.pa.subject)] = r
// Prune the results cache. Keeps us from unbounded growth. Random delete.
if len(c.in.results) > maxResultCacheSize {
n := 0
for subject := range c.in.results {
delete(c.in.results, subject)
if n++; n > pruneSize {
break
}
}
}
}
// Check to see if we need to map/route to another account.
if c.acc.imports.services != nil {
c.checkForImportServices(c.acc, msg)
}
var qa [16][]byte
queues := qa[:0]
// Check for no interest, short circuit if so.
// This is the fanout scale.
if len(r.psubs)+len(r.qsubs) > 0 {
var qnames *[][]byte
// If we have queue subs in this cluster, then if we run in gateway
// mode and the remote gateways have queue subs, then we need to
// collect the queue groups this message was sent to so that we
// exclude them when sending to gateways.
if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
qnames = &queues
}
c.processMsgResults(c.acc, r, msg, c.pa.subject, c.pa.reply, qnames)
}
// Now deal with gateways
if c.srv.gateway.enabled {
c.sendMsgToGateways(msg, queues)
}
}
// This checks and process import services by doing the mapping and sending the
// message onward if applicable.
func (c *client) checkForImportServices(acc *Account, msg []byte) {
if acc == nil || acc.imports.services == nil {
return
}
acc.mu.RLock()
rm := acc.imports.services[string(c.pa.subject)]
invalid := rm != nil && rm.invalid
acc.mu.RUnlock()
// Get the results from the other account for the mapped "to" subject.
// If we have been marked invalid simply return here.
if rm != nil && !invalid && rm.acc != nil && rm.acc.sl != nil {
var nrr []byte
if rm.ae {
acc.removeServiceImport(rm.from)
}
if c.pa.reply != nil {
// We want to remap this to provide anonymity.
nrr = c.newServiceReply()
rm.acc.addImplicitServiceImport(acc, string(nrr), string(c.pa.reply), true, nil)
}
// FIXME(dlc) - Do L1 cache trick from above.
rr := rm.acc.sl.Match(rm.to)
c.processMsgResults(rm.acc, rr, msg, []byte(rm.to), nrr, nil)
}
}
func (c *client) addSubToRouteTargets(sub *subscription) {
if c.in.rts == nil {
c.in.rts = make([]routeTarget, 0, routeTargetInit)
}
for i := range c.in.rts {
rt := &c.in.rts[i]
if rt.sub.client == sub.client {
if sub.queue != nil {
rt.qs = append(rt.qs, sub.queue...)
rt.qs = append(rt.qs, ' ')
}
return
}
}
// If we are here we do not have the sub yet in our list
// If we have to grow do so here.
if len(c.in.rts) == cap(c.in.rts) {
c.in.rts = append(c.in.rts, routeTarget{})
}
var rt *routeTarget
lrts := len(c.in.rts)
c.in.rts = c.in.rts[:lrts+1]
rt = &c.in.rts[lrts]
rt.sub = sub
rt.qs = rt._qs[:0]
if sub.queue != nil {
rt.qs = append(rt.qs, sub.queue...)
rt.qs = append(rt.qs, ' ')
}
}
// This processes the sublist results for a given message.
func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, subject, reply []byte, queues *[][]byte) {
// msg header for clients.
msgh := c.msgb[1:msgHeadProtoLen]
msgh = append(msgh, subject...)
msgh = append(msgh, ' ')
si := len(msgh)
// For sending messages across routes. Reset it if we have one.
// We reuse this data structure.
if c.in.rts != nil {
c.in.rts = c.in.rts[:0]
}
// Loop over all normal subscriptions that match.
for _, sub := range r.psubs {
// Check if this is a send to a ROUTER. We now process
// these after everything else.
if sub.client.kind == ROUTER {
if c.kind == ROUTER {
continue
}
c.addSubToRouteTargets(sub)
continue
} else if sub.client.kind == GATEWAY {
// Never send to gateway from here.
continue
}
// Check for stream import mapped subs. These apply to local subs only.
if sub.im != nil && sub.im.prefix != "" {
// Redo the subject here on the fly.
msgh = c.msgb[1:msgHeadProtoLen]
msgh = append(msgh, sub.im.prefix...)
msgh = append(msgh, subject...)
msgh = append(msgh, ' ')
si = len(msgh)
}
// Normal delivery
mh := c.msgHeader(msgh[:si], sub, reply)
c.deliverMsg(sub, mh, msg)
}
// If we are sourced from a route we need to have direct filtered queues.
if c.kind == ROUTER && c.pa.queues == nil {
return
}
// Set these up to optionally filter based on the queue lists.
// This is for messages received from routes which will have directed
// guidance on which queue groups we should deliver to.
qf := c.pa.queues
// For gateway connections, we still want to send messages to routes
// even if there is no queue filters.
if c.kind == GATEWAY && qf == nil {
goto sendToRoutes
}
// Check to see if we have our own rand yet. Global rand
// has contention with lots of clients, etc.
if c.in.prand == nil {
c.in.prand = rand.New(rand.NewSource(time.Now().UnixNano()))
}
// Process queue subs
for i := 0; i < len(r.qsubs); i++ {
qsubs := r.qsubs[i]
// If we have a filter check that here. We could make this a map or someting more
// complex but linear search since we expect queues to be small. Should be faster
// and more cache friendly.
if qf != nil && len(qsubs) > 0 {
tqn := qsubs[0].queue
for _, qn := range qf {
if bytes.Equal(qn, tqn) {
goto selectQSub
}
}
continue
}
selectQSub:
// We will hold onto remote qsubs when we are coming from a route
// just in case we can no longer do local delivery.
var rsub *subscription
// Find a subscription that is able to deliver this message
// starting at a random index.
startIndex := c.in.prand.Intn(len(qsubs))
for i := 0; i < len(qsubs); i++ {
index := (startIndex + i) % len(qsubs)
sub := qsubs[index]
if sub == nil {
continue
}
// Potentially sending to a remote sub across a route.
if sub.client.kind == ROUTER {
if c.kind == ROUTER {
// We just came from a route, so skip and prefer local subs.
// Keep our first rsub in case all else fails.
if rsub == nil {
rsub = sub
}
continue
} else {
c.addSubToRouteTargets(sub)
if queues != nil {
*queues = append(*queues, sub.queue)
}
}
break
}
// Check for mapped subs
if sub.im != nil && sub.im.prefix != "" {
// Redo the subject here on the fly.
msgh = c.msgb[1:msgHeadProtoLen]
msgh = append(msgh, sub.im.prefix...)
msgh = append(msgh, subject...)
msgh = append(msgh, ' ')
si = len(msgh)
}
mh := c.msgHeader(msgh[:si], sub, reply)
if c.deliverMsg(sub, mh, msg) {
// Clear rsub
rsub = nil
if queues != nil {
*queues = append(*queues, sub.queue)
}
break
}
}
if rsub != nil {
// If we are here we tried to deliver to a local qsub
// but failed. So we will send it to a remote.
c.addSubToRouteTargets(rsub)
if queues != nil {
*queues = append(*queues, rsub.queue)
}
}
}
sendToRoutes:
// If no messages for routes return here.
if len(c.in.rts) == 0 {
return
}
// We address by index to avoid struct copy.
// We have inline structs for memory layout and cache coherency.
for i := range c.in.rts {
rt := &c.in.rts[i]
mh := c.msgb[:msgHeadProtoLen]
mh = append(mh, acc.Name...)
mh = append(mh, ' ')
mh = append(mh, subject...)
mh = append(mh, ' ')
if len(rt.qs) > 0 {
if reply != nil {
mh = append(mh, "+ "...) // Signal that there is a reply.
mh = append(mh, reply...)
mh = append(mh, ' ')
} else {
mh = append(mh, "| "...) // Only queues
}
mh = append(mh, rt.qs...)
} else if reply != nil {
mh = append(mh, reply...)
mh = append(mh, ' ')
}
mh = append(mh, c.pa.szb...)
mh = append(mh, _CRLF_...)
c.deliverMsg(rt.sub, mh, msg)
}
}
func (c *client) pubPermissionViolation(subject []byte) {
c.sendErr(fmt.Sprintf("Permissions Violation for Publish to %q", subject))
c.Errorf("Publish Violation - User %q, Subject %q", c.opts.Username, subject)
}
func (c *client) replySubjectViolation(reply []byte) {
c.sendErr(fmt.Sprintf("Permissions Violation for Publish with Reply of %q", reply))
c.Errorf("Publish Violation - User %q, Reply %q", c.opts.Username, reply)
}
func (c *client) processPingTimer() {
c.mu.Lock()
defer c.mu.Unlock()
c.ping.tmr = nil
// Check if connection is still opened
if c.nc == nil {
return
}
c.Debugf("%s Ping Timer", c.typeString())
// If we have had activity within the PingInterval no
// need to send a ping.
if delta := time.Since(c.last); delta < c.srv.getOpts().PingInterval {
c.Debugf("Delaying PING due to activity %v ago", delta.Round(time.Second))
} else {
// Check for violation
if c.ping.out+1 > c.srv.getOpts().MaxPingsOut {
c.Debugf("Stale Client Connection - Closing")
c.sendProto([]byte(fmt.Sprintf("-ERR '%s'\r\n", "Stale Connection")), true)
c.clearConnection(StaleConnection)
return
}
// Send PING
c.sendPing()
}
// Reset to fire again.
c.setPingTimer()
}
// Lock should be held
func (c *client) setPingTimer() {
if c.srv == nil {
return
}
d := c.srv.getOpts().PingInterval
c.ping.tmr = time.AfterFunc(d, c.processPingTimer)
}
// Lock should be held
func (c *client) clearPingTimer() {
if c.ping.tmr == nil {
return
}
c.ping.tmr.Stop()
c.ping.tmr = nil
}
// Lock should be held
func (c *client) setAuthTimer(d time.Duration) {
c.atmr = time.AfterFunc(d, c.authTimeout)
}
// Lock should be held
func (c *client) clearAuthTimer() bool {
if c.atmr == nil {
return true
}
stopped := c.atmr.Stop()
c.atmr = nil
return stopped
}
// We may reuse atmr for expiring user jwts,
// so check connectReceived.
func (c *client) awaitingAuth() bool {
c.mu.Lock()
authSet := !c.flags.isSet(connectReceived) && c.atmr != nil
c.mu.Unlock()
return authSet
}
// This will set the atmr for the JWT expiration time.
// We will lock on entry.
func (c *client) setExpirationTimer(d time.Duration) {
c.mu.Lock()
c.atmr = time.AfterFunc(d, c.authExpired)
c.mu.Unlock()
}
// Lock should be held
func (c *client) clearConnection(reason ClosedState) {
if c.flags.isSet(clearConnection) {
return
}
c.flags.set(clearConnection)
nc := c.nc
if nc == nil || c.srv == nil {
return
}
// Flush any pending.
c.flushOutbound()
// Clear outbound here.
if c.out.sg != nil {
c.out.sg.Broadcast()
}
// With TLS, Close() is sending an alert (that is doing a write).
// Need to set a deadline otherwise the server could block there
// if the peer is not reading from socket.
if c.flags.isSet(handshakeComplete) {
nc.SetWriteDeadline(time.Now().Add(c.out.wdl))
}
nc.Close()
// Do this always to also kick out any IO writes.
nc.SetWriteDeadline(time.Time{})
// Save off the connection if its a client.
if c.kind == CLIENT && c.srv != nil {
go c.srv.saveClosedClient(c, nc, reason)
}
}
func (c *client) typeString() string {
switch c.kind {
case CLIENT:
return "Client"
case ROUTER:
return "Router"
case GATEWAY:
return "Gateway"
}
return "Unknown Type"
}
// processSubsOnConfigReload removes any subscriptions the client has that are no
// longer authorized, and check for imports (accounts) due to a config reload.
func (c *client) processSubsOnConfigReload(awcsti map[string]struct{}) {
c.mu.Lock()
var (
checkPerms = c.perms != nil
checkAcc = c.acc != nil
acc = c.acc
)
if !checkPerms && !checkAcc {
c.mu.Unlock()
return
}
var (
_subs [32]*subscription
subs = _subs[:0]
_removed [32]*subscription
removed = _removed[:0]
srv = c.srv
userInfo = c.opts.Nkey
)
if userInfo == "" {
userInfo = c.opts.Username
if userInfo == "" {
userInfo = fmt.Sprintf("%v", c.cid)
}
}
if checkAcc {
// We actually only want to check if stream imports have changed.
if _, ok := awcsti[acc.Name]; !ok {
checkAcc = false
}
}
// We will clear any mperms we have here. It will rebuild on the fly with canSubscribe,
// so we do that here as we collect them. We will check result down below.
c.mperms = nil
// Collect client's subs under the lock
for _, sub := range c.subs {
// Just checking to rebuild mperms under the lock, will collect removed though here.
// Only collect under subs array of canSubscribe and checkAcc true.
if !c.canSubscribe(string(sub.subject)) {
removed = append(removed, sub)
} else if checkAcc {
subs = append(subs, sub)
}
}
c.mu.Unlock()
// This list is all subs who are allowed and we need to check accounts.
for _, sub := range subs {
c.mu.Lock()
oldShadows := sub.shadow
sub.shadow = nil
c.mu.Unlock()
c.addShadowSubscriptions(acc, sub)
for _, nsub := range oldShadows {
nsub.im.acc.sl.Remove(nsub)
}
}
// Unsubscribe all that need to be removed and report back to client and logs.
for _, sub := range removed {
c.unsubscribe(acc, sub, true)
c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q (sid %q)",
sub.subject, sub.sid))
srv.Noticef("Removed sub %q (sid %q) for user %q - not authorized",
sub.subject, sub.sid, userInfo)
}
}
// Allows us to count up all the queue subscribers during close.
type qsub struct {
sub *subscription
n int32
}
func (c *client) closeConnection(reason ClosedState) {
c.mu.Lock()
if c.nc == nil {
c.mu.Unlock()
return
}
// Be consistent with the creation: for routes and gateways,
// we use Noticef on create, so use that too for delete.
if c.kind == ROUTER || c.kind == GATEWAY {
c.Noticef("%s connection closed", c.typeString())
} else {
c.Debugf("%s connection closed", c.typeString())
}
c.clearAuthTimer()
c.clearPingTimer()
c.clearConnection(reason)
c.nc = nil
var (
retryImplicit bool
connectURLs []string
gwName string
gwIsOutbound bool
gwCfg *gatewayCfg
kind = c.kind
srv = c.srv
noReconnect = c.flags.isSet(noReconnect)
acc = c.acc
)
// Snapshot for use if we are a client connection.
// FIXME(dlc) - we can just stub in a new one for client
// and reference existing one.
var subs []*subscription
if kind == CLIENT {
subs = make([]*subscription, 0, len(c.subs))
for _, sub := range c.subs {
// Auto-unsubscribe subscriptions must be unsubscribed forcibly.
sub.max = 0
subs = append(subs, sub)
}
}
if c.route != nil {
if !noReconnect {
retryImplicit = c.route.retry
}
connectURLs = c.route.connectURLs
}
if kind == GATEWAY {
gwName = c.gw.name
gwIsOutbound = c.gw.outbound
gwCfg = c.gw.cfg
}
c.mu.Unlock()
// Remove clients subscriptions.
if kind == CLIENT {
acc.sl.RemoveBatch(subs)
} else if kind == ROUTER {
go c.removeRemoteSubs()
}
if srv != nil {
// This is a route that disconnected, but we are not in lame duck mode...
if len(connectURLs) > 0 && !srv.isLameDuckMode() {
// Unless disabled, possibly update the server's INFO protocol
// and send to clients that know how to handle async INFOs.
if !srv.getOpts().Cluster.NoAdvertise {
srv.removeClientConnectURLsAndSendINFOToClients(connectURLs)
}
}
// Unregister
srv.removeClient(c)
// Update remote subscriptions.
if acc != nil && kind == CLIENT {
qsubs := map[string]*qsub{}
for _, sub := range subs {
if sub.queue == nil {
srv.updateRouteSubscriptionMap(acc, sub, -1)
} else {
// We handle queue subscribers special in case we
// have a bunch we can just send one update to the
// connected routes.
key := string(sub.subject) + " " + string(sub.queue)
if esub, ok := qsubs[key]; ok {
esub.n++
} else {
qsubs[key] = &qsub{sub, 1}
}
}
if srv.gateway.enabled {
srv.gatewayUpdateSubInterest(acc.Name, sub, -1)
}
}
// Process any qsubs here.
for _, esub := range qsubs {
srv.updateRouteSubscriptionMap(acc, esub.sub, -(esub.n))
}
if prev := c.acc.removeClient(c); prev == 1 && c.srv != nil {
c.srv.mu.Lock()
c.srv.activeAccounts--
c.srv.mu.Unlock()
}
}
}
// Don't reconnect connections that have been marked with
// the no reconnect flag.
if noReconnect {
return
}
// Check for a solicited route. If it was, start up a reconnect unless
// we are already connected to the other end.
if c.isSolicitedRoute() || retryImplicit {
// Capture these under lock
c.mu.Lock()
rid := c.route.remoteID
rtype := c.route.routeType
rurl := c.route.url
c.mu.Unlock()
srv.mu.Lock()
defer srv.mu.Unlock()
// It is possible that the server is being shutdown.
// If so, don't try to reconnect
if !srv.running {
return
}
if rid != "" && srv.remotes[rid] != nil {
c.srv.Debugf("Not attempting reconnect for solicited route, already connected to \"%s\"", rid)
return
} else if rid == srv.info.ID {
c.srv.Debugf("Detected route to self, ignoring \"%s\"", rurl)
return
} else if rtype != Implicit || retryImplicit {
c.srv.Debugf("Attempting reconnect for solicited route \"%s\"", rurl)
// Keep track of this go-routine so we can wait for it on
// server shutdown.
srv.startGoRoutine(func() { srv.reConnectToRoute(rurl, rtype) })
}
} else if srv != nil && kind == GATEWAY && gwIsOutbound {
if gwCfg != nil {
srv.Debugf("Attempting reconnect for gateway %q", gwName)
// Run this as a go routine since we may be called within
// the solicitGateway itself if there was an error during
// the creation of the gateway connection.
srv.startGoRoutine(func() { srv.reconnectGateway(gwCfg) })
} else {
srv.Debugf("Gateway %q not in configuration, not attempting reconnect", gwName)
}
}
}
// Set the noReconnect flag. This is used before a call to closeConnection()
// to prevent the connection to reconnect (routes, gateways).
func (c *client) setNoReconnect() {
c.mu.Lock()
c.flags.set(noReconnect)
c.mu.Unlock()
}
// Returns the client's RTT value with the protection of the client's lock.
func (c *client) getRTTValue() time.Duration {
c.mu.Lock()
rtt := c.rtt
c.mu.Unlock()
return rtt
}
// This function is used by ROUTER and GATEWAY connections to
// look for a subject on a given account (since these type of
// connections are not bound to a specific account).
// If the c.pa.subject is found in the cache, the cached result
// is returned, otherwse, we match the account's sublist and update
// the cache. The cache is pruned if reaching a certain size.
func (c *client) getAccAndResultFromCache() (*Account, *SublistResult) {
var (
acc *Account
pac *perAccountCache
r *SublistResult
ok bool
)
// Check our cache.
if pac, ok = c.in.pacache[string(c.pa.pacache)]; ok {
// Check the genid to see if it's still valid.
if genid := atomic.LoadUint64(&pac.acc.sl.genid); genid != pac.genid {
ok = false
delete(c.in.pacache, string(c.pa.pacache))
} else {
acc = pac.acc
r = pac.results
}
}
if !ok {
// Match correct account and sublist.
if acc, _ = c.srv.LookupAccount(string(c.pa.account)); acc == nil {
return nil, nil
}
// Match against the account sublist.
r = acc.sl.Match(string(c.pa.subject))
// Store in our cache
c.in.pacache[string(c.pa.pacache)] = &perAccountCache{acc, r, atomic.LoadUint64(&acc.sl.genid)}
// Check if we need to prune.
if len(c.in.pacache) > maxPerAccountCacheSize {
c.prunePerAccountCache()
}
}
return acc, r
}
// prunePerAccountCache will prune off a random number of cache entries.
func (c *client) prunePerAccountCache() {
n := 0
for cacheKey := range c.in.pacache {
delete(c.in.pacache, cacheKey)
if n++; n > prunePerAccountCacheSize {
break
}
}
}
// Logging functionality scoped to a client or route.
func (c *client) Errorf(format string, v ...interface{}) {
format = fmt.Sprintf("%s - %s", c, format)
c.srv.Errorf(format, v...)
}
func (c *client) Debugf(format string, v ...interface{}) {
format = fmt.Sprintf("%s - %s", c, format)
c.srv.Debugf(format, v...)
}
func (c *client) Noticef(format string, v ...interface{}) {
format = fmt.Sprintf("%s - %s", c, format)
c.srv.Noticef(format, v...)
}
func (c *client) Tracef(format string, v ...interface{}) {
format = fmt.Sprintf("%s - %s", c, format)
c.srv.Tracef(format, v...)
}
| 1 | 8,493 | For a client, we store host, as string c.host. That is what we use for monitoring and statsz. Not sure if its useful here or not. Looks like probably not. | nats-io-nats-server | go |
@@ -196,6 +196,6 @@ public class TestDataSourceOptions {
.option("split-size", String.valueOf(562L)) // 562 bytes is the size of SimpleRecord(1,"a")
.load(tableLocation);
- Assert.assertEquals("Spark partitions should match", 2, resultDf.javaRDD().getNumPartitions());
+ Assert.assertEquals("Spark partitions should match", 4, resultDf.javaRDD().getNumPartitions());
}
} | 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.spark.source;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.FileScanTask;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Table;
import org.apache.iceberg.TableProperties;
import org.apache.iceberg.hadoop.HadoopTables;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.types.Types;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.apache.iceberg.types.Types.NestedField.optional;
public class TestDataSourceOptions {
private static final Configuration CONF = new Configuration();
private static final Schema SCHEMA = new Schema(
optional(1, "id", Types.IntegerType.get()),
optional(2, "data", Types.StringType.get())
);
private static SparkSession spark = null;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@BeforeClass
public static void startSpark() {
TestDataSourceOptions.spark = SparkSession.builder().master("local[2]").getOrCreate();
}
@AfterClass
public static void stopSpark() {
SparkSession currentSpark = TestDataSourceOptions.spark;
TestDataSourceOptions.spark = null;
currentSpark.stop();
}
@Test
public void testWriteFormatOptionOverridesTableProperties() throws IOException {
String tableLocation = temp.newFolder("iceberg-table").toString();
HadoopTables tables = new HadoopTables(CONF);
PartitionSpec spec = PartitionSpec.unpartitioned();
Map<String, String> options = Maps.newHashMap();
options.put(TableProperties.DEFAULT_FILE_FORMAT, "avro");
Table table = tables.create(SCHEMA, spec, options, tableLocation);
List<SimpleRecord> expectedRecords = Lists.newArrayList(
new SimpleRecord(1, "a"),
new SimpleRecord(2, "b"),
new SimpleRecord(3, "c")
);
Dataset<Row> df = spark.createDataFrame(expectedRecords, SimpleRecord.class);
df.select("id", "data").write()
.format("iceberg")
.option("write-format", "parquet")
.mode("append")
.save(tableLocation);
try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
tasks.forEach(task -> {
FileFormat fileFormat = FileFormat.fromFileName(task.file().path());
Assert.assertEquals(FileFormat.PARQUET, fileFormat);
});
}
}
@Test
public void testNoWriteFormatOption() throws IOException {
String tableLocation = temp.newFolder("iceberg-table").toString();
HadoopTables tables = new HadoopTables(CONF);
PartitionSpec spec = PartitionSpec.unpartitioned();
Map<String, String> options = Maps.newHashMap();
options.put(TableProperties.DEFAULT_FILE_FORMAT, "avro");
Table table = tables.create(SCHEMA, spec, options, tableLocation);
List<SimpleRecord> expectedRecords = Lists.newArrayList(
new SimpleRecord(1, "a"),
new SimpleRecord(2, "b"),
new SimpleRecord(3, "c")
);
Dataset<Row> df = spark.createDataFrame(expectedRecords, SimpleRecord.class);
df.select("id", "data").write()
.format("iceberg")
.mode("append")
.save(tableLocation);
try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
tasks.forEach(task -> {
FileFormat fileFormat = FileFormat.fromFileName(task.file().path());
Assert.assertEquals(FileFormat.AVRO, fileFormat);
});
}
}
@Test
public void testHadoopOptions() throws IOException {
String tableLocation = temp.newFolder("iceberg-table").toString();
Configuration sparkHadoopConf = spark.sessionState().newHadoopConf();
String originalDefaultFS = sparkHadoopConf.get("fs.default.name");
try {
HadoopTables tables = new HadoopTables(CONF);
PartitionSpec spec = PartitionSpec.unpartitioned();
Map<String, String> options = Maps.newHashMap();
tables.create(SCHEMA, spec, options, tableLocation);
// set an invalid value for 'fs.default.name' in Spark Hadoop config
// to verify that 'hadoop.' data source options are propagated correctly
sparkHadoopConf.set("fs.default.name", "hdfs://localhost:9000");
List<SimpleRecord> expectedRecords = Lists.newArrayList(
new SimpleRecord(1, "a"),
new SimpleRecord(2, "b")
);
Dataset<Row> originalDf = spark.createDataFrame(expectedRecords, SimpleRecord.class);
originalDf.select("id", "data").write()
.format("iceberg")
.mode("append")
.option("hadoop.fs.default.name", "file:///")
.save(tableLocation);
Dataset<Row> resultDf = spark.read()
.format("iceberg")
.option("hadoop.fs.default.name", "file:///")
.load(tableLocation);
List<SimpleRecord> resultRecords = resultDf.orderBy("id")
.as(Encoders.bean(SimpleRecord.class))
.collectAsList();
Assert.assertEquals("Records should match", expectedRecords, resultRecords);
} finally {
sparkHadoopConf.set("fs.default.name", originalDefaultFS);
}
}
@Test
public void testSplitOptionsOverridesTableProperties() throws IOException {
String tableLocation = temp.newFolder("iceberg-table").toString();
HadoopTables tables = new HadoopTables(CONF);
PartitionSpec spec = PartitionSpec.unpartitioned();
Map<String, String> options = Maps.newHashMap();
options.put(TableProperties.SPLIT_SIZE, String.valueOf(128L * 1024 * 1024)); // 128Mb
tables.create(SCHEMA, spec, options, tableLocation);
List<SimpleRecord> expectedRecords = Lists.newArrayList(
new SimpleRecord(1, "a"),
new SimpleRecord(2, "b")
);
Dataset<Row> originalDf = spark.createDataFrame(expectedRecords, SimpleRecord.class);
originalDf.select("id", "data").write()
.format("iceberg")
.mode("append")
.save(tableLocation);
Dataset<Row> resultDf = spark.read()
.format("iceberg")
.option("split-size", String.valueOf(562L)) // 562 bytes is the size of SimpleRecord(1,"a")
.load(tableLocation);
Assert.assertEquals("Spark partitions should match", 2, resultDf.javaRDD().getNumPartitions());
}
}
| 1 | 14,498 | This change is suspicious. Why did the number of partitions increase? | apache-iceberg | java |
@@ -20,8 +20,7 @@ class ProposalPolicy
end
def can_create!
- # TODO restrict by client_slug
- true
+ slug_matches? || @user.admin?
end
alias_method :can_new!, :can_create!
| 1 | class ProposalPolicy
include ExceptionPolicy
def initialize(user, record)
super(user, record)
@proposal = record
end
def can_approve!
approver! && pending_approval! && not_cancelled!
end
def can_edit!
requester! && not_approved! && not_cancelled!
end
alias_method :can_update!, :can_edit!
def can_show!
check(self.visible_proposals.exists?(@proposal.id), "You are not allowed to see this proposal")
end
def can_create!
# TODO restrict by client_slug
true
end
alias_method :can_new!, :can_create!
def can_cancel!
requester! && not_cancelled!
end
alias_method :can_cancel_form!, :can_cancel!
protected
def restricted?
ENV['RESTRICT_ACCESS'] == 'true'
end
def requester?
@proposal.requester_id == @user.id
end
def requester!
check(self.requester?, "You are not the requester")
end
def not_approved!
check([email protected]?,
"That proposal's already approved. New proposal?")
end
def not_cancelled!
check([email protected]?, "Sorry, this proposal has been cancelled.")
end
def approver?
@proposal.approvers.exists?(@user.id)
end
def delegate?
@proposal.delegate?(@user)
end
def approver!
check(self.approver? || self.delegate?,
"Sorry, you're not an approver on this proposal")
end
def observer!
check(@proposal.observers.include?(@user),
"Sorry, you're not an observer on this proposal")
end
def pending_approver?
@proposal.currently_awaiting_approvers.include?(@user)
end
def pending_delegate?
ApprovalDelegate.where(assigner_id: @proposal.currently_awaiting_approvers, assignee: @user).exists?
end
def pending_approval!
check(self.pending_approver? || self.pending_delegate?,
"A response has already been logged a response for this proposal")
end
def visible_proposals
ProposalPolicy::Scope.new(@user, Proposal).resolve
end
end
| 1 | 14,090 | I'm still new to this area, so please forgive what may be a stupid question: When would this be false? And do we have a test for that situation? | 18F-C2 | rb |
@@ -1710,10 +1710,11 @@ namespace pwiz.Skyline.EditUI
private void UpdateMoleculeType()
{
bool isPeptide = radioPeptide.Checked;
- btnCustomMoleculeColumns.Enabled = radioMolecule.Checked;
+ btnCustomMoleculeColumns.Enabled = true;
Settings.Default.TransitionListInsertPeptides = isPeptide; // Remember for next time
- //Skip updating if nothing needs to be changed
+ // Skip updating if nothing needs to be changed
+ // This should probably be taken out when we add smarter column selection as its currently hard coded for the number of columns
if ((isPeptide && gridViewTransitionList.ColumnCount == 5) || (!isPeptide && gridViewTransitionList.ColumnCount == 6))
return;
| 1 | /*
* Original author: Nick Shulman <nicksh .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2009 University of Washington - Seattle, WA
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pwiz.Common.Chemistry;
using pwiz.Common.Controls;
using pwiz.Common.SystemUtil;
using pwiz.ProteomeDatabase.API;
using pwiz.Skyline.Alerts;
using pwiz.Skyline.Controls;
using pwiz.Skyline.Model;
using pwiz.Skyline.Model.AuditLog;
using pwiz.Skyline.Model.Crosslinking;
using pwiz.Skyline.Model.DocSettings;
using pwiz.Skyline.Model.DocSettings.Extensions;
using pwiz.Skyline.Model.Lib;
using pwiz.Skyline.Model.Proteome;
using pwiz.Skyline.Properties;
using pwiz.Skyline.Util;
using pwiz.Skyline.Util.Extensions;
namespace pwiz.Skyline.EditUI
{
// CONSIDER bspratt: Checkbox for hiding and showing new protein columns
public partial class PasteDlg : FormEx, IMultipleViewProvider
{
private readonly StatementCompletionTextBox _statementCompletionEditBox;
private bool _noErrors;
private readonly AuditLogEntryCreatorList _entryCreators;
public PasteDlg(IDocumentUIContainer documentUiContainer)
{
InitializeComponent();
Icon = Resources.Skyline;
DocumentUiContainer = documentUiContainer;
_entryCreators = new AuditLogEntryCreatorList();
_statementCompletionEditBox = new StatementCompletionTextBox(DocumentUiContainer)
{
MatchTypes = ProteinMatchTypes.OfValues(ProteinMatchType.name, ProteinMatchType.description)
};
_statementCompletionEditBox.SelectionMade += statementCompletionEditBox_SelectionMade;
gridViewProteins.DataGridViewKey += OnDataGridViewKey;
gridViewPeptides.DataGridViewKey += OnDataGridViewKey;
gridViewTransitionList.DataGridViewKey += OnDataGridViewKey;
}
void OnDataGridViewKey(object sender, KeyEventArgs e)
{
_statementCompletionEditBox.OnKeyPreview(sender, e);
}
void statementCompletionEditBox_SelectionMade(StatementCompletionItem statementCompletionItem)
{
if (tabControl1.SelectedTab == tabPageProteinList)
{
_statementCompletionEditBox.TextBox.Text = statementCompletionItem.ProteinInfo.Name;
gridViewProteins.EndEdit();
}
else if (tabControl1.SelectedTab == tabPagePeptideList)
{
_statementCompletionEditBox.TextBox.Text = statementCompletionItem.Peptide;
if (gridViewPeptides.CurrentRow != null)
{
gridViewPeptides.CurrentRow.Cells[colPeptideProtein.Index].Value
= statementCompletionItem.ProteinInfo.Name;
}
gridViewPeptides.EndEdit();
}
else if (tabControl1.SelectedTab == tabPageTransitionList)
{
_statementCompletionEditBox.TextBox.Text = statementCompletionItem.Peptide;
if (gridViewTransitionList.CurrentRow != null)
{
gridViewTransitionList.CurrentRow.Cells[colTransitionProteinName.Index].Value =
statementCompletionItem.ProteinInfo.Name;
}
gridViewTransitionList.EndEdit();
}
}
public IDocumentUIContainer DocumentUiContainer { get; private set; }
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
DocumentUiContainer.ListenUI(OnDocumentUIChanged);
}
protected override void OnHandleDestroyed(EventArgs e)
{
base.OnHandleDestroyed(e);
DocumentUiContainer.UnlistenUI(OnDocumentUIChanged);
}
private IdentityPath _selectedPath;
public IdentityPath SelectedPath
{
get { return _selectedPath; }
set
{
_selectedPath = value;
// Handle insert node path
if (_selectedPath != null &&
_selectedPath.Depth == (int)SrmDocument.Level.MoleculeGroups &&
ReferenceEquals(_selectedPath.GetIdentity((int)SrmDocument.Level.MoleculeGroups), SequenceTree.NODE_INSERT_ID))
{
_selectedPath = null;
}
}
}
public string ErrorText
{
get { return panelError.Visible ? tbxError.Text : null; }
}
public int SelectedGridRow
{
get
{
var cell = ActiveGridView.CurrentCell;
return cell != null ? cell.RowIndex : -1;
}
}
public int SelectedGridColumn
{
get
{
var cell = ActiveGridView.CurrentCell;
return cell != null ? cell.ColumnIndex : -1;
}
}
private DataGridView ActiveGridView
{
get
{
return gridViewProteins.Visible
? gridViewProteins
: (gridViewPeptides.Visible
? gridViewPeptides
: gridViewTransitionList);
}
}
public void ShowError(PasteError pasteError)
{
_noErrors = false;
panelError.Visible = true;
if (pasteError == null)
{
tbxError.Text = string.Empty;
tbxError.Visible = false;
Text = Description;
return;
}
tbxError.BackColor = Color.Red;
tbxError.ForeColor = Color.White;
tbxError.Text = pasteError.Message;
// Useful for debugging if this hangs in a test - it appears in the timeout report
// ReSharper disable LocalizableElement
Text = Description + " (" + pasteError.Message + ")";
// ReSharper restore LocalizableElement
}
public void ShowNoErrors()
{
_noErrors = true;
panelError.Visible = true;
tbxError.Text = Resources.PasteDlg_ShowNoErrors_No_errors;
tbxError.BackColor = Color.LightGreen;
tbxError.ForeColor = Color.Black;
Text = Description; // Clear any error info
}
public void HideNoErrors()
{
if (!_noErrors)
{
return;
}
panelError.Visible = false;
Text = Description; // Clear any error info
}
private void btnValidate_Click(object sender, EventArgs e)
{
ValidateCells();
}
public void ValidateCells()
{
IdentityPath selectedPath = null;
var document = GetNewDocument(DocumentUiContainer.Document, true, ref selectedPath);
if (document != null)
ShowNoErrors();
}
private SrmDocument GetNewDocument(SrmDocument document, bool validating, ref IdentityPath selectedPath)
{
List<PeptideGroupDocNode> newPeptideGroups;
return GetNewDocument(document, validating, ref selectedPath, out newPeptideGroups);
}
private SrmDocument GetNewDocument(SrmDocument document, bool validating, ref IdentityPath selectedPath, out List<PeptideGroupDocNode> newPeptideGroups)
{
var fastaHelper = new ImportFastaHelper(tbxFasta, tbxError, panelError, toolTip1);
if ((document = fastaHelper.AddFasta(document, null, ref selectedPath, out newPeptideGroups, out var error)) == null)
{
fastaHelper.ShowFastaError(error);
tabControl1.SelectedTab = tabPageFasta; // To show fasta errors
return null;
}
if ((document = AddProteins(document, ref selectedPath)) == null)
{
return null;
}
if ((document = AddPeptides(document, validating, ref selectedPath)) == null)
{
return null;
}
if ((document = AddTransitionList(document, ref selectedPath)) == null)
{
return null;
}
return document;
}
private void SetCurrentCellForPasteError(DataGridView gridView, PasteError pasteError, int? columnIndex = null)
{
ShowError(pasteError);
var errColumn = columnIndex ?? pasteError.Column;
if (errColumn >= 0 && gridView.Rows[pasteError.Line].Cells[errColumn].Visible)
{
gridView.CurrentCell = gridView.Rows[pasteError.Line].Cells[errColumn];
}
else
{
// Set the row even if desired column isn't visible - just pick the first available column
for (var firstVisibleColumn = 0; firstVisibleColumn < gridView.Rows[pasteError.Line].Cells.Count; firstVisibleColumn++)
{
if (gridView.Rows[pasteError.Line].Cells[firstVisibleColumn].Visible)
{
gridView.CurrentCell = gridView.Rows[pasteError.Line].Cells[firstVisibleColumn];
break;
}
}
}
}
private void ShowProteinError(PasteError pasteError)
{
tabControl1.SelectedTab = tabPageProteinList;
SetCurrentCellForPasteError(gridViewProteins, pasteError, colProteinName.Index);
}
private void ShowPeptideError(PasteError pasteError)
{
tabControl1.SelectedTab = tabPagePeptideList;
SetCurrentCellForPasteError(gridViewPeptides, pasteError);
}
private void ShowTransitionError(PasteError pasteError)
{
tabControl1.SelectedTab = tabPageTransitionList;
SetCurrentCellForPasteError(gridViewTransitionList, pasteError);
}
private SrmDocument AddPeptides(SrmDocument document, bool validating, ref IdentityPath selectedPath)
{
if (tabControl1.SelectedTab != tabPagePeptideList)
return document;
var matcher = new ModificationMatcher();
var listPeptideSequences = ListPeptideSequences();
if (listPeptideSequences == null)
return null;
try
{
matcher.CreateMatches(document.Settings, listPeptideSequences, Settings.Default.StaticModList,
Settings.Default.HeavyModList);
}
catch (FormatException e)
{
MessageDlg.ShowException(this, e);
ShowPeptideError(new PasteError
{
Column = colPeptideSequence.Index,
Message = Resources.PasteDlg_AddPeptides_Unable_to_interpret_peptide_modifications
});
return null;
}
var strNameMatches = matcher.FoundMatches;
if (!validating && !string.IsNullOrEmpty(strNameMatches))
{
string message = TextUtil.LineSeparate(Resources.PasteDlg_AddPeptides_Would_you_like_to_use_the_Unimod_definitions_for_the_following_modifications,
string.Empty, strNameMatches);
if (MultiButtonMsgDlg.Show(this, message, Resources.PasteDlg_AddPeptides_OK) == DialogResult.Cancel)
return null;
}
var backgroundProteome = GetBackgroundProteome(document);
// Insert last to first so that proteins get inserted on top of each other
// in the order they are added. Peptide insertion into peptide lists needs
// to be carefully tracked to insert them in the order they are listed in
// the grid.
int lastGroupGlobalIndex = 0, lastPeptideIndex = -1;
for (int i = gridViewPeptides.Rows.Count - 1; i >= 0; i--)
{
PeptideGroupDocNode peptideGroupDocNode;
var row = gridViewPeptides.Rows[i];
var pepModSequence = Convert.ToString(row.Cells[colPeptideSequence.Index].Value);
pepModSequence = FastaSequence.NormalizeNTerminalMod(pepModSequence);
var proteinName = Convert.ToString(row.Cells[colPeptideProtein.Index].Value);
if (string.IsNullOrEmpty(pepModSequence) && string.IsNullOrEmpty(proteinName))
continue;
if (string.IsNullOrEmpty(proteinName))
{
peptideGroupDocNode = GetSelectedPeptideGroupDocNode(document, selectedPath);
if (!IsPeptideListDocNode(peptideGroupDocNode))
{
peptideGroupDocNode = null;
}
}
else
{
peptideGroupDocNode = FindPeptideGroupDocNode(document, proteinName);
}
if (peptideGroupDocNode == null)
{
if (string.IsNullOrEmpty(proteinName))
{
peptideGroupDocNode = new PeptideGroupDocNode(new PeptideGroup(),
document.GetPeptideGroupId(true), null,
new PeptideDocNode[0]);
}
else
{
ProteinMetadata metadata = null;
PeptideGroup peptideGroup = backgroundProteome.IsNone ? new PeptideGroup()
: (backgroundProteome.GetFastaSequence(proteinName, out metadata) ??
new PeptideGroup());
if (metadata != null)
peptideGroupDocNode = new PeptideGroupDocNode(peptideGroup, metadata, new PeptideDocNode[0]);
else
peptideGroupDocNode = new PeptideGroupDocNode(peptideGroup, proteinName,
peptideGroup.Description, new PeptideDocNode[0]);
}
// Add to the end, if no insert node
var to = selectedPath;
if (to == null || to.Depth < (int)SrmDocument.Level.MoleculeGroups)
document = (SrmDocument)document.Add(peptideGroupDocNode);
else
{
Identity toId = selectedPath.GetIdentity((int) SrmDocument.Level.MoleculeGroups);
document = (SrmDocument) document.Insert(toId, peptideGroupDocNode);
}
selectedPath = new IdentityPath(peptideGroupDocNode.Id);
}
var peptides = new List<PeptideDocNode>();
foreach (PeptideDocNode peptideDocNode in peptideGroupDocNode.Children)
{
peptides.Add(peptideDocNode);
}
var fastaSequence = peptideGroupDocNode.PeptideGroup as FastaSequence;
PeptideDocNode nodePepNew;
if (fastaSequence != null)
{
// Attempt to create node for error checking.
nodePepNew = fastaSequence.CreateFullPeptideDocNode(document.Settings,
new Target(FastaSequence.StripModifications(pepModSequence)));
if (nodePepNew == null)
{
ShowPeptideError(new PasteError
{
Column = colPeptideSequence.Index,
Line = i,
Message = Resources.PasteDlg_AddPeptides_This_peptide_sequence_was_not_found_in_the_protein_sequence
});
return null;
}
}
// Create node using ModificationMatcher.
nodePepNew = matcher.GetModifiedNode(pepModSequence, fastaSequence).ChangeSettings(document.Settings,
SrmSettingsDiff.ALL);
// Avoid adding an existing peptide a second time.
if (!peptides.Contains(nodePep => Equals(nodePep.Key, nodePepNew.Key)))
{
if (nodePepNew.Peptide.FastaSequence != null)
{
peptides.Add(nodePepNew);
peptides.Sort(FastaSequence.ComparePeptides);
}
else
{
int groupGlobalIndex = peptideGroupDocNode.PeptideGroup.GlobalIndex;
if (groupGlobalIndex == lastGroupGlobalIndex && lastPeptideIndex != -1)
{
peptides.Insert(lastPeptideIndex, nodePepNew);
}
else
{
lastPeptideIndex = peptides.Count;
peptides.Add(nodePepNew);
}
lastGroupGlobalIndex = groupGlobalIndex;
}
var newPeptideGroupDocNode = new PeptideGroupDocNode(peptideGroupDocNode.PeptideGroup, peptideGroupDocNode.Annotations, peptideGroupDocNode.Name, peptideGroupDocNode.Description, peptides.ToArray(), false);
document = (SrmDocument)document.ReplaceChild(newPeptideGroupDocNode);
}
}
if (!validating && listPeptideSequences.Count > 0)
{
var pepModsNew = matcher.GetDocModifications(document);
document = document.ChangeSettings(document.Settings.ChangePeptideModifications(mods => pepModsNew));
document.Settings.UpdateDefaultModifications(false);
}
return document;
}
private List<string> ListPeptideSequences()
{
List<string> listSequences = new List<string>();
for (int i = gridViewPeptides.Rows.Count - 1; i >= 0; i--)
{
var row = gridViewPeptides.Rows[i];
var peptideSequence = Convert.ToString(row.Cells[colPeptideSequence.Index].Value);
var proteinName = Convert.ToString(row.Cells[colPeptideProtein.Index].Value);
if (string.IsNullOrEmpty(peptideSequence) && string.IsNullOrEmpty(proteinName))
{
continue;
}
if (string.IsNullOrEmpty(peptideSequence))
{
ShowPeptideError(new PasteError
{
Column = colPeptideSequence.Index,
Line = i,
Message = Resources.PasteDlg_ListPeptideSequences_The_peptide_sequence_cannot_be_blank
});
return null;
}
CrosslinkLibraryKey crosslinkLibraryKey =
CrosslinkSequenceParser.TryParseCrosslinkLibraryKey(peptideSequence, 0);
if (crosslinkLibraryKey == null)
{
if (!FastaSequence.IsExSequence(peptideSequence))
{
ShowPeptideError(new PasteError
{
Column = colPeptideSequence.Index,
Line = i,
Message = Resources.PasteDlg_ListPeptideSequences_This_peptide_sequence_contains_invalid_characters
});
return null;
}
peptideSequence = FastaSequence.NormalizeNTerminalMod(peptideSequence);
}
else if (!crosslinkLibraryKey.IsSupportedBySkyline())
{
ShowPeptideError(new PasteError
{
Column = colPeptideSequence.Index,
Line = i,
Message = Resources.PasteDlg_ListPeptideSequences_The_structure_of_this_crosslinked_peptide_is_not_supported_by_Skyline
});
return null;
}
listSequences.Add(peptideSequence);
}
return listSequences;
}
private static bool IsPeptideListDocNode(PeptideGroupDocNode peptideGroupDocNode)
{
return peptideGroupDocNode != null && peptideGroupDocNode.IsPeptideList;
}
private SrmDocument AddProteins(SrmDocument document, ref IdentityPath selectedPath)
{
if (tabControl1.SelectedTab != tabPageProteinList)
return document;
var backgroundProteome = GetBackgroundProteome(document);
for (int i = gridViewProteins.Rows.Count - 1; i >= 0; i--)
{
var row = gridViewProteins.Rows[i];
var proteinName = Convert.ToString(row.Cells[colProteinName.Index].Value);
if (String.IsNullOrEmpty(proteinName))
{
continue;
}
var pastedMetadata = new ProteinMetadata(proteinName,
Convert.ToString(row.Cells[colProteinDescription.Index].Value),
SmallMoleculeTransitionListReader.NullForEmpty(Convert.ToString(row.Cells[colProteinPreferredName.Index].Value)),
SmallMoleculeTransitionListReader.NullForEmpty(Convert.ToString(row.Cells[colProteinAccession.Index].Value)),
SmallMoleculeTransitionListReader.NullForEmpty(Convert.ToString(row.Cells[colProteinGene.Index].Value)),
SmallMoleculeTransitionListReader.NullForEmpty(Convert.ToString(row.Cells[colProteinSpecies.Index].Value)));
FastaSequence fastaSequence = null;
if (!backgroundProteome.IsNone)
{
ProteinMetadata protdbMetadata;
fastaSequence = backgroundProteome.GetFastaSequence(proteinName, out protdbMetadata);
// Fill in any gaps in pasted metadata with that in protdb
pastedMetadata = pastedMetadata.Merge(protdbMetadata);
}
// Strip any whitespace (tab, newline etc) In case it was copied out of a FASTA file
var fastaSequenceString = new string(Convert.ToString(row.Cells[colProteinSequence.Index].Value).Where(c => !Char.IsWhiteSpace(c)).ToArray());
if (!string.IsNullOrEmpty(fastaSequenceString))
{
try
{
if (fastaSequence == null) // Didn't match anything in protdb
{
fastaSequence = new FastaSequence(pastedMetadata.Name, pastedMetadata.Description,
new ProteinMetadata[0], fastaSequenceString);
}
else
{
if (fastaSequence.Sequence != fastaSequenceString)
{
fastaSequence = new FastaSequence(pastedMetadata.Name, pastedMetadata.Description,
fastaSequence.Alternatives, fastaSequenceString);
}
}
}
catch (Exception exception)
{
ShowProteinError(new PasteError
{
Line = i,
Column = colProteinDescription.Index,
Message = string.Format(Resources.PasteDlg_AddProteins_Invalid_protein_sequence__0__, exception.Message)
});
return null;
}
}
if (fastaSequence == null)
{
ShowProteinError(
new PasteError
{
Line = i,
Message = backgroundProteome.IsNone
? Resources.PasteDlg_AddProteins_Missing_protein_sequence
: Resources.PasteDlg_AddProteins_This_protein_was_not_found_in_the_background_proteome_database
});
return null;
}
var description = pastedMetadata.Description;
if (!string.IsNullOrEmpty(description) && description != fastaSequence.Description)
{
fastaSequence = new FastaSequence(fastaSequence.Name, description, fastaSequence.Alternatives, fastaSequence.Sequence);
}
pastedMetadata = pastedMetadata.ChangeName(fastaSequence.Name).ChangeDescription(fastaSequence.Description); // Make sure these agree
var nodeGroupPep = new PeptideGroupDocNode(fastaSequence, pastedMetadata, new PeptideDocNode[0]);
nodeGroupPep = nodeGroupPep.ChangeSettings(document.Settings, SrmSettingsDiff.ALL);
var to = selectedPath;
if (to == null || to.Depth < (int)SrmDocument.Level.MoleculeGroups)
document = (SrmDocument)document.Add(nodeGroupPep);
else
{
Identity toId = selectedPath.GetIdentity((int)SrmDocument.Level.MoleculeGroups);
document = (SrmDocument)document.Insert(toId, nodeGroupPep);
}
selectedPath = new IdentityPath(nodeGroupPep.Id);
}
return document;
}
private const char TRANSITION_LIST_SEPARATOR = TextUtil.SEPARATOR_TSV;
private static readonly ColumnIndices TRANSITION_LIST_COL_INDICES = new ColumnIndices(
0, 1, 2, 3);
private int ColumnIndex(string name)
{
var col = gridViewTransitionList.Columns[name];
return col == null ? -1: gridViewTransitionList.Columns.IndexOf(col);
}
private SrmDocument AddTransitionList(SrmDocument document, ref IdentityPath selectedPath)
{
if (tabControl1.SelectedTab != tabPageTransitionList)
return document;
if (IsMolecule)
{
// Save the current column order to settings
var active = new List<string>();
for (int order = 0; order < gridViewTransitionList.Columns.Count; order++)
{
for (int gridcol = 0; gridcol < gridViewTransitionList.Columns.Count; gridcol++)
{
var dataGridViewColumn = gridViewTransitionList.Columns[gridcol];
if (dataGridViewColumn.DisplayIndex == order)
{
if (dataGridViewColumn.Visible)
active.Add(dataGridViewColumn.Name);
break;
}
}
}
Settings.Default.CustomMoleculeTransitionInsertColumnsList = active;
var importer = new SmallMoleculeTransitionListPasteHandler(this);
IdentityPath firstAdded;
document = importer.CreateTargets(document, null, out firstAdded);
}
else
{
var backgroundProteome = GetBackgroundProteome(document);
var sbTransitionList = new StringBuilder();
var dictNameSeq = new Dictionary<string, FastaSequence>();
// Add all existing FASTA sequences in the document to the name to seq dictionary
// Including named peptide lists would cause the import code to give matching names
// in this list new names (e.g. with 1, 2, 3 appended). In this code, the names
// are intended to be merged.
foreach (var nodePepGroup in document.Children.Cast<PeptideGroupDocNode>().Where(n => !n.IsPeptideList))
{
if (!dictNameSeq.ContainsKey(nodePepGroup.Name))
dictNameSeq.Add(nodePepGroup.Name, (FastaSequence) nodePepGroup.PeptideGroup);
}
// Check for simple errors and build strings for import
for (int i = 0; i < gridViewTransitionList.Rows.Count; i++)
{
var row = gridViewTransitionList.Rows[i];
var peptideSequence = Convert.ToString(row.Cells[colTransitionPeptide.Index].Value);
var proteinName = Convert.ToString(row.Cells[colTransitionProteinName.Index].Value);
var precursorMzText = Convert.ToString(row.Cells[colTransitionPrecursorMz.Index].Value);
var productMzText = Convert.ToString(row.Cells[colTransitionProductMz.Index].Value);
if (string.IsNullOrEmpty(peptideSequence) && string.IsNullOrEmpty(proteinName))
{
continue;
}
if (string.IsNullOrEmpty(peptideSequence))
{
ShowTransitionError(new PasteError
{
Column = colTransitionPeptide.Index,
Line = i,
Message = Resources.PasteDlg_ListPeptideSequences_The_peptide_sequence_cannot_be_blank
});
return null;
}
if (!FastaSequence.IsExSequence(peptideSequence))
{
ShowTransitionError(new PasteError
{
Column = colTransitionPeptide.Index,
Line = i,
Message = Resources.PasteDlg_ListPeptideSequences_This_peptide_sequence_contains_invalid_characters
});
return null;
}
double mz;
if (!double.TryParse(precursorMzText, out mz))
{
ShowTransitionError(new PasteError
{
Column = colTransitionPrecursorMz.Index,
Line = i,
Message = Resources.PasteDlg_AddTransitionList_The_precursor_m_z_must_be_a_number_
});
return null;
}
if (!double.TryParse(productMzText, out mz))
{
ShowTransitionError(new PasteError
{
Column = colTransitionProductMz.Index,
Line = i,
Message = Resources.PasteDlg_AddTransitionList_The_product_m_z_must_be_a_number_
});
return null;
}
const char sep = TRANSITION_LIST_SEPARATOR;
// Add columns in order specified by TRANSITION_LIST_COL_INDICES
sbTransitionList
.Append(proteinName).Append(sep)
.Append(peptideSequence).Append(sep)
.Append(precursorMzText).Append(sep)
.Append(productMzText).AppendLine();
// Build FASTA sequence text in cases where it is known
if (!dictNameSeq.ContainsKey(proteinName))
{
var fastaSeq = backgroundProteome.GetFastaSequence(proteinName);
if (fastaSeq != null)
dictNameSeq.Add(proteinName, fastaSeq);
}
}
if (sbTransitionList.Length == 0)
return document;
// Do the actual import into PeptideGroupDocNodes
IEnumerable<PeptideGroupDocNode> peptideGroupDocNodes;
try
{
List<TransitionImportErrorInfo> errorList = new List<TransitionImportErrorInfo>();
List<MeasuredRetentionTime> irtPeptides = new List<MeasuredRetentionTime>();
List<SpectrumMzInfo> librarySpectra = new List<SpectrumMzInfo>();
var inputs = new MassListInputs(sbTransitionList.ToString(), LocalizationHelper.CurrentCulture, TRANSITION_LIST_SEPARATOR);
var importer = new MassListImporter(document, inputs);
// TODO: support long-wait broker
if (importer.PreImport(null, TRANSITION_LIST_COL_INDICES, false))
peptideGroupDocNodes = importer.DoImport(null, dictNameSeq, irtPeptides, librarySpectra, errorList);
else
peptideGroupDocNodes = new PeptideGroupDocNode[0];
if (errorList.Any())
{
var firstError = errorList[0];
if (firstError.LineNum.HasValue)
{
throw new LineColNumberedIoException(firstError.ErrorMessage, firstError.LineNum.Value, (firstError.Column ?? 0) - 1);
}
else
{
throw new InvalidDataException(firstError.ErrorMessage);
}
}
}
catch (LineColNumberedIoException x)
{
var columns = new[]
{
colTransitionProteinName,
colPeptideSequence,
colTransitionPrecursorMz,
colTransitionProductMz
};
ShowTransitionError(new PasteError
{
Column = x.ColumnIndex >= 0 ? columns[x.ColumnIndex].Index : 0,
Line = (int) x.LineNumber - 1,
Message = x.PlainMessage
});
return null;
}
catch (InvalidDataException x)
{
ShowTransitionError(new PasteError
{
Message = x.Message
});
return null;
}
catch (InvalidOperationException x)
{
ShowTransitionError(new PasteError
{
Message = x.Message
});
return null;
}
// Insert the resulting nodes into the document tree, merging when possible
bool after = false;
foreach (var nodePepGroup in peptideGroupDocNodes)
{
PeptideGroupDocNode nodePepGroupExist = FindPeptideGroupDocNode(document, nodePepGroup);
if (nodePepGroupExist != null)
{
var nodePepGroupNew = nodePepGroupExist.Merge(nodePepGroup);
if (!ReferenceEquals(nodePepGroupExist, nodePepGroupNew))
document = (SrmDocument) document.ReplaceChild(nodePepGroupNew);
}
else
{
// Add to the end, if no insert node
var to = selectedPath;
if (to == null || to.Depth < (int) SrmDocument.Level.MoleculeGroups)
document = (SrmDocument) document.Add(nodePepGroup);
else
{
Identity toId = selectedPath.GetIdentity((int) SrmDocument.Level.MoleculeGroups);
document = (SrmDocument) document.Insert(toId, nodePepGroup, after);
}
selectedPath = new IdentityPath(nodePepGroup.Id);
// All future insertions should be after, to avoid reversing the list
after = true;
}
}
}
return document;
}
private static PeptideGroupDocNode FindPeptideGroupDocNode(SrmDocument document, PeptideGroupDocNode nodePepGroup)
{
if (!nodePepGroup.IsPeptideList)
return (PeptideGroupDocNode) document.FindNode(nodePepGroup.PeptideGroup);
// Find peptide lists by name
return FindPeptideGroupDocNode(document, nodePepGroup.Name);
}
private static PeptideGroupDocNode FindPeptideGroupDocNode(SrmDocument document, String name)
{
return document.MoleculeGroups.FirstOrDefault(n => Equals(name, n.Name));
}
private PeptideGroupDocNode GetSelectedPeptideGroupDocNode(SrmDocument document, IdentityPath selectedPath)
{
var to = selectedPath;
if (to != null && to.Depth >= (int)SrmDocument.Level.MoleculeGroups)
return (PeptideGroupDocNode) document.FindNode(to.GetIdentity((int) SrmDocument.Level.MoleculeGroups));
PeptideGroupDocNode lastPeptideGroupDocuNode = null;
foreach (PeptideGroupDocNode peptideGroupDocNode in document.MoleculeGroups)
{
lastPeptideGroupDocuNode = peptideGroupDocNode;
}
return lastPeptideGroupDocuNode;
}
// Select transition list column visibility
// Inspired by http://www.codeproject.com/Articles/31987/A-DataGridView-Column-Show-Hide-Popup
private void CheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
gridViewTransitionList.Columns[e.Index].Visible = (e.NewValue == CheckState.Checked);
}
private void btnCustomMoleculeColumns_Click(object sender, EventArgs e)
{
var checkedListBox = new CheckedListBox {CheckOnClick = true};
checkedListBox.ItemCheck += CheckedListBox_ItemCheck;
checkedListBox.Items.Clear();
foreach (DataGridViewColumn c in gridViewTransitionList.Columns)
{
checkedListBox.Items.Add(c.HeaderText, c.Visible);
}
checkedListBox.Height = checkedListBox.Items.Count * radioMolecule.Height * 12 / 10;
checkedListBox.Width = radioMolecule.Width * 3;
var controlHost = new ToolStripControlHost(checkedListBox)
{
Padding = Padding.Empty,
Margin = Padding.Empty,
AutoSize = false
};
var popup = new ToolStripDropDown {Padding = Padding.Empty};
popup.Items.Add(controlHost);
popup.Show(btnCustomMoleculeColumns.PointToScreen(new Point(0, -checkedListBox.Height)));
}
private void btnTransitionListHelp_Click(object sender, EventArgs e)
{
// ReSharper disable LocalizableElement
var helpText = Resources.PasteDlg_btnTransitionListHelp_Click_;
if (btnCustomMoleculeColumns.Visible)
{
helpText = TextUtil.LineSeparate(Resources.PasteDlg_btnTransitionListHelp_Click_SmallMol_,
string.Join(", ", SmallMoleculeTransitionListColumnHeaders.KnownHeaders),
string.Format(Resources.PasteDlg_btnTransitionListHelp_Click_Supported_values_for__0__are___1_, SmallMoleculeTransitionListColumnHeaders.imUnits, string.Join(", ", Enum.GetNames(typeof(eIonMobilityUnits))))+
string.Empty,
Resources.PasteDlg_btnTransitionListHelp_Click_2_,
string.Empty,
Resources.FormulaBox_FormulaHelpText_Formulas_are_written_in_standard_chemical_notation__e_g___C2H6O____Heavy_isotopes_are_indicated_by_a_prime__e_g__C__for_C13__or_double_prime_for_less_abundant_stable_iostopes__e_g__O__for_O17__O__for_O18__ +
string.Empty,
Adduct.Tips);
}
// CONSIDER(bspratt) use DocumentationViewer instead, this is quite a lot of text
helpText = TextUtil.LineSeparate(Resources.PasteDlg_btnTransitionListHelp_Click_Transition_List_Help,
string.Empty,
helpText);
// ReSharper restore LocalizableElement
MessageDlg.Show(this, helpText);
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
DialogResult = DialogResult.Cancel;
}
private static void OnDocumentUIChanged(object sender, DocumentChangedEventArgs e)
{
}
public PasteFormat PasteFormat
{
get
{
return GetPasteFormat(tabControl1.SelectedTab);
}
set
{
var tab = GetTabPage(value);
btnTransitionListHelp.Visible =
btnCustomMoleculeColumns.Visible = radioMolecule.Visible = radioPeptide.Visible = (value == PasteFormat.transition_list);
if (value == PasteFormat.transition_list)
{
if (ModeUI == SrmDocument.DOCUMENT_TYPE.proteomic)
{
radioPeptide.Checked = true;
}
else if (ModeUI == SrmDocument.DOCUMENT_TYPE.small_molecules)
{
radioPeptide.Checked = false;
}
else
{
radioPeptide.Checked = Settings.Default.TransitionListInsertPeptides;
}
IsMolecule = !radioPeptide.Checked;
UpdateMoleculeType();
}
for (int i = tabControl1.Controls.Count - 1; i >= 0; i--)
{
if (tabControl1.Controls[i] != tab)
{
tabControl1.Controls.RemoveAt(i);
}
}
if (tab.Parent == null)
{
tabControl1.Controls.Add(tab);
}
tabControl1.SelectedTab = tab;
AcceptButton = tabControl1.SelectedTab != tabPageFasta ? btnInsert : null;
}
}
public string Description
{
get
{
switch (PasteFormat)
{
case PasteFormat.fasta: return Resources.PasteDlg_Description_Insert_FASTA;
case PasteFormat.protein_list: return Resources.PasteDlg_Description_Insert_protein_list;
case PasteFormat.peptide_list: return Resources.PasteDlg_Description_Insert_peptide_list;
case PasteFormat.transition_list: return Resources.PasteDlg_Description_Insert_transition_list;
}
return Resources.PasteDlg_Description_Insert;
}
}
// ReSharper disable MemberCanBeMadeStatic.Local
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
// Should no longer be possible to change tabs
}
// ReSharper restore MemberCanBeMadeStatic.Local
private PasteFormat GetPasteFormat(TabPage tabPage)
{
if (tabPage == tabPageFasta)
{
return PasteFormat.fasta;
}
if (tabPage == tabPageProteinList)
{
return PasteFormat.protein_list;
}
if (tabPage == tabPagePeptideList)
{
return PasteFormat.peptide_list;
}
if (tabPage == tabPageTransitionList)
{
return PasteFormat.transition_list;
}
return PasteFormat.none;
}
private TabPage GetTabPage(PasteFormat pasteFormat)
{
switch (pasteFormat)
{
case PasteFormat.fasta:
return tabPageFasta;
case PasteFormat.protein_list:
return tabPageProteinList;
case PasteFormat.peptide_list:
return tabPagePeptideList;
case PasteFormat.transition_list:
return tabPageTransitionList;
}
return null;
}
private static BackgroundProteome GetBackgroundProteome(SrmDocument srmDocument)
{
return srmDocument.Settings.PeptideSettings.BackgroundProteome;
}
private void gridViewProteins_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
HideNoErrors();
if (e.ColumnIndex < 0 || e.RowIndex < 0)
{
return;
}
var column = gridViewProteins.Columns[e.ColumnIndex];
if (column != colProteinName)
{
return;
}
var row = gridViewProteins.Rows[e.RowIndex];
var proteinName = Convert.ToString(row.Cells[e.ColumnIndex].Value);
if (string.IsNullOrEmpty(proteinName))
{
gridViewProteins.Rows.Remove(row);
}
ProteinMetadata metadata;
FastaSequence fastaSequence = GetFastaSequence(row, proteinName, out metadata);
if (fastaSequence == null)
{
row.Cells[colProteinDescription.Index].Value = null;
row.Cells[colProteinSequence.Index].Value = null;
row.Cells[colProteinPreferredName.Index].Value = null;
row.Cells[colProteinAccession.Index].Value = null;
row.Cells[colProteinGene.Index].Value = null;
row.Cells[colProteinSpecies.Index].Value = null;
}
else
{
row.Cells[colProteinName.Index].Value = fastaSequence.Name; // Possibly the search was actually on accession, gene etc
row.Cells[colProteinDescription.Index].Value = fastaSequence.Description;
row.Cells[colProteinSequence.Index].Value = fastaSequence.Sequence;
row.Cells[colProteinPreferredName.Index].Value = (metadata == null) ? null : metadata.PreferredName;
row.Cells[colProteinAccession.Index].Value = (metadata == null) ? null : metadata.Accession;
row.Cells[colProteinGene.Index].Value = (metadata == null) ? null : metadata.Gene;
row.Cells[colProteinSpecies.Index].Value = (metadata == null) ? null : metadata.Species;
}
}
private void gridViewPeptides_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
{
return;
}
var row = gridViewPeptides.Rows[e.RowIndex];
var column = gridViewPeptides.Columns[e.ColumnIndex];
if (column != colPeptideProtein)
{
return;
}
var proteinName = Convert.ToString(row.Cells[colPeptideProtein.Index].Value);
ProteinMetadata metadata;
FastaSequence fastaSequence = GetFastaSequence(row, proteinName, out metadata);
row.Cells[colPeptideProteinDescription.Index].Value = fastaSequence == null ? null : fastaSequence.Description;
}
/// <summary>
/// Enumerates table entries for all proteins matching a pasted peptide.
/// This can't be done on gridViewPeptides_CellValueChanged because we are creating new cells.
/// </summary>
private void EnumerateProteins(DataGridView dataGridView, int rowIndex, bool keepAllPeptides,
ref int numUnmatched, ref int numMultipleMatches, ref int numFiltered, HashSet<string> seenPepSeq)
{
HideNoErrors();
var row = dataGridView.Rows[rowIndex];
int sequenceIndex = Equals(dataGridView, gridViewPeptides)
? colPeptideSequence.Index
: (Equals(dataGridView, gridViewTransitionList) ? colTransitionPeptide.Index : -1);
int proteinIndex = Equals(dataGridView, gridViewPeptides)
? colPeptideProtein.Index
: (Equals(dataGridView, gridViewTransitionList) ? colTransitionProteinName.Index : -1);
var proteinName = Convert.ToString(row.Cells[proteinIndex].Value);
var pepModSequence = Convert.ToString(row.Cells[sequenceIndex].Value);
// Only enumerate the proteins if the user has not specified a protein.
if (!string.IsNullOrEmpty(proteinName))
return;
// If there is no peptide sequence and no protein, remove this entry.
if (string.IsNullOrEmpty(pepModSequence))
{
dataGridView.Rows.Remove(row);
return;
}
string peptideSequence = FastaSequence.StripModifications(pepModSequence);
// Check to see if this is a new sequence because we don't want to count peptides more than once for
// the FilterMatchedPeptidesDlg.
bool newSequence = !seenPepSeq.Contains(peptideSequence);
if(newSequence)
{
// If we are not keeping filtered peptides, and this peptide does not match current filter
// settings, remove this peptide.
if (!FastaSequence.IsExSequence(peptideSequence))
{
dataGridView.CurrentCell = row.Cells[sequenceIndex];
throw new InvalidDataException(Resources.PasteDlg_ListPeptideSequences_This_peptide_sequence_contains_invalid_characters);
}
seenPepSeq.Add(peptideSequence);
}
var proteinNames = GetProteinNamesForPeptideSequence(peptideSequence);
bool isUnmatched = proteinNames == null || proteinNames.Count == 0;
bool hasMultipleMatches = proteinNames != null && proteinNames.Count > 1;
bool isFiltered = !DocumentUiContainer.Document.Settings.Accept(peptideSequence);
if(newSequence)
{
numUnmatched += isUnmatched ? 1 : 0;
numMultipleMatches += hasMultipleMatches ? 1 : 0;
numFiltered += isFiltered ? 1 : 0;
}
// No protein matches found, so we do not need to enumerate this peptide.
if (isUnmatched)
{
// If we are not keeping unmatched peptides, then remove this peptide.
if (!keepAllPeptides && !Settings.Default.LibraryPeptidesAddUnmatched)
dataGridView.Rows.Remove(row);
// Even if we are keeping this peptide, it has no matches so we don't enumerate it.
return;
}
// If there are multiple protein matches, and we are filtering such peptides, remove this peptide.
if (!keepAllPeptides &&
(hasMultipleMatches && FilterMultipleProteinMatches == BackgroundProteome.DuplicateProteinsFilter.NoDuplicates)
|| (isFiltered && !Settings.Default.LibraryPeptidesKeepFiltered))
{
dataGridView.Rows.Remove(row);
return;
}
row.Cells[proteinIndex].Value = proteinNames[0];
// Only using the first occurence.
if(!keepAllPeptides && FilterMultipleProteinMatches == BackgroundProteome.DuplicateProteinsFilter.FirstOccurence)
return;
// Finally, enumerate all proteins for this peptide.
for (int i = 1; i < proteinNames.Count; i ++)
{
var newRow = dataGridView.Rows[dataGridView.Rows.Add()];
// Copy all cells, except for the protein name as well as any cells that are not null,
// meaning that they have already been filled out by CellValueChanged.
for(int x = 0; x < row.Cells.Count; x++)
{
if (newRow.Cells[proteinIndex].Value != null)
continue;
if (x == proteinIndex)
newRow.Cells[proteinIndex].Value = proteinNames[i];
else
newRow.Cells[x].Value = row.Cells[x].Value;
}
}
}
private void gridViewTransitionList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
HideNoErrors();
if (e.ColumnIndex < 0 || e.RowIndex < 0)
{
return;
}
var row = gridViewTransitionList.Rows[e.RowIndex];
var proteinName = Convert.ToString(row.Cells[colTransitionProteinName.Index].Value);
var column = gridViewTransitionList.Columns[e.ColumnIndex];
if (column != colTransitionProteinName)
{
return;
}
ProteinMetadata metadata;
FastaSequence fastaSequence = GetFastaSequence(row, proteinName, out metadata);
if (fastaSequence != null)
{
row.Cells[colTransitionProteinDescription.Index].Value = fastaSequence.Description;
// CONSIDER (bspratt) show other parts of protein metadata here as well - gene, accession etc
}
}
private FastaSequence GetFastaSequence(DataGridViewRow row, string proteinName, out ProteinMetadata metadata)
{
metadata = null;
var backgroundProteome = GetBackgroundProteome(DocumentUiContainer.DocumentUI);
if (backgroundProteome.IsNone)
return null;
var fastaSequence = backgroundProteome.GetFastaSequence(proteinName, out metadata);
if (fastaSequence == null)
{
// Sometimes the protein name in the background proteome will have an extra "|" on the end.
// In that case, update the name of the protein to match the one in the database.
fastaSequence = backgroundProteome.GetFastaSequence(proteinName + @"|");
if (fastaSequence != null)
{
row.Cells[colPeptideProtein.Index].Value = fastaSequence.Name;
}
}
return fastaSequence;
}
private void OnEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
_statementCompletionEditBox.Attach(((DataGridView) sender).EditingControl as TextBox);
}
private void btnInsert_Click(object sender, EventArgs e)
{
OkDialog();
}
public void OkDialog()
{
bool error = false;
IdentityPath newSelectedPath = SelectedPath;
bool? keepEmptyProteins = null;
List<PeptideGroupDocNode> newPeptideGroups = null;
Program.MainWindow.ModifyDocument(
Description,
document =>
{
newSelectedPath = SelectedPath;
var newDocument = GetNewDocument(document, false, ref newSelectedPath, out newPeptideGroups);
if (newDocument == null)
{
error = true;
return document;
}
if (!keepEmptyProteins.HasValue)
{
keepEmptyProteins = ImportFastaHelper.AskWhetherToKeepEmptyProteins(this,
newPeptideGroups.Count(pepGroup => pepGroup.PeptideCount == 0), _entryCreators);
if (!keepEmptyProteins.HasValue)
{
// Cancelled
error = true;
return document;
}
}
if (!keepEmptyProteins.Value)
{
newDocument = ImportPeptideSearch.RemoveProteinsByPeptideCount(newDocument, 1);
}
return newDocument;
}, docPair =>
{
if (error)
return null;
MessageType singular;
MessageType plural;
string extraInfo = null;
DataGridViewEx grid = null;
IEnumerable<string> added = null;
DataGridViewColumn col = null;
var count = 0;
switch (PasteFormat)
{
case PasteFormat.fasta:
{
singular = MessageType.inserted_proteins_fasta;
plural = MessageType.inserted_proteins_fasta;
extraInfo = tbxFasta.Text;
added = newPeptideGroups.Select(group => group.AuditLogText);
count = newPeptideGroups.Count;
break;
}
case PasteFormat.protein_list:
singular = MessageType.inserted_protein;
plural = MessageType.inserted_proteins;
grid = gridViewProteins;
col = colProteinName;
break;
case PasteFormat.peptide_list:
singular = MessageType.inserted_peptide;
plural = MessageType.inserted_peptides;
grid = gridViewPeptides;
col = colPeptideSequence;
break;
case PasteFormat.transition_list:
singular = MessageType.inserted_transition;
plural = MessageType.inserted_transitions;
grid = gridViewTransitionList;
col = colTransitionPeptide;
break;
default:
return null;
}
if (grid != null)
{
extraInfo = grid.GetCopyText();
if (col != null)
{
added = grid.Rows.OfType<DataGridViewRow>().Select(row => row.Cells[col.Index].Value as string);
count = grid.RowCount - 1;
}
}
return AuditLogEntry.CreateCountChangeEntry(singular, plural, docPair.NewDocumentType, added, count)
.ChangeExtraInfo(extraInfo)
.Merge(docPair, _entryCreators, false);
});
if (error)
{
return;
}
SelectedPath = newSelectedPath;
DialogResult = DialogResult.OK;
}
public override void CancelDialog()
{
DialogResult = DialogResult.Cancel;
}
private void tbxFasta_TextChanged(object sender, EventArgs e)
{
HideNoErrors();
}
private void gridViewPeptides_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
_statementCompletionEditBox.MatchTypes = e.ColumnIndex == colPeptideSequence.Index
? ProteinMatchTypes.Singleton(ProteinMatchType.sequence) : ProteinMatchTypes.EMPTY;
}
private void gridViewProteins_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
_statementCompletionEditBox.MatchTypes = e.ColumnIndex == colProteinName.Index
? ProteinMatchTypes.ALL.Except(ProteinMatchType.sequence) : ProteinMatchTypes.EMPTY; // name, description, accession, etc
}
private void gridViewTransitionList_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
_statementCompletionEditBox.MatchTypes = e.ColumnIndex == colTransitionPeptide.Index
? ProteinMatchTypes.Singleton(ProteinMatchType.sequence) : ProteinMatchTypes.EMPTY;
}
private void gridViewProteins_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
if (!gridViewProteins.IsCurrentCellInEditMode)
{
PasteProteins();
e.Handled = true;
}
}
}
public void PasteFasta() // For functional test use
{
tbxFasta.Text = ClipboardHelper.GetClipboardText(this);
}
public void PasteProteins()
{
Paste(gridViewProteins, false);
}
public void PasteTransitions()
{
var document = DocumentUiContainer.Document;
var backgroundProteome = document.Settings.PeptideSettings.BackgroundProteome;
bool enumerateProteins = !IsMolecule && !backgroundProteome.IsNone;
Paste(gridViewTransitionList, enumerateProteins);
}
private void gridViewPeptides_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
if (!gridViewPeptides.IsCurrentCellInEditMode)
{
PastePeptides();
e.Handled = true;
}
}
}
public void PastePeptides()
{
var document = DocumentUiContainer.Document;
var backgroundProteome = document.Settings.PeptideSettings.BackgroundProteome;
Paste(gridViewPeptides, !backgroundProteome.IsNone);
}
/// <summary>
/// Removes the given number of last rows in the given DataGridView.
/// </summary>
private static void RemoveLastRows(DataGridView dataGridView, int numToRemove)
{
int rowCount = dataGridView.Rows.Count;
for (int i = rowCount - numToRemove; i < rowCount; i++)
{
dataGridView.Rows.Remove(dataGridView.Rows[dataGridView.Rows.Count - 2]);
}
}
public static BackgroundProteome.DuplicateProteinsFilter FilterMultipleProteinMatches
{
get
{
return Helpers.ParseEnum(Settings.Default.LibraryPeptidesAddDuplicatesEnum,
BackgroundProteome.DuplicateProteinsFilter.AddToAll);
}
}
private void Paste(DataGridView dataGridView, bool enumerateProteins)
{
string text = ClipboardHelper.GetClipboardText(this);
if (text == null)
{
return;
}
int numUnmatched;
int numMultipleMatches;
int numFiltered;
int prevRowCount = dataGridView.RowCount;
try
{
Paste(dataGridView, text, enumerateProteins, enumerateProteins, out numUnmatched,
out numMultipleMatches, out numFiltered);
}
// User pasted invalid text.
catch(InvalidDataException e)
{
dataGridView.Show();
// Show the invalid text, then remove all newly added rows.
MessageDlg.ShowException(this, e);
RemoveLastRows(dataGridView, dataGridView.RowCount - prevRowCount);
return;
}
// If we have no unmatched, no multiple matches, and no filtered, we do not need to show
// the FilterMatchedPeptidesDlg.
if (numUnmatched + numMultipleMatches + numFiltered == 0)
return;
using (var filterPeptidesDlg =
new FilterMatchedPeptidesDlg(numMultipleMatches, numUnmatched, numFiltered,
dataGridView.RowCount - prevRowCount == 1, false))
{
var result = filterPeptidesDlg.ShowDialog(this);
// If the user is keeping all peptide matches, we don't need to redo the paste.
bool keepAllPeptides = ((FilterMultipleProteinMatches ==
BackgroundProteome.DuplicateProteinsFilter.AddToAll || numMultipleMatches == 0)
&& (Settings.Default.LibraryPeptidesAddUnmatched || numUnmatched == 0)
&& (Settings.Default.LibraryPeptidesKeepFiltered || numFiltered == 0));
// If the user is filtering some peptides, or if the user clicked cancel, remove all rows added as
// a result of the paste.
if (result == DialogResult.Cancel || !keepAllPeptides)
RemoveLastRows(dataGridView, dataGridView.RowCount - prevRowCount);
// Redo the paste with the new filter settings.
if (result != DialogResult.Cancel && !keepAllPeptides)
{
Paste(dataGridView, text, enumerateProteins, !enumerateProteins, out numUnmatched,
out numMultipleMatches, out numFiltered);
_entryCreators.Add(filterPeptidesDlg.FormSettings.EntryCreator);
}
}
}
/// <summary>
/// Paste the clipboard text into the specified DataGridView.
/// The clipboard text is assumed to be tab separated values.
/// The values are matched up to the columns in the order they are displayed.
/// </summary>
private void Paste(DataGridView dataGridView, string text, bool enumerateProteins, bool keepAllPeptides,
out int numUnmatched, out int numMulitpleMatches, out int numFiltered)
{
numUnmatched = numMulitpleMatches = numFiltered = 0;
var columns = new DataGridViewColumn[dataGridView.Columns.Count];
dataGridView.Columns.CopyTo(columns, 0);
Array.Sort(columns, (a,b)=>a.DisplayIndex - b.DisplayIndex);
HashSet<string> listPepSeqs = new HashSet<string>();
foreach (var values in ParseColumnarData(text))
{
var row = dataGridView.Rows[dataGridView.Rows.Add()];
using (var valueEnumerator = values.GetEnumerator())
{
foreach (DataGridViewColumn column in columns)
{
if (column.ReadOnly || !column.Visible)
{
continue;
}
if (!valueEnumerator.MoveNext())
{
break;
}
row.Cells[column.Index].Value = valueEnumerator.Current;
}
}
if (enumerateProteins)
{
EnumerateProteins(dataGridView, row.Index, keepAllPeptides, ref numUnmatched, ref numMulitpleMatches,
ref numFiltered, listPepSeqs);
}
}
}
static IEnumerable<IList<string>> ParseColumnarData(String text)
{
IFormatProvider formatProvider;
char separator;
Type[] types;
if (!MassListImporter.IsColumnar(text, out formatProvider, out separator, out types))
{
string line;
var reader = new StringReader(text);
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (string.IsNullOrEmpty(line))
{
continue;
}
yield return new[] {line};
}
}
else
{
string line;
var reader = new StringReader(text);
while ((line = reader.ReadLine()) != null)
{
// Avoid trimming off tabs, which will shift columns
line = line.Trim('\r', '\n', TextUtil.SEPARATOR_SPACE);
if (string.IsNullOrEmpty(line))
{
continue;
}
yield return line.ParseDsvFields(separator); // Properly handles quoted commas etc
}
}
}
private List<String> GetProteinNamesForPeptideSequence(String peptideSequence)
{
var document = DocumentUiContainer.Document;
var backgroundProteome = document.Settings.PeptideSettings.BackgroundProteome;
if (backgroundProteome.IsNone)
{
return null;
}
using (var proteomeDb = backgroundProteome.OpenProteomeDb())
{
var digestion = backgroundProteome.GetDigestion(proteomeDb, document.Settings.PeptideSettings);
if (digestion == null)
{
return null;
}
var proteins = digestion.GetProteinsWithSequence(peptideSequence);
return proteins.ConvertAll(protein => protein.Name);
}
}
private void OnCellEndEdit(object sender, DataGridViewCellEventArgs e)
{
_statementCompletionEditBox.HideStatementCompletionForm();
}
private void gridViewTransitionList_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
if (!gridViewTransitionList.IsCurrentCellInEditMode)
{
PasteTransitions();
e.Handled = true;
}
}
}
private void OnLoad(object sender, EventArgs e)
{
// If you set this in the Designer, DataGridView has a defect that causes it to throw an
// exception if the the cursor is positioned over the record selector column during loading.
gridViewPeptides.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
gridViewProteins.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
gridViewTransitionList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
#region Testing
public class FastaTab : IFormView {}
public class ProteinListTab : IFormView { }
public class PeptideListTab : IFormView { }
public class TransitionListTab : IFormView { }
private static readonly IFormView[] TAB_PAGES =
{
new FastaTab(), new ProteinListTab(), new PeptideListTab(), new TransitionListTab()
};
public IFormView ShowingFormView
{
get
{
int selectedIndex = 0;
Invoke(new Action(() => selectedIndex = GetSelectedTabIndex()));
return TAB_PAGES[selectedIndex];
}
}
private int GetSelectedTabIndex()
{
if (tabControl1.SelectedTab == tabPageFasta)
return 0;
else if (tabControl1.SelectedTab == tabPageProteinList)
return 1;
else if (tabControl1.SelectedTab == tabPagePeptideList)
return 2;
return 3;
}
public int PeptideRowCount
{
get { return gridViewPeptides.RowCount; }
}
public int TransitionRowCount
{
get { return gridViewTransitionList.RowCount; }
}
public bool PeptideRowsContainProtein(Predicate<string> found)
{
var peptideRows = new DataGridViewRow[gridViewPeptides.RowCount];
gridViewPeptides.Rows.CopyTo(peptideRows, 0);
return peptideRows.Take(gridViewPeptides.RowCount-1).Contains(row =>
{
var protein = row.Cells[colPeptideProtein.Index].Value;
return found(protein != null ? protein.ToString() : null);
});
}
public bool PeptideRowsContainPeptide(Predicate<string> found)
{
var peptideRows = new DataGridViewRow[gridViewPeptides.RowCount];
gridViewPeptides.Rows.CopyTo(peptideRows, 0);
return peptideRows.Take(gridViewPeptides.RowCount-1).Contains(row =>
{
var peptide = row.Cells[colPeptideSequence.Index].Value;
return found(peptide != null ? peptide.ToString() : null);
});
}
public bool TransitionListRowsContainProtein(Predicate<string> found)
{
var transitionListRows = new DataGridViewRow[gridViewTransitionList.RowCount];
gridViewPeptides.Rows.CopyTo(transitionListRows, 0);
return transitionListRows.Take(gridViewTransitionList.RowCount-1).Contains(row =>
{
var protein = row.Cells[colTransitionProteinName.Index].Value;
return found(protein != null ? protein.ToString() : null);
});
}
public void ClearRows()
{
if(PasteFormat == PasteFormat.peptide_list)
gridViewPeptides.Rows.Clear();
if(PasteFormat == PasteFormat.transition_list)
gridViewTransitionList.Rows.Clear();
}
#endregion
private void radioPeptide_CheckedChanged(object sender, EventArgs e)
{
UpdateMoleculeType();
}
private void UpdateMoleculeType()
{
bool isPeptide = radioPeptide.Checked;
btnCustomMoleculeColumns.Enabled = radioMolecule.Checked;
Settings.Default.TransitionListInsertPeptides = isPeptide; // Remember for next time
//Skip updating if nothing needs to be changed
if ((isPeptide && gridViewTransitionList.ColumnCount == 5) || (!isPeptide && gridViewTransitionList.ColumnCount == 6))
return;
int rowCount = gridViewTransitionList.RowCount - 1;
if (rowCount > 0)
{
if (
MultiButtonMsgDlg.Show(this,
string.Format(
Resources.PasteDlg_UpdateMoleculeType_Possible_loss_of_data_could_occur_if_you_switch_to__0___Do_you_want_to_continue_,
isPeptide ? radioPeptide.Text : radioMolecule.Text), MultiButtonMsgDlg.BUTTON_YES) ==
DialogResult.Cancel)
{
radioPeptide.Checked = !isPeptide;
btnCustomMoleculeColumns.Enabled = radioMolecule.Checked;
return;
}
}
// Items that peptide and small molecules have in common, for swapping back and forth
var peptideGroupNames = new string[rowCount];
var peptideNames = new string[rowCount];
var productNames = new string[rowCount];
var precursorMzs = new string[rowCount];
var productMzs = new string[rowCount];
for (int i = 0; i < rowCount; i ++)
{
peptideGroupNames[i] = Convert.ToString(gridViewTransitionList.Rows[i].Cells[(isPeptide ? 0 : 3)].Value);
peptideNames[i] = Convert.ToString(gridViewTransitionList.Rows[i].Cells[(isPeptide ? 1 : 0)].Value);
precursorMzs[i] = Convert.ToString(gridViewTransitionList.Rows[i].Cells[(isPeptide ? 4 : 1)].Value);
productMzs[i] = Convert.ToString(gridViewTransitionList.Rows[i].Cells[(isPeptide ? 5 : 2)].Value);
}
gridViewTransitionList.Columns.Clear();
if (isPeptide)
{
gridViewTransitionList.Columns.Add(@"Peptide", Resources.PasteDlg_UpdateMoleculeType_Peptide);
gridViewTransitionList.Columns.Add(@"Precursor", Resources.PasteDlg_UpdateMoleculeType_Precursor_m_z);
gridViewTransitionList.Columns.Add(@"Product", Resources.PasteDlg_UpdateMoleculeType_Product_m_z);
gridViewTransitionList.Columns.Add(@"Protein", Resources.PasteDlg_UpdateMoleculeType_Protein_name);
gridViewTransitionList.Columns.Add(@"Description", Resources.PasteDlg_UpdateMoleculeType_Protein_description);
}
else
{
var defaultColumns = new List<string>(); // List of headers which will initially appear if no settings found
void AddColumn(string name, string headerLocalized, bool isDefaultColumn = false)
{
gridViewTransitionList.Columns.Add(name, headerLocalized);
if (isDefaultColumn)
defaultColumns.Add(name);
}
AddColumn(SmallMoleculeTransitionListColumnHeaders.moleculeGroup, Resources.PasteDlg_UpdateMoleculeType_Molecule_List_Name, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.namePrecursor, Resources.PasteDlg_UpdateMoleculeType_Precursor_Name, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.formulaPrecursor, Resources.PasteDlg_UpdateMoleculeType_Precursor_Formula, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.adductPrecursor, Resources.PasteDlg_UpdateMoleculeType_Precursor_Adduct, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.mzPrecursor, Resources.PasteDlg_UpdateMoleculeType_Precursor_m_z, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.chargePrecursor, Resources.PasteDlg_UpdateMoleculeType_Precursor_Charge, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.nameProduct, Resources.PasteDlg_UpdateMoleculeType_Product_Name);
AddColumn(SmallMoleculeTransitionListColumnHeaders.formulaProduct, Resources.PasteDlg_UpdateMoleculeType_Product_Formula, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.neutralLossProduct, Resources.PasteDlg_UpdateMoleculeType_Product_Neutral_Loss);
AddColumn(SmallMoleculeTransitionListColumnHeaders.adductProduct, Resources.PasteDlg_UpdateMoleculeType_Product_Adduct);
AddColumn(SmallMoleculeTransitionListColumnHeaders.mzProduct, Resources.PasteDlg_UpdateMoleculeType_Product_m_z, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.chargeProduct, Resources.PasteDlg_UpdateMoleculeType_Product_Charge, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.labelType, Resources.PasteDlg_UpdateMoleculeType_Label_Type);
AddColumn(SmallMoleculeTransitionListColumnHeaders.rtPrecursor, Resources.PasteDlg_UpdateMoleculeType_Explicit_Retention_Time, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.rtWindowPrecursor, Resources.PasteDlg_UpdateMoleculeType_Explicit_Retention_Time_Window);
AddColumn(SmallMoleculeTransitionListColumnHeaders.cePrecursor, Resources.PasteDlg_UpdateMoleculeType_Explicit_Collision_Energy, true);
AddColumn(SmallMoleculeTransitionListColumnHeaders.note, Resources.PasteDlg_UpdateMoleculeType_Note);
AddColumn(SmallMoleculeTransitionListColumnHeaders.idInChiKey, SmallMoleculeTransitionListColumnHeaders.idInChiKey); // No need to localize
AddColumn(SmallMoleculeTransitionListColumnHeaders.idCAS, SmallMoleculeTransitionListColumnHeaders.idCAS); // No need to localize
AddColumn(SmallMoleculeTransitionListColumnHeaders.idHMDB, SmallMoleculeTransitionListColumnHeaders.idHMDB); // No need to localize
AddColumn(SmallMoleculeTransitionListColumnHeaders.idInChi, SmallMoleculeTransitionListColumnHeaders.idInChi); // No need to localize
AddColumn(SmallMoleculeTransitionListColumnHeaders.idSMILES, SmallMoleculeTransitionListColumnHeaders.idSMILES); // No need to localize
AddColumn(SmallMoleculeTransitionListColumnHeaders.idKEGG, SmallMoleculeTransitionListColumnHeaders.idKEGG); // No need to localize
AddColumn(SmallMoleculeTransitionListColumnHeaders.slens, Resources.PasteDlg_UpdateMoleculeType_S_Lens);
AddColumn(SmallMoleculeTransitionListColumnHeaders.coneVoltage, Resources.PasteDlg_UpdateMoleculeType_Cone_Voltage);
AddColumn(SmallMoleculeTransitionListColumnHeaders.dtPrecursor, Resources.PasteDlg_UpdateMoleculeType_Explicit_Drift_Time__msec_);
AddColumn(SmallMoleculeTransitionListColumnHeaders.dtHighEnergyOffset, Resources.PasteDlg_UpdateMoleculeType_Explicit_Drift_Time_High_Energy_Offset__msec_);
AddColumn(SmallMoleculeTransitionListColumnHeaders.imPrecursor, Resources.PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility);
AddColumn(SmallMoleculeTransitionListColumnHeaders.imUnits, Resources.PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility_Units);
AddColumn(SmallMoleculeTransitionListColumnHeaders.imHighEnergyOffset, Resources.PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility_High_Energy_Offset);
AddColumn(SmallMoleculeTransitionListColumnHeaders.ccsPrecursor, Resources.PasteDlg_UpdateMoleculeType_Collisional_Cross_Section__sq_A_);
AddColumn(SmallMoleculeTransitionListColumnHeaders.compensationVoltage, Resources.PasteDlg_UpdateMoleculeType_Explicit_Compensation_Voltage);
AddColumn(SmallMoleculeTransitionListColumnHeaders.declusteringPotential, Resources.PasteDlg_UpdateMoleculeType_Explicit_Declustering_Potential);
// Now set order and visibility based on settings, if any
SetSmallMoleculeColumns(Settings.Default.CustomMoleculeTransitionInsertColumnsList.Any()
? Settings.Default.CustomMoleculeTransitionInsertColumnsList
: defaultColumns);
}
for (int i = 0; i < rowCount; i ++)
{
if (isPeptide)
{
gridViewTransitionList.Rows.Add(peptideNames[i], precursorMzs[i], productMzs[i],
peptideGroupNames[i], string.Empty);
}
else
{
gridViewTransitionList.Rows.Add(peptideGroupNames[i], peptideNames[i], productNames[i], string.Empty,
string.Empty, precursorMzs[i], productMzs[i]);
}
}
}
public bool IsMolecule
{
get { return radioMolecule.Checked; }
set
{
radioMolecule.Checked = value;
radioPeptide.Checked = Settings.Default.TransitionListInsertPeptides = !value; // Preserve for user convenience next time
}
}
public void SetSmallMoleculeColumns(List<string> columns)
{
Settings.Default.CustomMoleculeTransitionInsertColumnsList = columns;
if (Settings.Default.CustomMoleculeTransitionInsertColumnsList.Any())
{
for (int gridcol = 0; gridcol < gridViewTransitionList.Columns.Count; gridcol++)
{
gridViewTransitionList.Columns[gridcol].Visible = false;
}
var order = 0;
foreach (var colName in Settings.Default.CustomMoleculeTransitionInsertColumnsList)
{
// Make corresponding column visible, and next in column order
for (var gridcol = 0; gridcol < gridViewTransitionList.Columns.Count; gridcol++)
{
var dataGridViewColumn = gridViewTransitionList.Columns[gridcol];
if (dataGridViewColumn.Name.Equals(colName))
{
dataGridViewColumn.Visible = true;
dataGridViewColumn.DisplayIndex = order++;
break;
}
}
}
}
}
// For test support
public List<string> GetColumnNames()
{
return
gridViewTransitionList.Columns.OfType<DataGridViewColumn>()
.Where(c => c.Visible)
.OrderBy(c => c.DisplayIndex)
.Select(c => c.Name)
.ToList();
}
public int GetUsableColumnCount()
{
return gridViewTransitionList.Columns.GetColumnCount(DataGridViewElementStates.Visible) -
gridViewTransitionList.Columns.GetColumnCount(DataGridViewElementStates.ReadOnly);
}
class SmallMoleculeTransitionListPasteHandler : SmallMoleculeTransitionListReader
{
private readonly PasteDlg _pasteDlg;
public SmallMoleculeTransitionListPasteHandler(PasteDlg pasteDlg)
{
_pasteDlg = pasteDlg;
for (var i = 0; i < _pasteDlg.gridViewTransitionList.RowCount - 1; i++)
{
var cells = new List<string>();
for (var col = 0; col < _pasteDlg.gridViewTransitionList.Rows[i].Cells.Count; col++)
{
cells.Add(Convert.ToString(_pasteDlg.gridViewTransitionList.Rows[i].Cells[col].Value));
}
Rows.Add(new Row(this, i, cells));
}
}
public override void UpdateCellBackingStore(int row, int col, object value)
{
_pasteDlg.gridViewTransitionList.Rows[row].Cells[col].Value = value;
}
public override int ColumnIndex(string name)
{
return _pasteDlg.ColumnIndex(name);
}
public override void ShowTransitionError(PasteError error)
{
_pasteDlg.ShowTransitionError(error);
}
}
private void PasteDlg_KeyDown(object sender, KeyEventArgs e)
{
// This keyboard handling is necessary to get Escape and Enter keys to work correctly in this form
// They need to generally work, but not when grid controls are in edit mode and not Enter when the
// FASTA text box has the focus. Especially to make grid editing work as expected, it seems to be
// necessary to not have an Accept or Cancel button on the form.
switch (e.KeyCode)
{
case Keys.Escape:
// Somehow a grid in edit mode doesn't end up here, if there is no Cancel button on the form
CancelDialog();
e.Handled = true;
break;
case Keys.Enter:
// Allow the FASTA text box to have enter keys
if (!tbxFasta.Focused)
{
// Otherwise, OK the dialog
OkDialog();
e.Handled = true;
}
break;
}
}
}
public enum PasteFormat
{
none,
fasta,
protein_list,
peptide_list,
transition_list,
}
public class ImportFastaHelper
{
public ImportFastaHelper(TextBox tbxFasta, TextBox tbxError, Panel panelError, ToolTip helpTip)
{
_tbxFasta = tbxFasta;
_tbxError = tbxError;
_panelError = panelError;
_helpTip = helpTip;
}
public IdentityPath SelectedPath { get; set; }
private readonly TextBox _tbxFasta;
private TextBox TbxFasta { get { return _tbxFasta; } }
private readonly TextBox _tbxError;
private TextBox TbxError { get { return _tbxError; } }
private readonly Panel _panelError;
private Panel PanelError { get { return _panelError; } }
private readonly ToolTip _helpTip;
private ToolTip HelpTip { get { return _helpTip; } }
public SrmDocument AddFasta(SrmDocument document, IProgressMonitor monitor, ref IdentityPath selectedPath, out List<PeptideGroupDocNode> newPeptideGroups, out PasteError error)
{
newPeptideGroups = new List<PeptideGroupDocNode>();
var text = TbxFasta.Text;
if (text.Length == 0)
{
error = null;
return document;
}
if (!text.StartsWith(@">"))
{
error = new PasteError
{
Message = Resources.ImportFastaHelper_AddFasta_This_must_start_with____,
Column = 0,
Length = 1,
Line = 0,
};
return null;
}
string[] lines = text.Split('\n');
int lastNameLine = -1;
int aa = 0;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (line.StartsWith(@">"))
{
if (line.Trim().Length == 1)
{
error = new PasteError
{
Message = Resources.ImportFastaHelper_AddFasta_There_is_no_name_for_this_protein,
Column = 0,
Line = i,
Length = 1
};
return null;
}
if ((error = CheckSequence(aa, lastNameLine, lines)) != null)
return null;
lastNameLine = i;
aa = 0;
continue;
}
for (int column = 0; column < line.Length; column++)
{
char c = line[column];
if (AminoAcid.IsExAA(c))
aa++;
else if (!char.IsWhiteSpace(c) && c != '*')
{
error = new PasteError
{
Message =
string.Format(Resources.ImportFastaHelper_AddFasta___0___is_not_a_capital_letter_that_corresponds_to_an_amino_acid_, c),
Column = column,
Line = i,
Length = 1,
};
return null;
}
}
}
if ((error = CheckSequence(aa, lastNameLine, lines)) != null)
return null;
var importer = new FastaImporter(document, false);
try
{
var reader = new StringReader(TbxFasta.Text);
IdentityPath to = selectedPath;
IdentityPath firstAdded, nextAdd;
newPeptideGroups = importer.Import(reader, monitor, -1).ToList();
document = document.AddPeptideGroups(newPeptideGroups, false, to, out firstAdded, out nextAdd);
selectedPath = firstAdded;
}
catch (Exception exception)
{
error = new PasteError
{
Message = Resources.ImportFastaHelper_AddFasta_An_unexpected_error_occurred__ + exception.Message + @" (" + exception.GetType() + @")"
};
return null;
}
return document;
}
public void ShowFastaError(PasteError pasteError)
{
PanelError.Visible = true;
if (pasteError == null)
{
TbxError.Text = string.Empty;
TbxError.Visible = false;
return;
}
ShowFastaError(pasteError.Message);
TbxFasta.SelectionStart = Math.Max(0, TbxFasta.GetFirstCharIndexFromLine(pasteError.Line) + pasteError.Column);
TbxFasta.SelectionLength = Math.Min(pasteError.Length, TbxFasta.Text.Length - TbxFasta.SelectionStart);
TbxFasta.Focus();
}
public void ShowFastaError(string errorMsg)
{
PanelError.Visible = true;
if (string.IsNullOrEmpty(errorMsg))
{
TbxError.Text = string.Empty;
TbxError.Visible = false;
return;
}
TbxError.BackColor = Color.Red;
TbxError.ForeColor = Color.White;
TbxError.Text = errorMsg;
TbxError.Visible = true;
if (HelpTip != null)
{
// In case message is long, make it possible to see in a tip
HelpTip.SetToolTip(TbxError, errorMsg);
}
}
public void ClearFastaError()
{
TbxError.Text = string.Empty;
TbxError.Visible = false;
PanelError.Visible = false;
}
private static PasteError CheckSequence(int aa, int lastNameLine, string[] lines)
{
if (aa == 0 && lastNameLine >= 0)
{
return new PasteError
{
Message = Resources.ImportFastaHelper_CheckSequence_There_is_no_sequence_for_this_protein,
Column = 0,
Line = lastNameLine,
Length = lines[lastNameLine].Length
};
}
return null;
}
public static SrmDocument HandleEmptyPeptideGroups(IWin32Window parent, int emptyPeptideGroups, SrmDocument docCurrent, AuditLogEntryCreatorList entryCreatorList = null)
{
switch (AskWhetherToKeepEmptyProteins(parent, emptyPeptideGroups, entryCreatorList))
{
case true:
return docCurrent;
case false:
return ImportPeptideSearch.RemoveProteinsByPeptideCount(docCurrent, 1);
default:
return null;
}
}
/// <summary>
/// Display the dialog that says "This operation has added X new proteins with no peptides meeting your filter criteria".
/// </summary>
/// <returns>
/// null if the user cancels, true/false for whether the user says whether they want to keep empty proteins.
/// Also returns true if there were so many empty peptide groups that they have already been removed.
/// </returns>
public static bool? AskWhetherToKeepEmptyProteins(IWin32Window parent, int numberOfEmptyPeptideGroups, AuditLogEntryCreatorList entryCreatorList = null)
{
if (numberOfEmptyPeptideGroups > FastaImporter.MaxEmptyPeptideGroupCount)
{
MessageDlg.Show(parent, string.Format(Resources.SkylineWindow_ImportFasta_This_operation_discarded__0__proteins_with_no_peptides_matching_the_current_filter_settings_, numberOfEmptyPeptideGroups));
return true;
}
else if (numberOfEmptyPeptideGroups > 0)
{
using (var dlg = new EmptyProteinsDlg(numberOfEmptyPeptideGroups))
{
if (dlg.ShowDialog(parent) == DialogResult.Cancel)
return null;
if(entryCreatorList != null)
entryCreatorList.Add(dlg.FormSettings.EntryCreator);
// Remove all empty proteins, if requested by the user.
return dlg.IsKeepEmptyProteins;
}
}
return true;
}
}
}
| 1 | 14,423 | Should there be any changes to this file at all? | ProteoWizard-pwiz | .cs |
@@ -87,6 +87,7 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
var folderLoader caddytls.FolderLoader
var certSelector caddytls.CustomCertSelectionPolicy
var acmeIssuer *caddytls.ACMEIssuer
+ var autoPolicy *caddytls.AutomationPolicy
var internalIssuer *caddytls.InternalIssuer
var issuers []certmagic.Issuer
var onDemand bool | 1 | // Copyright 2015 Matthew Holt and The Caddy 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 httpcaddyfile
import (
"encoding/base64"
"encoding/pem"
"fmt"
"html"
"io/ioutil"
"net/http"
"reflect"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/caddyserver/caddy/v2/modules/caddytls"
"github.com/caddyserver/certmagic"
"github.com/mholt/acmez/acme"
"go.uber.org/zap/zapcore"
)
func init() {
RegisterDirective("bind", parseBind)
RegisterDirective("tls", parseTLS)
RegisterHandlerDirective("root", parseRoot)
RegisterHandlerDirective("redir", parseRedir)
RegisterHandlerDirective("respond", parseRespond)
RegisterHandlerDirective("route", parseRoute)
RegisterHandlerDirective("handle", parseHandle)
RegisterDirective("handle_errors", parseHandleErrors)
RegisterDirective("log", parseLog)
}
// parseBind parses the bind directive. Syntax:
//
// bind <addresses...>
//
func parseBind(h Helper) ([]ConfigValue, error) {
var lnHosts []string
for h.Next() {
lnHosts = append(lnHosts, h.RemainingArgs()...)
}
return h.NewBindAddresses(lnHosts), nil
}
// parseTLS parses the tls directive. Syntax:
//
// tls [<email>|internal]|[<cert_file> <key_file>] {
// protocols <min> [<max>]
// ciphers <cipher_suites...>
// curves <curves...>
// client_auth {
// mode [request|require|verify_if_given|require_and_verify]
// trusted_ca_cert <base64_der>
// trusted_ca_cert_file <filename>
// trusted_leaf_cert <base64_der>
// trusted_leaf_cert_file <filename>
// }
// alpn <values...>
// load <paths...>
// ca <acme_ca_endpoint>
// ca_root <pem_file>
// dns <provider_name> [...]
// on_demand
// eab <key_id> <mac_key>
// issuer <module_name> [...]
// }
//
func parseTLS(h Helper) ([]ConfigValue, error) {
cp := new(caddytls.ConnectionPolicy)
var fileLoader caddytls.FileLoader
var folderLoader caddytls.FolderLoader
var certSelector caddytls.CustomCertSelectionPolicy
var acmeIssuer *caddytls.ACMEIssuer
var internalIssuer *caddytls.InternalIssuer
var issuers []certmagic.Issuer
var onDemand bool
for h.Next() {
// file certificate loader
firstLine := h.RemainingArgs()
switch len(firstLine) {
case 0:
case 1:
if firstLine[0] == "internal" {
internalIssuer = new(caddytls.InternalIssuer)
} else if !strings.Contains(firstLine[0], "@") {
return nil, h.Err("single argument must either be 'internal' or an email address")
} else {
if acmeIssuer == nil {
acmeIssuer = new(caddytls.ACMEIssuer)
}
acmeIssuer.Email = firstLine[0]
}
case 2:
certFilename := firstLine[0]
keyFilename := firstLine[1]
// tag this certificate so if multiple certs match, specifically
// this one that the user has provided will be used, see #2588:
// https://github.com/caddyserver/caddy/issues/2588 ... but we
// must be careful about how we do this; being careless will
// lead to failed handshakes
//
// we need to remember which cert files we've seen, since we
// must load each cert only once; otherwise, they each get a
// different tag... since a cert loaded twice has the same
// bytes, it will overwrite the first one in the cache, and
// only the last cert (and its tag) will survive, so a any conn
// policy that is looking for any tag but the last one to be
// loaded won't find it, and TLS handshakes will fail (see end)
// of issue #3004)
//
// tlsCertTags maps certificate filenames to their tag.
// This is used to remember which tag is used for each
// certificate files, since we need to avoid loading
// the same certificate files more than once, overwriting
// previous tags
tlsCertTags, ok := h.State["tlsCertTags"].(map[string]string)
if !ok {
tlsCertTags = make(map[string]string)
h.State["tlsCertTags"] = tlsCertTags
}
tag, ok := tlsCertTags[certFilename]
if !ok {
// haven't seen this cert file yet, let's give it a tag
// and add a loader for it
tag = fmt.Sprintf("cert%d", len(tlsCertTags))
fileLoader = append(fileLoader, caddytls.CertKeyFilePair{
Certificate: certFilename,
Key: keyFilename,
Tags: []string{tag},
})
// remember this for next time we see this cert file
tlsCertTags[certFilename] = tag
}
certSelector.AnyTag = append(certSelector.AnyTag, tag)
default:
return nil, h.ArgErr()
}
var hasBlock bool
for nesting := h.Nesting(); h.NextBlock(nesting); {
hasBlock = true
switch h.Val() {
case "protocols":
args := h.RemainingArgs()
if len(args) == 0 {
return nil, h.SyntaxErr("one or two protocols")
}
if len(args) > 0 {
if _, ok := caddytls.SupportedProtocols[args[0]]; !ok {
return nil, h.Errf("Wrong protocol name or protocol not supported: '%s'", args[0])
}
cp.ProtocolMin = args[0]
}
if len(args) > 1 {
if _, ok := caddytls.SupportedProtocols[args[1]]; !ok {
return nil, h.Errf("Wrong protocol name or protocol not supported: '%s'", args[1])
}
cp.ProtocolMax = args[1]
}
case "ciphers":
for h.NextArg() {
if !caddytls.CipherSuiteNameSupported(h.Val()) {
return nil, h.Errf("Wrong cipher suite name or cipher suite not supported: '%s'", h.Val())
}
cp.CipherSuites = append(cp.CipherSuites, h.Val())
}
case "curves":
for h.NextArg() {
if _, ok := caddytls.SupportedCurves[h.Val()]; !ok {
return nil, h.Errf("Wrong curve name or curve not supported: '%s'", h.Val())
}
cp.Curves = append(cp.Curves, h.Val())
}
case "client_auth":
cp.ClientAuthentication = &caddytls.ClientAuthentication{}
for nesting := h.Nesting(); h.NextBlock(nesting); {
subdir := h.Val()
switch subdir {
case "mode":
if !h.Args(&cp.ClientAuthentication.Mode) {
return nil, h.ArgErr()
}
if h.NextArg() {
return nil, h.ArgErr()
}
case "trusted_ca_cert",
"trusted_leaf_cert":
if !h.NextArg() {
return nil, h.ArgErr()
}
if subdir == "trusted_ca_cert" {
cp.ClientAuthentication.TrustedCACerts = append(cp.ClientAuthentication.TrustedCACerts, h.Val())
} else {
cp.ClientAuthentication.TrustedLeafCerts = append(cp.ClientAuthentication.TrustedLeafCerts, h.Val())
}
case "trusted_ca_cert_file",
"trusted_leaf_cert_file":
if !h.NextArg() {
return nil, h.ArgErr()
}
filename := h.Val()
certDataPEM, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
block, _ := pem.Decode(certDataPEM)
if block == nil || block.Type != "CERTIFICATE" {
return nil, h.Errf("no CERTIFICATE pem block found in %s", h.Val())
}
if subdir == "trusted_ca_cert_file" {
cp.ClientAuthentication.TrustedCACerts = append(cp.ClientAuthentication.TrustedCACerts,
base64.StdEncoding.EncodeToString(block.Bytes))
} else {
cp.ClientAuthentication.TrustedLeafCerts = append(cp.ClientAuthentication.TrustedLeafCerts,
base64.StdEncoding.EncodeToString(block.Bytes))
}
default:
return nil, h.Errf("unknown subdirective for client_auth: %s", subdir)
}
}
case "alpn":
args := h.RemainingArgs()
if len(args) == 0 {
return nil, h.ArgErr()
}
cp.ALPN = args
case "load":
folderLoader = append(folderLoader, h.RemainingArgs()...)
case "ca":
arg := h.RemainingArgs()
if len(arg) != 1 {
return nil, h.ArgErr()
}
if acmeIssuer == nil {
acmeIssuer = new(caddytls.ACMEIssuer)
}
acmeIssuer.CA = arg[0]
case "eab":
arg := h.RemainingArgs()
if len(arg) != 2 {
return nil, h.ArgErr()
}
if acmeIssuer == nil {
acmeIssuer = new(caddytls.ACMEIssuer)
}
acmeIssuer.ExternalAccount = &acme.EAB{
KeyID: arg[0],
MACKey: arg[1],
}
case "issuer":
if !h.NextArg() {
return nil, h.ArgErr()
}
modName := h.Val()
mod, err := caddy.GetModule("tls.issuance." + modName)
if err != nil {
return nil, h.Errf("getting issuer module '%s': %v", modName, err)
}
unm, ok := mod.New().(caddyfile.Unmarshaler)
if !ok {
return nil, h.Errf("issuer module '%s' is not a Caddyfile unmarshaler", mod.ID)
}
err = unm.UnmarshalCaddyfile(h.NewFromNextSegment())
if err != nil {
return nil, err
}
issuer, ok := unm.(certmagic.Issuer)
if !ok {
return nil, h.Errf("module %s is not a certmagic.Issuer", mod.ID)
}
issuers = append(issuers, issuer)
case "dns":
if !h.NextArg() {
return nil, h.ArgErr()
}
provName := h.Val()
if acmeIssuer == nil {
acmeIssuer = new(caddytls.ACMEIssuer)
}
if acmeIssuer.Challenges == nil {
acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
}
dnsProvModule, err := caddy.GetModule("dns.providers." + provName)
if err != nil {
return nil, h.Errf("getting DNS provider module named '%s': %v", provName, err)
}
dnsProvModuleInstance := dnsProvModule.New()
if unm, ok := dnsProvModuleInstance.(caddyfile.Unmarshaler); ok {
err = unm.UnmarshalCaddyfile(h.NewFromNextSegment())
if err != nil {
return nil, err
}
}
acmeIssuer.Challenges.DNS.ProviderRaw = caddyconfig.JSONModuleObject(dnsProvModuleInstance, "name", provName, h.warnings)
case "ca_root":
arg := h.RemainingArgs()
if len(arg) != 1 {
return nil, h.ArgErr()
}
if acmeIssuer == nil {
acmeIssuer = new(caddytls.ACMEIssuer)
}
acmeIssuer.TrustedRootsPEMFiles = append(acmeIssuer.TrustedRootsPEMFiles, arg[0])
case "on_demand":
if h.NextArg() {
return nil, h.ArgErr()
}
onDemand = true
default:
return nil, h.Errf("unknown subdirective: %s", h.Val())
}
}
// a naked tls directive is not allowed
if len(firstLine) == 0 && !hasBlock {
return nil, h.ArgErr()
}
}
// begin building the final config values
configVals := []ConfigValue{}
// certificate loaders
if len(fileLoader) > 0 {
configVals = append(configVals, ConfigValue{
Class: "tls.cert_loader",
Value: fileLoader,
})
}
if len(folderLoader) > 0 {
configVals = append(configVals, ConfigValue{
Class: "tls.cert_loader",
Value: folderLoader,
})
}
if len(issuers) > 0 && (acmeIssuer != nil || internalIssuer != nil) {
// some tls subdirectives are shortcuts that implicitly configure issuers, and the
// user can also configure issuers explicitly using the issuer subdirective; the
// logic to support both would likely be complex, or at least unintuitive
return nil, h.Err("cannot mix issuer subdirective (explicit issuers) with other issuer-specific subdirectives (implicit issuers)")
}
for _, issuer := range issuers {
configVals = append(configVals, ConfigValue{
Class: "tls.cert_issuer",
Value: issuer,
})
}
if acmeIssuer != nil {
configVals = append(configVals, ConfigValue{
Class: "tls.cert_issuer",
Value: disambiguateACMEIssuer(acmeIssuer),
})
}
if internalIssuer != nil {
configVals = append(configVals, ConfigValue{
Class: "tls.cert_issuer",
Value: internalIssuer,
})
}
// on-demand TLS
if onDemand {
configVals = append(configVals, ConfigValue{
Class: "tls.on_demand",
Value: true,
})
}
// custom certificate selection
if len(certSelector.AnyTag) > 0 {
cp.CertSelection = &certSelector
}
// connection policy -- always add one, to ensure that TLS
// is enabled, because this directive was used (this is
// needed, for instance, when a site block has a key of
// just ":5000" - i.e. no hostname, and only on-demand TLS
// is enabled)
configVals = append(configVals, ConfigValue{
Class: "tls.connection_policy",
Value: cp,
})
return configVals, nil
}
// parseRoot parses the root directive. Syntax:
//
// root [<matcher>] <path>
//
func parseRoot(h Helper) (caddyhttp.MiddlewareHandler, error) {
var root string
for h.Next() {
if !h.NextArg() {
return nil, h.ArgErr()
}
root = h.Val()
if h.NextArg() {
return nil, h.ArgErr()
}
}
return caddyhttp.VarsMiddleware{"root": root}, nil
}
// parseRedir parses the redir directive. Syntax:
//
// redir [<matcher>] <to> [<code>]
//
func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) {
if !h.Next() {
return nil, h.ArgErr()
}
if !h.NextArg() {
return nil, h.ArgErr()
}
to := h.Val()
var code string
if h.NextArg() {
code = h.Val()
}
if code == "permanent" {
code = "301"
}
if code == "temporary" || code == "" {
code = "302"
}
var body string
if code == "html" {
// Script tag comes first since that will better imitate a redirect in the browser's
// history, but the meta tag is a fallback for most non-JS clients.
const metaRedir = `<!DOCTYPE html>
<html>
<head>
<title>Redirecting...</title>
<script>window.location.replace("%s");</script>
<meta http-equiv="refresh" content="0; URL='%s'">
</head>
<body>Redirecting to <a href="%s">%s</a>...</body>
</html>
`
safeTo := html.EscapeString(to)
body = fmt.Sprintf(metaRedir, safeTo, safeTo, safeTo, safeTo)
}
return caddyhttp.StaticResponse{
StatusCode: caddyhttp.WeakString(code),
Headers: http.Header{"Location": []string{to}},
Body: body,
}, nil
}
// parseRespond parses the respond directive.
func parseRespond(h Helper) (caddyhttp.MiddlewareHandler, error) {
sr := new(caddyhttp.StaticResponse)
err := sr.UnmarshalCaddyfile(h.Dispenser)
if err != nil {
return nil, err
}
return sr, nil
}
// parseRoute parses the route directive.
func parseRoute(h Helper) (caddyhttp.MiddlewareHandler, error) {
sr := new(caddyhttp.Subroute)
allResults, err := parseSegmentAsConfig(h)
if err != nil {
return nil, err
}
for _, result := range allResults {
switch handler := result.Value.(type) {
case caddyhttp.Route:
sr.Routes = append(sr.Routes, handler)
case caddyhttp.Subroute:
// directives which return a literal subroute instead of a route
// means they intend to keep those handlers together without
// them being reordered; we're doing that anyway since we're in
// the route directive, so just append its handlers
sr.Routes = append(sr.Routes, handler.Routes...)
default:
return nil, h.Errf("%s directive returned something other than an HTTP route or subroute: %#v (only handler directives can be used in routes)", result.directive, result.Value)
}
}
return sr, nil
}
func parseHandle(h Helper) (caddyhttp.MiddlewareHandler, error) {
return ParseSegmentAsSubroute(h)
}
func parseHandleErrors(h Helper) ([]ConfigValue, error) {
subroute, err := ParseSegmentAsSubroute(h)
if err != nil {
return nil, err
}
return []ConfigValue{
{
Class: "error_route",
Value: subroute,
},
}, nil
}
// parseLog parses the log directive. Syntax:
//
// log {
// output <writer_module> ...
// format <encoder_module> ...
// level <level>
// }
//
func parseLog(h Helper) ([]ConfigValue, error) {
var configValues []ConfigValue
for h.Next() {
// log does not currently support any arguments
if h.NextArg() {
return nil, h.ArgErr()
}
cl := new(caddy.CustomLog)
for h.NextBlock(0) {
switch h.Val() {
case "output":
if !h.NextArg() {
return nil, h.ArgErr()
}
moduleName := h.Val()
// can't use the usual caddyfile.Unmarshaler flow with the
// standard writers because they are in the caddy package
// (because they are the default) and implementing that
// interface there would unfortunately create circular import
var wo caddy.WriterOpener
switch moduleName {
case "stdout":
wo = caddy.StdoutWriter{}
case "stderr":
wo = caddy.StderrWriter{}
case "discard":
wo = caddy.DiscardWriter{}
default:
mod, err := caddy.GetModule("caddy.logging.writers." + moduleName)
if err != nil {
return nil, h.Errf("getting log writer module named '%s': %v", moduleName, err)
}
unm, ok := mod.New().(caddyfile.Unmarshaler)
if !ok {
return nil, h.Errf("log writer module '%s' is not a Caddyfile unmarshaler", mod)
}
err = unm.UnmarshalCaddyfile(h.NewFromNextSegment())
if err != nil {
return nil, err
}
wo, ok = unm.(caddy.WriterOpener)
if !ok {
return nil, h.Errf("module %s is not a WriterOpener", mod)
}
}
cl.WriterRaw = caddyconfig.JSONModuleObject(wo, "output", moduleName, h.warnings)
case "format":
if !h.NextArg() {
return nil, h.ArgErr()
}
moduleName := h.Val()
mod, err := caddy.GetModule("caddy.logging.encoders." + moduleName)
if err != nil {
return nil, h.Errf("getting log encoder module named '%s': %v", moduleName, err)
}
unm, ok := mod.New().(caddyfile.Unmarshaler)
if !ok {
return nil, h.Errf("log encoder module '%s' is not a Caddyfile unmarshaler", mod)
}
err = unm.UnmarshalCaddyfile(h.NewFromNextSegment())
if err != nil {
return nil, err
}
enc, ok := unm.(zapcore.Encoder)
if !ok {
return nil, h.Errf("module %s is not a zapcore.Encoder", mod)
}
cl.EncoderRaw = caddyconfig.JSONModuleObject(enc, "format", moduleName, h.warnings)
case "level":
if !h.NextArg() {
return nil, h.ArgErr()
}
cl.Level = h.Val()
if h.NextArg() {
return nil, h.ArgErr()
}
default:
return nil, h.Errf("unrecognized subdirective: %s", h.Val())
}
}
var val namedCustomLog
if !reflect.DeepEqual(cl, new(caddy.CustomLog)) {
logCounter, ok := h.State["logCounter"].(int)
if !ok {
logCounter = 0
}
val.name = fmt.Sprintf("log%d", logCounter)
cl.Include = []string{"http.log.access." + val.name}
val.log = cl
logCounter++
h.State["logCounter"] = logCounter
}
configValues = append(configValues, ConfigValue{
Class: "custom_log",
Value: val,
})
}
return configValues, nil
}
| 1 | 16,081 | The only field being used is the KeyType; Instead, we can probably just make a `keyType` variable here. | caddyserver-caddy | go |
@@ -36,8 +36,11 @@ var SwaggerPetstore = ( /** @lends SwaggerPetstore */ function() {
* {@link https://github.com/request/request#requestoptions-callback Options doc}
*/
function SwaggerPetstore(baseUri, options) {
- SwaggerPetstore['super_'].call(this, options);
-
+ if (!options) {
+ options = {};
+ }
+ SwaggerPetstore['super_'].call(this, options.credentials, options);
+
this.baseUri = baseUri;
if (this.baseUri === null || this.baseUri === undefined) {
this.baseUri = 'http://localhost:12510/api'; | 1 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
'use strict';
var util = require('util');
var azureCommon = require('../../lib/msRest');
var ServiceClient = azureCommon.ServiceClient;
var HttpOperationResponse = azureCommon.HttpOperationResponse;
var WebResource = azureCommon.WebResource;
var Pet = require('./models/Pet');
var SwaggerPetstore = ( /** @lends SwaggerPetstore */ function() {
/**
* @class
* Initializes a new instance of the SwaggerPetstore class.
* @constructor
*
* @param {string} [baseUri] The base URI of the service.
*
* @param {object} options The parameter options
*
* @param {object} [options.credentials] - BasicAuthenticationCredentials or
* TokenCredentials object used for authentication.
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
*/
function SwaggerPetstore(baseUri, options) {
SwaggerPetstore['super_'].call(this, options);
this.baseUri = baseUri;
if (this.baseUri === null || this.baseUri === undefined) {
this.baseUri = 'http://localhost:12510/api';
}
}
util.inherits(SwaggerPetstore, ServiceClient);
/**
* Returns a pet.
*
* @param {Number} id ID of pet to fetch
*
* @param {function} callback
*
* @returns {Stream} The response stream.
*/
SwaggerPetstore.prototype.findPetById = function(id, callback) {
this.findPetByIdWithOperationResponse(id, function (error, resultWithEnvelope) {
return callback(null, resultWithEnvelope.body);
});
};
/**
* Returns a pet.
*
* @param {Number} id ID of pet to fetch
*
* @param {function} callback
*
* @returns {Stream} The response stream.
*/
SwaggerPetstore.prototype.findPetByIdWithOperationResponse = function(id, callback) {
if (callback === null || callback === undefined) {
throw new Error('callback cannot be null.');
}
// Validate
if (id === null || id === undefined) {
return callback(new Error('id cannot be null.'));
}
// Tracing
// Construct URL
var url2 = '';
url2 = url2 + '/pets/';
url2 = url2 + encodeURIComponent(id.toString());
var baseUrl = this.baseUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.length - 1] === '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length - 1) + 0);
}
if (url2[0] === '/') {
url2 = url2.substring(1);
}
url2 = baseUrl + '/' + url2;
url2 = url2.replace(' ', '%20');
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.headers = {};
httpRequest.url = url2;
// Send Request
return this.pipeline(httpRequest, function (err, response, body) {
if (err !== null && err !== undefined) {
return callback(err);
}
var statusCode = response.statusCode;
var responseContent = body;
if (statusCode !== 200) {
var errorModel = {};
var responseDoc = null;
if (responseContent) {
responseDoc = JSON.parse(responseContent);
}
if (responseDoc !== null) {
errorModel.deserializeJsonSync(responseDoc);
}
var error = new Error(responseContent);
error.statusCode = response.statusCode;
return callback(error);
}
// Create Result
var result = new HttpOperationResponse(httpRequest, response);
// Deserialize Response
if (statusCode === 200) {
var resultModel = new Pet();
var responseDoc = null;
if (responseContent) {
responseDoc = JSON.parse(responseContent);
}
if (responseDoc !== null) {
result.body = resultModel.deserializeJsonSync(responseDoc);
}
}
return callback(null, result);
});
};
return SwaggerPetstore;
})();
exports.SwaggerPetstore = SwaggerPetstore;
| 1 | 20,707 | This should be done by code-gen change happening in the hydra repo. I am tweaking it just to get CI into a 'passing' state | Azure-autorest | java |
@@ -23,13 +23,15 @@ import { createTestRegistry } from './utils';
* Renders the given UI into a container to make assertions.
*
* @since 1.7.1
+ * @since 1.25.0 Added `features` option.
* @see {@link https://testing-library.com/docs/react-testing-library/api#render}
* @private
*
- * @param {*} ui Any valid React child element.
- * @param {Object} options Render options.
- * @param {Function} options.setupRegistry A function which accepts the registry instance to configure it.
- * @param {Function} options.registry A specific registry instance to use. Defaults to a fresh test registry with all stores.
+ * @param {*} ui Any valid React child element.
+ * @param {Object} [options] Optional. Render options.
+ * @param {string[]} [options.features] Feature flags to enable for this hook render.
+ * @param {Function} [options.setupRegistry] A function which accepts the registry instance to configure it.
+ * @param {Object} [options.registry] A specific registry instance to use. Defaults to a fresh test registry with all stores.
* @return {Object} An object containing all of {@link https://testing-library.com/docs/react-testing-library/api#render-result} as well as the `registry`.
*/
const customRender = ( ui, options = {} ) => { | 1 | /**
* External dependencies
*/
import { render } from '@testing-library/react';
import { renderHook, act as actHook } from '@testing-library/react-hooks';
import invariant from 'invariant';
/**
* WordPress dependencies
*/
import { RegistryProvider } from '@wordpress/data';
/**
* Internal dependencies
*/
import FeaturesProvider from '../../assets/js/components/FeaturesProvider';
import { createTestRegistry } from './utils';
// Override `@testing-library/react`'s render method with one that includes
// our data store.
/**
* Renders the given UI into a container to make assertions.
*
* @since 1.7.1
* @see {@link https://testing-library.com/docs/react-testing-library/api#render}
* @private
*
* @param {*} ui Any valid React child element.
* @param {Object} options Render options.
* @param {Function} options.setupRegistry A function which accepts the registry instance to configure it.
* @param {Function} options.registry A specific registry instance to use. Defaults to a fresh test registry with all stores.
* @return {Object} An object containing all of {@link https://testing-library.com/docs/react-testing-library/api#render-result} as well as the `registry`.
*/
const customRender = ( ui, options = {} ) => {
const {
features = [],
setupRegistry = ( r ) => r,
registry = createTestRegistry(),
...renderOptions
} = options;
invariant( typeof setupRegistry === 'function', 'options.setupRegistry must be a function.' );
setupRegistry( registry );
function Wrapper( { children } ) {
return (
<RegistryProvider value={ registry }>
<FeaturesProvider value={ features }>
{ children }
</FeaturesProvider>
</RegistryProvider>
);
}
const result = render( ui, { wrapper: Wrapper, ...renderOptions } );
const {
getByTestId: getByTestID, // eslint-disable-line sitekit/acronym-case
findByTestId: findByTestID, // eslint-disable-line sitekit/acronym-case
getAllByTestId: getAllByTestID, // eslint-disable-line sitekit/acronym-case
findAllByTestId: findAllByTestID, // eslint-disable-line sitekit/acronym-case
queryByTestId: queryByTestID, // eslint-disable-line sitekit/acronym-case
queryAllByTestId: queryAllByTestID, // eslint-disable-line sitekit/acronym-case
} = result;
return {
...result,
findAllByTestID,
findByTestID,
getAllByTestID,
getByTestID,
queryAllByTestID,
queryByTestID,
registry,
};
};
/**
* Renders a test component that will call the provided callback, including any hooks it calls, every time it renders.
*
* @since 1.12.0
* @since 1.25.0 Added `features` option.
* @private
*
* @param {Function} callback The function that is called each render of the test component. This function should call one or more hooks for testing. The props passed into the callback will be the initialProps provided in the options to renderHook, unless new props are provided by a subsequent rerender call.
* @param {Object} [options] Optional. An options object to modify the execution of the callback function. See the [renderHook Options](@link https://react-hooks-testing-library.com/reference/api#renderhook-options) section for more details.
* @param {string[]} [options.features] Feature flags to enable for this hook render.
* @param {Object} [options.registry] Registry to use with the RegistryProvider. Default is a new test registry.
* @return {Object} Object with `result`, `rerender`, `unmount`, and async utilities. @link https://react-hooks-testing-library.com/reference/api#renderhook-result.
*/
const customRenderHook = (
callback,
{
features = [],
registry = createTestRegistry(),
...renderHookOptions
} = {}
) => {
const Wrapper = ( { children } ) => (
<RegistryProvider value={ registry }>
<FeaturesProvider value={ features }>
{ children }
</FeaturesProvider>
</RegistryProvider>
);
return {
...renderHook( callback, { wrapper: Wrapper, ...renderHookOptions } ),
registry,
};
};
// Export our own test utils from this file.
export * from 'tests/js/utils';
// Export @testing-library/react as normal.
export * from '@testing-library/react';
// Override @testing-library/react's render method with our own.
export { customRender as render };
// Override @testing-library/react-hooks's renderHook method with our own.
export { customRenderHook as renderHook };
// Hooks need to use the `act` from @testing-library/react-hooks.
export { actHook };
| 1 | 36,611 | Cleaned up when I originally added support for passing `screenContext` here (and later `viewContext`) but that was removed. | google-site-kit-wp | js |
@@ -251,14 +251,14 @@ std::string CPlusPlusLanguage::MethodName::GetScopeQualifiedName() {
bool CPlusPlusLanguage::IsCPPMangledName(const char *name) {
// FIXME!! we should really run through all the known C++ Language plugins
// and ask each one if this is a C++ mangled name
-
+
if (name == nullptr)
return false;
-
- // MSVC style mangling
+
+ // MSVC style mangling
if (name[0] == '?')
return true;
-
+
return (name[0] != '\0' && name[0] == '_' && name[1] == 'Z');
}
| 1 | //===-- CPlusPlusLanguage.cpp -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CPlusPlusLanguage.h"
// C Includes
#include <cctype>
#include <cstring>
// C++ Includes
#include <functional>
#include <memory>
#include <mutex>
#include <set>
// Other libraries and framework includes
#include "llvm/ADT/StringRef.h"
#include "llvm/Demangle/Demangle.h"
// Project includes
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/UniqueCStringMap.h"
#include "lldb/DataFormatters/CXXFunctionPointer.h"
#include "lldb/DataFormatters/DataVisualization.h"
#include "lldb/DataFormatters/FormattersHelpers.h"
#include "lldb/DataFormatters/VectorType.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/RegularExpression.h"
#include "BlockPointer.h"
#include "CPlusPlusNameParser.h"
#include "CxxStringTypes.h"
#include "LibCxx.h"
#include "LibCxxAtomic.h"
#include "LibStdcpp.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::formatters;
void CPlusPlusLanguage::Initialize() {
PluginManager::RegisterPlugin(GetPluginNameStatic(), "C++ Language",
CreateInstance);
}
void CPlusPlusLanguage::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
lldb_private::ConstString CPlusPlusLanguage::GetPluginNameStatic() {
static ConstString g_name("cplusplus");
return g_name;
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
lldb_private::ConstString CPlusPlusLanguage::GetPluginName() {
return GetPluginNameStatic();
}
uint32_t CPlusPlusLanguage::GetPluginVersion() { return 1; }
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
Language *CPlusPlusLanguage::CreateInstance(lldb::LanguageType language) {
if (Language::LanguageIsCPlusPlus(language))
return new CPlusPlusLanguage();
return nullptr;
}
void CPlusPlusLanguage::MethodName::Clear() {
m_full.Clear();
m_basename = llvm::StringRef();
m_context = llvm::StringRef();
m_arguments = llvm::StringRef();
m_qualifiers = llvm::StringRef();
m_parsed = false;
m_parse_error = false;
}
static bool ReverseFindMatchingChars(const llvm::StringRef &s,
const llvm::StringRef &left_right_chars,
size_t &left_pos, size_t &right_pos,
size_t pos = llvm::StringRef::npos) {
assert(left_right_chars.size() == 2);
left_pos = llvm::StringRef::npos;
const char left_char = left_right_chars[0];
const char right_char = left_right_chars[1];
pos = s.find_last_of(left_right_chars, pos);
if (pos == llvm::StringRef::npos || s[pos] == left_char)
return false;
right_pos = pos;
uint32_t depth = 1;
while (pos > 0 && depth > 0) {
pos = s.find_last_of(left_right_chars, pos);
if (pos == llvm::StringRef::npos)
return false;
if (s[pos] == left_char) {
if (--depth == 0) {
left_pos = pos;
return left_pos < right_pos;
}
} else if (s[pos] == right_char) {
++depth;
}
}
return false;
}
static bool IsTrivialBasename(const llvm::StringRef &basename) {
// Check that the basename matches with the following regular expression
// "^~?([A-Za-z_][A-Za-z_0-9]*)$" We are using a hand written implementation
// because it is significantly more efficient then using the general purpose
// regular expression library.
size_t idx = 0;
if (basename.size() > 0 && basename[0] == '~')
idx = 1;
if (basename.size() <= idx)
return false; // Empty string or "~"
if (!std::isalpha(basename[idx]) && basename[idx] != '_')
return false; // First charater (after removing the possible '~'') isn't in
// [A-Za-z_]
// Read all characters matching [A-Za-z_0-9]
++idx;
while (idx < basename.size()) {
if (!std::isalnum(basename[idx]) && basename[idx] != '_')
break;
++idx;
}
// We processed all characters. It is a vaild basename.
if (idx == basename.size())
return true;
return false;
}
bool CPlusPlusLanguage::MethodName::TrySimplifiedParse() {
// This method tries to parse simple method definitions which are presumably
// most comman in user programs. Definitions that can be parsed by this
// function don't have return types and templates in the name.
// A::B::C::fun(std::vector<T> &) const
size_t arg_start, arg_end;
llvm::StringRef full(m_full.GetCString());
llvm::StringRef parens("()", 2);
if (ReverseFindMatchingChars(full, parens, arg_start, arg_end)) {
m_arguments = full.substr(arg_start, arg_end - arg_start + 1);
if (arg_end + 1 < full.size())
m_qualifiers = full.substr(arg_end + 1).ltrim();
if (arg_start == 0)
return false;
size_t basename_end = arg_start;
size_t context_start = 0;
size_t context_end = full.rfind(':', basename_end);
if (context_end == llvm::StringRef::npos)
m_basename = full.substr(0, basename_end);
else {
if (context_start < context_end)
m_context = full.substr(context_start, context_end - 1 - context_start);
const size_t basename_begin = context_end + 1;
m_basename = full.substr(basename_begin, basename_end - basename_begin);
}
if (IsTrivialBasename(m_basename)) {
return true;
} else {
// The C++ basename doesn't match our regular expressions so this can't
// be a valid C++ method, clear everything out and indicate an error
m_context = llvm::StringRef();
m_basename = llvm::StringRef();
m_arguments = llvm::StringRef();
m_qualifiers = llvm::StringRef();
return false;
}
}
return false;
}
void CPlusPlusLanguage::MethodName::Parse() {
if (!m_parsed && m_full) {
if (TrySimplifiedParse()) {
m_parse_error = false;
} else {
CPlusPlusNameParser parser(m_full.GetStringRef());
if (auto function = parser.ParseAsFunctionDefinition()) {
m_basename = function.getValue().name.basename;
m_context = function.getValue().name.context;
m_arguments = function.getValue().arguments;
m_qualifiers = function.getValue().qualifiers;
m_parse_error = false;
} else {
m_parse_error = true;
}
}
m_parsed = true;
}
}
llvm::StringRef CPlusPlusLanguage::MethodName::GetBasename() {
if (!m_parsed)
Parse();
return m_basename;
}
llvm::StringRef CPlusPlusLanguage::MethodName::GetContext() {
if (!m_parsed)
Parse();
return m_context;
}
llvm::StringRef CPlusPlusLanguage::MethodName::GetArguments() {
if (!m_parsed)
Parse();
return m_arguments;
}
llvm::StringRef CPlusPlusLanguage::MethodName::GetQualifiers() {
if (!m_parsed)
Parse();
return m_qualifiers;
}
std::string CPlusPlusLanguage::MethodName::GetScopeQualifiedName() {
if (!m_parsed)
Parse();
if (m_context.empty())
return m_basename;
std::string res;
res += m_context;
res += "::";
res += m_basename;
return res;
}
bool CPlusPlusLanguage::IsCPPMangledName(const char *name) {
// FIXME!! we should really run through all the known C++ Language plugins
// and ask each one if this is a C++ mangled name
if (name == nullptr)
return false;
// MSVC style mangling
if (name[0] == '?')
return true;
return (name[0] != '\0' && name[0] == '_' && name[1] == 'Z');
}
bool CPlusPlusLanguage::ExtractContextAndIdentifier(
const char *name, llvm::StringRef &context, llvm::StringRef &identifier) {
CPlusPlusNameParser parser(name);
if (auto full_name = parser.ParseAsFullName()) {
identifier = full_name.getValue().basename;
context = full_name.getValue().context;
return true;
}
return false;
}
/// Given a mangled function `mangled`, replace all the primitive function type
/// arguments of `search` with type `replace`.
static ConstString SubsPrimitiveParmItanium(llvm::StringRef mangled,
llvm::StringRef search,
llvm::StringRef replace) {
class PrimitiveParmSubs {
llvm::StringRef mangled;
llvm::StringRef search;
llvm::StringRef replace;
ptrdiff_t read_pos;
std::string output;
std::back_insert_iterator<std::string> writer;
public:
PrimitiveParmSubs(llvm::StringRef m, llvm::StringRef s, llvm::StringRef r)
: mangled(m), search(s), replace(r), read_pos(0),
writer(std::back_inserter(output)) {}
void Substitute(llvm::StringRef tail) {
assert(tail.data() >= mangled.data() &&
tail.data() < mangled.data() + mangled.size() &&
"tail must point into range of mangled");
if (tail.startswith(search)) {
auto reader = mangled.begin() + read_pos;
ptrdiff_t read_len = tail.data() - (mangled.data() + read_pos);
// First write the unmatched part of the original. Then write the
// replacement string. Finally skip the search string in the original.
writer = std::copy(reader, reader + read_len, writer);
writer = std::copy(replace.begin(), replace.end(), writer);
read_pos += read_len + search.size();
}
}
ConstString Finalize() {
// If we did a substitution, write the remaining part of the original.
if (read_pos > 0) {
writer = std::copy(mangled.begin() + read_pos, mangled.end(), writer);
read_pos = mangled.size();
}
return ConstString(output);
}
static void Callback(void *context, const char *match) {
((PrimitiveParmSubs *)context)->Substitute(llvm::StringRef(match));
}
};
// The demangler will call back for each instance of a primitive type,
// allowing us to perform substitution
PrimitiveParmSubs parmSubs(mangled, search, replace);
assert(mangled.data()[mangled.size()] == '\0' && "Expect C-String");
bool err = llvm::itaniumFindTypesInMangledName(mangled.data(), &parmSubs,
PrimitiveParmSubs::Callback);
ConstString result = parmSubs.Finalize();
if (Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)) {
if (err)
LLDB_LOG(log, "Failed to substitute mangling in {0}", mangled);
else if (result)
LLDB_LOG(log, "Substituted mangling {0} -> {1}", mangled, result);
}
return result;
}
uint32_t CPlusPlusLanguage::FindAlternateFunctionManglings(
const ConstString mangled_name, std::set<ConstString> &alternates) {
const auto start_size = alternates.size();
/// Get a basic set of alternative manglings for the given symbol `name`, by
/// making a few basic possible substitutions on basic types, storage duration
/// and `const`ness for the given symbol. The output parameter `alternates`
/// is filled with a best-guess, non-exhaustive set of different manglings
/// for the given name.
// Maybe we're looking for a const symbol but the debug info told us it was
// non-const...
if (!strncmp(mangled_name.GetCString(), "_ZN", 3) &&
strncmp(mangled_name.GetCString(), "_ZNK", 4)) {
std::string fixed_scratch("_ZNK");
fixed_scratch.append(mangled_name.GetCString() + 3);
alternates.insert(ConstString(fixed_scratch));
}
// Maybe we're looking for a static symbol but we thought it was global...
if (!strncmp(mangled_name.GetCString(), "_Z", 2) &&
strncmp(mangled_name.GetCString(), "_ZL", 3)) {
std::string fixed_scratch("_ZL");
fixed_scratch.append(mangled_name.GetCString() + 2);
alternates.insert(ConstString(fixed_scratch));
}
// `char` is implementation defined as either `signed` or `unsigned`. As a
// result a char parameter has 3 possible manglings: 'c'-char, 'a'-signed
// char, 'h'-unsigned char. If we're looking for symbols with a signed char
// parameter, try finding matches which have the general case 'c'.
if (ConstString char_fixup =
SubsPrimitiveParmItanium(mangled_name.GetStringRef(), "a", "c"))
alternates.insert(char_fixup);
// long long parameter mangling 'x', may actually just be a long 'l' argument
if (ConstString long_fixup =
SubsPrimitiveParmItanium(mangled_name.GetStringRef(), "x", "l"))
alternates.insert(long_fixup);
// unsigned long long parameter mangling 'y', may actually just be unsigned
// long 'm' argument
if (ConstString ulong_fixup =
SubsPrimitiveParmItanium(mangled_name.GetStringRef(), "y", "m"))
alternates.insert(ulong_fixup);
return alternates.size() - start_size;
}
static void LoadLibCxxFormatters(lldb::TypeCategoryImplSP cpp_category_sp) {
if (!cpp_category_sp)
return;
TypeSummaryImpl::Flags stl_summary_flags;
stl_summary_flags.SetCascades(true)
.SetSkipPointers(false)
.SetSkipReferences(false)
.SetDontShowChildren(true)
.SetDontShowValue(true)
.SetShowMembersOneLiner(false)
.SetHideItemNames(false);
#ifndef LLDB_DISABLE_PYTHON
lldb::TypeSummaryImplSP std_string_summary_sp(new CXXFunctionSummaryFormat(
stl_summary_flags, lldb_private::formatters::LibcxxStringSummaryProvider,
"std::string summary provider"));
lldb::TypeSummaryImplSP std_wstring_summary_sp(new CXXFunctionSummaryFormat(
stl_summary_flags, lldb_private::formatters::LibcxxWStringSummaryProvider,
"std::wstring summary provider"));
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__1::string"), std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__ndk1::string"), std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__1::basic_string<char, std::__1::char_traits<char>, "
"std::__1::allocator<char> >"),
std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__ndk1::basic_string<char, "
"std::__ndk1::char_traits<char>, "
"std::__ndk1::allocator<char> >"),
std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__1::wstring"), std_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__ndk1::wstring"), std_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__1::basic_string<wchar_t, "
"std::__1::char_traits<wchar_t>, "
"std::__1::allocator<wchar_t> >"),
std_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__ndk1::basic_string<wchar_t, "
"std::__ndk1::char_traits<wchar_t>, "
"std::__ndk1::allocator<wchar_t> >"),
std_wstring_summary_sp);
SyntheticChildren::Flags stl_synth_flags;
stl_synth_flags.SetCascades(true).SetSkipPointers(false).SetSkipReferences(
false);
SyntheticChildren::Flags stl_deref_flags = stl_synth_flags;
stl_deref_flags.SetFrontEndWantsDereference();
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxBitsetSyntheticFrontEndCreator,
"libc++ std::bitset synthetic children",
ConstString("^std::__(ndk)?1::bitset<.+>(( )?&)?$"), stl_deref_flags,
true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdVectorSyntheticFrontEndCreator,
"libc++ std::vector synthetic children",
ConstString("^std::__(ndk)?1::vector<.+>(( )?&)?$"), stl_deref_flags,
true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdForwardListSyntheticFrontEndCreator,
"libc++ std::forward_list synthetic children",
ConstString("^std::__(ndk)?1::forward_list<.+>(( )?&)?$"),
stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdListSyntheticFrontEndCreator,
"libc++ std::list synthetic children",
ConstString("^std::__(ndk)?1::list<.+>(( )?&)?$"), stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator,
"libc++ std::map synthetic children",
ConstString("^std::__(ndk)?1::map<.+> >(( )?&)?$"), stl_synth_flags,
true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator,
"libc++ std::set synthetic children",
ConstString("^std::__(ndk)?1::set<.+> >(( )?&)?$"), stl_deref_flags,
true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator,
"libc++ std::multiset synthetic children",
ConstString("^std::__(ndk)?1::multiset<.+> >(( )?&)?$"), stl_deref_flags,
true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator,
"libc++ std::multimap synthetic children",
ConstString("^std::__(ndk)?1::multimap<.+> >(( )?&)?$"), stl_synth_flags,
true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxStdUnorderedMapSyntheticFrontEndCreator,
"libc++ std::unordered containers synthetic children",
ConstString("^(std::__(ndk)?1::)unordered_(multi)?(map|set)<.+> >$"),
stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxInitializerListSyntheticFrontEndCreator,
"libc++ std::initializer_list synthetic children",
ConstString("^std::initializer_list<.+>(( )?&)?$"), stl_synth_flags,
true);
AddCXXSynthetic(cpp_category_sp, LibcxxQueueFrontEndCreator,
"libc++ std::queue synthetic children",
ConstString("^std::__(ndk)?1::queue<.+>(( )?&)?$"),
stl_synth_flags, true);
AddCXXSynthetic(cpp_category_sp, LibcxxTupleFrontEndCreator,
"libc++ std::tuple synthetic children",
ConstString("^std::__(ndk)?1::tuple<.*>(( )?&)?$"), stl_synth_flags,
true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxAtomicSyntheticFrontEndCreator,
"libc++ std::atomic synthetic children",
ConstString("^std::__(ndk)?1::atomic<.+>$"), stl_synth_flags, true);
cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add(
RegularExpressionSP(new RegularExpression(
llvm::StringRef("^(std::__(ndk)?1::)deque<.+>(( )?&)?$"))),
SyntheticChildrenSP(new ScriptedSyntheticChildren(
stl_synth_flags,
"lldb.formatters.cpp.libcxx.stddeque_SynthProvider")));
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxSharedPtrSyntheticFrontEndCreator,
"shared_ptr synthetic children",
ConstString("^(std::__(ndk)?1::)shared_ptr<.+>(( )?&)?$"),
stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibcxxSharedPtrSyntheticFrontEndCreator,
"weak_ptr synthetic children",
ConstString("^(std::__(ndk)?1::)weak_ptr<.+>(( )?&)?$"), stl_synth_flags,
true);
stl_summary_flags.SetDontShowChildren(false);
stl_summary_flags.SetSkipPointers(false);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::bitset summary provider",
ConstString("^std::__(ndk)?1::bitset<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::vector summary provider",
ConstString("^std::__(ndk)?1::vector<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::list summary provider",
ConstString("^std::__(ndk)?1::forward_list<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::list summary provider",
ConstString("^std::__(ndk)?1::list<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::map summary provider",
ConstString("^std::__(ndk)?1::map<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::deque summary provider",
ConstString("^std::__(ndk)?1::deque<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::queue summary provider",
ConstString("^std::__(ndk)?1::queue<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::set summary provider",
ConstString("^std::__(ndk)?1::set<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::multiset summary provider",
ConstString("^std::__(ndk)?1::multiset<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::multimap summary provider",
ConstString("^std::__(ndk)?1::multimap<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::LibcxxContainerSummaryProvider,
"libc++ std::unordered containers summary provider",
ConstString("^(std::__(ndk)?1::)unordered_(multi)?(map|set)<.+> >$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp, LibcxxContainerSummaryProvider,
"libc++ std::tuple summary provider",
ConstString("^std::__(ndk)?1::tuple<.*>(( )?&)?$"), stl_summary_flags,
true);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::LibCxxAtomicSummaryProvider,
"libc++ std::atomic summary provider",
ConstString("^std::__(ndk)?1::atomic<.+>$"), stl_summary_flags, true);
stl_summary_flags.SetSkipPointers(true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxSmartPointerSummaryProvider,
"libc++ std::shared_ptr summary provider",
ConstString("^std::__(ndk)?1::shared_ptr<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibcxxSmartPointerSummaryProvider,
"libc++ std::weak_ptr summary provider",
ConstString("^std::__(ndk)?1::weak_ptr<.+>(( )?&)?$"),
stl_summary_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibCxxVectorIteratorSyntheticFrontEndCreator,
"std::vector iterator synthetic children",
ConstString("^std::__(ndk)?1::__wrap_iter<.+>$"), stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibCxxMapIteratorSyntheticFrontEndCreator,
"std::map iterator synthetic children",
ConstString("^std::__(ndk)?1::__map_iterator<.+>$"), stl_synth_flags,
true);
AddCXXSynthetic(
cpp_category_sp, lldb_private::formatters::LibcxxFunctionFrontEndCreator,
"std::function synthetic value provider",
ConstString("^std::__(ndk)?1::function<.+>$"), stl_synth_flags, true);
#endif
}
static void LoadLibStdcppFormatters(lldb::TypeCategoryImplSP cpp_category_sp) {
if (!cpp_category_sp)
return;
TypeSummaryImpl::Flags stl_summary_flags;
stl_summary_flags.SetCascades(true)
.SetSkipPointers(false)
.SetSkipReferences(false)
.SetDontShowChildren(true)
.SetDontShowValue(true)
.SetShowMembersOneLiner(false)
.SetHideItemNames(false);
lldb::TypeSummaryImplSP std_string_summary_sp(
new StringSummaryFormat(stl_summary_flags, "${var._M_dataplus._M_p}"));
lldb::TypeSummaryImplSP cxx11_string_summary_sp(new CXXFunctionSummaryFormat(
stl_summary_flags, LibStdcppStringSummaryProvider,
"libstdc++ c++11 std::string summary provider"));
lldb::TypeSummaryImplSP cxx11_wstring_summary_sp(new CXXFunctionSummaryFormat(
stl_summary_flags, LibStdcppWStringSummaryProvider,
"libstdc++ c++11 std::wstring summary provider"));
cpp_category_sp->GetTypeSummariesContainer()->Add(ConstString("std::string"),
std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::basic_string<char>"), std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::basic_string<char,std::char_traits<char>,std::"
"allocator<char> >"),
std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::basic_string<char, std::char_traits<char>, "
"std::allocator<char> >"),
std_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__cxx11::string"), cxx11_string_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__cxx11::basic_string<char, std::char_traits<char>, "
"std::allocator<char> >"),
cxx11_string_summary_sp);
// making sure we force-pick the summary for printing wstring (_M_p is a
// wchar_t*)
lldb::TypeSummaryImplSP std_wstring_summary_sp(
new StringSummaryFormat(stl_summary_flags, "${var._M_dataplus._M_p%S}"));
cpp_category_sp->GetTypeSummariesContainer()->Add(ConstString("std::wstring"),
std_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::basic_string<wchar_t>"), std_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::basic_string<wchar_t,std::char_traits<wchar_t>,std::"
"allocator<wchar_t> >"),
std_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::basic_string<wchar_t, std::char_traits<wchar_t>, "
"std::allocator<wchar_t> >"),
std_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__cxx11::wstring"), cxx11_wstring_summary_sp);
cpp_category_sp->GetTypeSummariesContainer()->Add(
ConstString("std::__cxx11::basic_string<wchar_t, "
"std::char_traits<wchar_t>, std::allocator<wchar_t> >"),
cxx11_wstring_summary_sp);
#ifndef LLDB_DISABLE_PYTHON
SyntheticChildren::Flags stl_synth_flags;
stl_synth_flags.SetCascades(true).SetSkipPointers(false).SetSkipReferences(
false);
cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add(
RegularExpressionSP(
new RegularExpression(llvm::StringRef("^std::vector<.+>(( )?&)?$"))),
SyntheticChildrenSP(new ScriptedSyntheticChildren(
stl_synth_flags,
"lldb.formatters.cpp.gnu_libstdcpp.StdVectorSynthProvider")));
cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add(
RegularExpressionSP(
new RegularExpression(llvm::StringRef("^std::map<.+> >(( )?&)?$"))),
SyntheticChildrenSP(new ScriptedSyntheticChildren(
stl_synth_flags,
"lldb.formatters.cpp.gnu_libstdcpp.StdMapSynthProvider")));
cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add(
RegularExpressionSP(new RegularExpression(
llvm::StringRef("^std::(__cxx11::)?list<.+>(( )?&)?$"))),
SyntheticChildrenSP(new ScriptedSyntheticChildren(
stl_synth_flags,
"lldb.formatters.cpp.gnu_libstdcpp.StdListSynthProvider")));
stl_summary_flags.SetDontShowChildren(false);
stl_summary_flags.SetSkipPointers(true);
cpp_category_sp->GetRegexTypeSummariesContainer()->Add(
RegularExpressionSP(
new RegularExpression(llvm::StringRef("^std::vector<.+>(( )?&)?$"))),
TypeSummaryImplSP(
new StringSummaryFormat(stl_summary_flags, "size=${svar%#}")));
cpp_category_sp->GetRegexTypeSummariesContainer()->Add(
RegularExpressionSP(
new RegularExpression(llvm::StringRef("^std::map<.+> >(( )?&)?$"))),
TypeSummaryImplSP(
new StringSummaryFormat(stl_summary_flags, "size=${svar%#}")));
cpp_category_sp->GetRegexTypeSummariesContainer()->Add(
RegularExpressionSP(new RegularExpression(
llvm::StringRef("^std::(__cxx11::)?list<.+>(( )?&)?$"))),
TypeSummaryImplSP(
new StringSummaryFormat(stl_summary_flags, "size=${svar%#}")));
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibStdcppVectorIteratorSyntheticFrontEndCreator,
"std::vector iterator synthetic children",
ConstString("^__gnu_cxx::__normal_iterator<.+>$"), stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibstdcppMapIteratorSyntheticFrontEndCreator,
"std::map iterator synthetic children",
ConstString("^std::_Rb_tree_iterator<.+>$"), stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibStdcppUniquePtrSyntheticFrontEndCreator,
"std::unique_ptr synthetic children",
ConstString("^std::unique_ptr<.+>(( )?&)?$"), stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibStdcppSharedPtrSyntheticFrontEndCreator,
"std::shared_ptr synthetic children",
ConstString("^std::shared_ptr<.+>(( )?&)?$"), stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibStdcppSharedPtrSyntheticFrontEndCreator,
"std::weak_ptr synthetic children",
ConstString("^std::weak_ptr<.+>(( )?&)?$"), stl_synth_flags, true);
AddCXXSynthetic(
cpp_category_sp,
lldb_private::formatters::LibStdcppTupleSyntheticFrontEndCreator,
"std::tuple synthetic children", ConstString("^std::tuple<.+>(( )?&)?$"),
stl_synth_flags, true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibStdcppUniquePointerSummaryProvider,
"libstdc++ std::unique_ptr summary provider",
ConstString("^std::unique_ptr<.+>(( )?&)?$"), stl_summary_flags,
true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibStdcppSmartPointerSummaryProvider,
"libstdc++ std::shared_ptr summary provider",
ConstString("^std::shared_ptr<.+>(( )?&)?$"), stl_summary_flags,
true);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::LibStdcppSmartPointerSummaryProvider,
"libstdc++ std::weak_ptr summary provider",
ConstString("^std::weak_ptr<.+>(( )?&)?$"), stl_summary_flags,
true);
#endif
}
static void LoadSystemFormatters(lldb::TypeCategoryImplSP cpp_category_sp) {
if (!cpp_category_sp)
return;
TypeSummaryImpl::Flags string_flags;
string_flags.SetCascades(true)
.SetSkipPointers(true)
.SetSkipReferences(false)
.SetDontShowChildren(true)
.SetDontShowValue(false)
.SetShowMembersOneLiner(false)
.SetHideItemNames(false);
TypeSummaryImpl::Flags string_array_flags;
string_array_flags.SetCascades(true)
.SetSkipPointers(true)
.SetSkipReferences(false)
.SetDontShowChildren(true)
.SetDontShowValue(true)
.SetShowMembersOneLiner(false)
.SetHideItemNames(false);
#ifndef LLDB_DISABLE_PYTHON
// FIXME because of a bug in the FormattersContainer we need to add a summary
// for both X* and const X* (<rdar://problem/12717717>)
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::Char16StringSummaryProvider,
"char16_t * summary provider", ConstString("char16_t *"), string_flags);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::Char16StringSummaryProvider,
"char16_t [] summary provider",
ConstString("char16_t \\[[0-9]+\\]"), string_array_flags, true);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::Char32StringSummaryProvider,
"char32_t * summary provider", ConstString("char32_t *"), string_flags);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::Char32StringSummaryProvider,
"char32_t [] summary provider",
ConstString("char32_t \\[[0-9]+\\]"), string_array_flags, true);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::WCharStringSummaryProvider,
"wchar_t * summary provider", ConstString("wchar_t *"), string_flags);
AddCXXSummary(cpp_category_sp,
lldb_private::formatters::WCharStringSummaryProvider,
"wchar_t * summary provider",
ConstString("wchar_t \\[[0-9]+\\]"), string_array_flags, true);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::Char16StringSummaryProvider,
"unichar * summary provider", ConstString("unichar *"), string_flags);
TypeSummaryImpl::Flags widechar_flags;
widechar_flags.SetDontShowValue(true)
.SetSkipPointers(true)
.SetSkipReferences(false)
.SetCascades(true)
.SetDontShowChildren(true)
.SetHideItemNames(true)
.SetShowMembersOneLiner(false);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::Char16SummaryProvider,
"char16_t summary provider", ConstString("char16_t"), widechar_flags);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::Char32SummaryProvider,
"char32_t summary provider", ConstString("char32_t"), widechar_flags);
AddCXXSummary(cpp_category_sp, lldb_private::formatters::WCharSummaryProvider,
"wchar_t summary provider", ConstString("wchar_t"),
widechar_flags);
AddCXXSummary(
cpp_category_sp, lldb_private::formatters::Char16SummaryProvider,
"unichar summary provider", ConstString("unichar"), widechar_flags);
#endif
}
std::unique_ptr<Language::TypeScavenger> CPlusPlusLanguage::GetTypeScavenger() {
class CPlusPlusTypeScavenger : public Language::ImageListTypeScavenger {
public:
virtual CompilerType AdjustForInclusion(CompilerType &candidate) override {
LanguageType lang_type(candidate.GetMinimumLanguage());
if (!Language::LanguageIsC(lang_type) &&
!Language::LanguageIsCPlusPlus(lang_type))
return CompilerType();
if (candidate.IsTypedefType())
return candidate.GetTypedefedType();
return candidate;
}
};
return std::unique_ptr<TypeScavenger>(new CPlusPlusTypeScavenger());
}
lldb::TypeCategoryImplSP CPlusPlusLanguage::GetFormatters() {
static std::once_flag g_initialize;
static TypeCategoryImplSP g_category;
llvm::call_once(g_initialize, [this]() -> void {
DataVisualization::Categories::GetCategory(GetPluginName(), g_category);
if (g_category) {
LoadLibCxxFormatters(g_category);
LoadLibStdcppFormatters(g_category);
LoadSystemFormatters(g_category);
}
});
return g_category;
}
HardcodedFormatters::HardcodedSummaryFinder
CPlusPlusLanguage::GetHardcodedSummaries() {
static std::once_flag g_initialize;
static ConstString g_vectortypes("VectorTypes");
static HardcodedFormatters::HardcodedSummaryFinder g_formatters;
llvm::call_once(g_initialize, []() -> void {
g_formatters.push_back(
[](lldb_private::ValueObject &valobj, lldb::DynamicValueType,
FormatManager &) -> TypeSummaryImpl::SharedPointer {
static CXXFunctionSummaryFormat::SharedPointer formatter_sp(
new CXXFunctionSummaryFormat(
TypeSummaryImpl::Flags(),
lldb_private::formatters::CXXFunctionPointerSummaryProvider,
"Function pointer summary provider"));
if (valobj.GetCompilerType().IsFunctionPointerType()) {
return formatter_sp;
}
return nullptr;
});
g_formatters.push_back(
[](lldb_private::ValueObject &valobj, lldb::DynamicValueType,
FormatManager &fmt_mgr) -> TypeSummaryImpl::SharedPointer {
static CXXFunctionSummaryFormat::SharedPointer formatter_sp(
new CXXFunctionSummaryFormat(
TypeSummaryImpl::Flags()
.SetCascades(true)
.SetDontShowChildren(true)
.SetHideItemNames(true)
.SetShowMembersOneLiner(true)
.SetSkipPointers(true)
.SetSkipReferences(false),
lldb_private::formatters::VectorTypeSummaryProvider,
"vector_type pointer summary provider"));
if (valobj.GetCompilerType().IsVectorType(nullptr, nullptr)) {
if (fmt_mgr.GetCategory(g_vectortypes)->IsEnabled())
return formatter_sp;
}
return nullptr;
});
g_formatters.push_back(
[](lldb_private::ValueObject &valobj, lldb::DynamicValueType,
FormatManager &fmt_mgr) -> TypeSummaryImpl::SharedPointer {
static CXXFunctionSummaryFormat::SharedPointer formatter_sp(
new CXXFunctionSummaryFormat(
TypeSummaryImpl::Flags()
.SetCascades(true)
.SetDontShowChildren(true)
.SetHideItemNames(true)
.SetShowMembersOneLiner(true)
.SetSkipPointers(true)
.SetSkipReferences(false),
lldb_private::formatters::BlockPointerSummaryProvider,
"block pointer summary provider"));
if (valobj.GetCompilerType().IsBlockPointerType(nullptr)) {
return formatter_sp;
}
return nullptr;
});
});
return g_formatters;
}
HardcodedFormatters::HardcodedSyntheticFinder
CPlusPlusLanguage::GetHardcodedSynthetics() {
static std::once_flag g_initialize;
static ConstString g_vectortypes("VectorTypes");
static HardcodedFormatters::HardcodedSyntheticFinder g_formatters;
llvm::call_once(g_initialize, []() -> void {
g_formatters.push_back([](lldb_private::ValueObject &valobj,
lldb::DynamicValueType, FormatManager &fmt_mgr)
-> SyntheticChildren::SharedPointer {
static CXXSyntheticChildren::SharedPointer formatter_sp(
new CXXSyntheticChildren(
SyntheticChildren::Flags()
.SetCascades(true)
.SetSkipPointers(true)
.SetSkipReferences(true)
.SetNonCacheable(true),
"vector_type synthetic children",
lldb_private::formatters::VectorTypeSyntheticFrontEndCreator));
if (valobj.GetCompilerType().IsVectorType(nullptr, nullptr)) {
if (fmt_mgr.GetCategory(g_vectortypes)->IsEnabled())
return formatter_sp;
}
return nullptr;
});
g_formatters.push_back([](lldb_private::ValueObject &valobj,
lldb::DynamicValueType, FormatManager &fmt_mgr)
-> SyntheticChildren::SharedPointer {
static CXXSyntheticChildren::SharedPointer formatter_sp(
new CXXSyntheticChildren(
SyntheticChildren::Flags()
.SetCascades(true)
.SetSkipPointers(true)
.SetSkipReferences(true)
.SetNonCacheable(true),
"block pointer synthetic children",
lldb_private::formatters::BlockPointerSyntheticFrontEndCreator));
if (valobj.GetCompilerType().IsBlockPointerType(nullptr)) {
return formatter_sp;
}
return nullptr;
});
});
return g_formatters;
}
| 1 | 16,989 | This looks like a bunch of whitespace fixing that's unrelated. Can you revert? | apple-swift-lldb | cpp |
@@ -25,7 +25,7 @@ class AppKernel extends Kernel
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
- new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
+ // new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
new EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle(),
new EasyCorp\Bundle\EasyAdminBundle\Tests\Fixtures\AppTestBundle\AppTestBundle(), | 1 | <?php
/*
* This file is part of the EasyAdminBundle.
*
* (c) Javier Eguiluz <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
/**
* The kernel used in the application of most functional tests.
*/
class AppKernel extends Kernel
{
public function registerBundles()
{
return array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
new EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle(),
new EasyCorp\Bundle\EasyAdminBundle\Tests\Fixtures\AppTestBundle\AppTestBundle(),
);
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
if ($this->requiresAssetsConfig()) {
$loader->load(function (ContainerBuilder $container) {
$container->loadFromExtension('framework', array(
'assets' => null,
));
});
}
if ($this->requiresTemplatingConfig()) {
$loader->load(function (ContainerBuilder $container) {
$container->loadFromExtension('framework', array(
'templating' => array(
'engines' => array('twig'),
),
));
});
}
if ($this->requiresLogoutOnUserChange()) {
$loader->load(function (ContainerBuilder $container) {
$container->loadFromExtension('security', array(
'firewalls' => array(
'main' => array(
'logout_on_user_change' => true,
),
),
));
});
}
}
/**
* @return string
*/
public function getCacheDir()
{
return __DIR__.'/../../../build/cache/'.$this->getEnvironment();
}
/**
* @return string
*/
public function getLogDir()
{
return __DIR__.'/../../../build/kernel_logs/'.$this->getEnvironment();
}
protected function requiresAssetsConfig()
{
return (int) Kernel::MAJOR_VERSION >= 3;
}
protected function requiresTemplatingConfig()
{
return 2 === (int) Kernel::MAJOR_VERSION && 3 === (int) Kernel::MINOR_VERSION;
}
protected function requiresLogoutOnUserChange()
{
return (int) Kernel::VERSION_ID >= 30400;
}
}
| 1 | 11,475 | should be removed instead | EasyCorp-EasyAdminBundle | php |
@@ -88,10 +88,14 @@ public class TestRegExp extends LuceneTestCase {
assertTrue(a.toString().length() > 0);
}
+
+ boolean caseSensitiveQuery = true;
+
public void testCoreJavaParity() {
// Generate random doc values and random regular expressions
// and check for same matching behaviour as Java's Pattern class.
for (int i = 0; i < 1000; i++) {
+ caseSensitiveQuery = true;
checkRandomExpression(randomDocValue(1 + random().nextInt(30)));
}
} | 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.lucene.util.automaton;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegExp extends LuceneTestCase {
/**
* Simple smoke test for regular expression.
*/
public void testSmoke() {
RegExp r = new RegExp("a(b+|c+)d");
Automaton a = r.toAutomaton();
assertTrue(a.isDeterministic());
CharacterRunAutomaton run = new CharacterRunAutomaton(a);
assertTrue(run.run("abbbbbd"));
assertTrue(run.run("acd"));
assertFalse(run.run("ad"));
}
/**
* Compiles a regular expression that is prohibitively expensive to
* determinize and expexts to catch an exception for it.
*/
public void testDeterminizeTooManyStates() {
// LUCENE-6046
String source = "[ac]*a[ac]{50,200}";
TooComplexToDeterminizeException expected = expectThrows(TooComplexToDeterminizeException.class, () -> {
new RegExp(source).toAutomaton();
});
assertTrue(expected.getMessage().contains(source));
}
public void testSerializeTooManyStatesToRepeat() throws Exception {
String source = "a{50001}";
TooComplexToDeterminizeException expected = expectThrows(TooComplexToDeterminizeException.class, () -> {
new RegExp(source).toAutomaton(50000);
});
assertTrue(expected.getMessage().contains(source));
}
// LUCENE-6713
public void testSerializeTooManyStatesToDeterminizeExc() throws Exception {
// LUCENE-6046
String source = "[ac]*a[ac]{50,200}";
TooComplexToDeterminizeException expected = expectThrows(TooComplexToDeterminizeException.class, () -> {
new RegExp(source).toAutomaton();
});
assertTrue(expected.getMessage().contains(source));
}
// LUCENE-6046
public void testRepeatWithEmptyString() throws Exception {
Automaton a = new RegExp("[^y]*{1,2}").toAutomaton(1000);
// paranoia:
assertTrue(a.toString().length() > 0);
}
public void testRepeatWithEmptyLanguage() throws Exception {
Automaton a = new RegExp("#*").toAutomaton(1000);
// paranoia:
assertTrue(a.toString().length() > 0);
a = new RegExp("#+").toAutomaton(1000);
assertTrue(a.toString().length() > 0);
a = new RegExp("#{2,10}").toAutomaton(1000);
assertTrue(a.toString().length() > 0);
a = new RegExp("#?").toAutomaton(1000);
assertTrue(a.toString().length() > 0);
}
public void testCoreJavaParity() {
// Generate random doc values and random regular expressions
// and check for same matching behaviour as Java's Pattern class.
for (int i = 0; i < 1000; i++) {
checkRandomExpression(randomDocValue(1 + random().nextInt(30)));
}
}
public void testIllegalBackslashChars() {
String illegalChars = "abcefghijklmnopqrtuvxyzABCEFGHIJKLMNOPQRTUVXYZ";
for (int i = 0; i < illegalChars.length(); i++) {
String illegalExpression = "\\" + illegalChars.charAt(i);
IllegalArgumentException expected = expectThrows(
IllegalArgumentException.class, () -> {
new RegExp(illegalExpression);
}
);
assertTrue(expected.getMessage().contains("invalid character class"));
}
}
public void testLegalBackslashChars() {
String legalChars = "dDsSWw0123456789[]*&^$@!{}\\/";
for (int i = 0; i < legalChars.length(); i++) {
String legalExpression = "\\" + legalChars.charAt(i);
new RegExp(legalExpression);
}
}
static String randomDocValue(int minLength) {
String charPalette = "AAAaaaBbbCccc123456 \t";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < minLength; i++) {
sb.append(charPalette.charAt(randomInt(charPalette.length() - 1)));
}
return sb.toString();
}
private static int randomInt(int bound) {
return bound == 0 ? 0 : random().nextInt(bound);
}
protected String checkRandomExpression(String docValue) {
// Generate and test a random regular expression which should match the given docValue
StringBuilder result = new StringBuilder();
// Pick a part of the string to change
int substitutionPoint = randomInt(docValue.length() - 1);
int substitutionLength = 1 + randomInt(Math.min(10, docValue.length() - substitutionPoint));
// Add any head to the result, unchanged
if (substitutionPoint > 0) {
result.append(docValue.substring(0, substitutionPoint));
}
// Modify the middle...
String replacementPart = docValue.substring(substitutionPoint, substitutionPoint + substitutionLength);
int mutation = random().nextInt(13);
switch (mutation) {
case 0:
// OR with random alpha of same length
result.append("(" + replacementPart + "|d" + randomDocValue(replacementPart.length()) + ")");
break;
case 1:
// OR with non-existant value
result.append("(" + replacementPart + "|doesnotexist)");
break;
case 2:
// OR with another randomised regex (used to create nested levels of expression).
result.append("(" + checkRandomExpression(replacementPart) + "|doesnotexist)");
break;
case 3:
// Star-replace all ab sequences.
result.append(replacementPart.replaceAll("ab", ".*"));
break;
case 4:
// .-replace all b chars
result.append(replacementPart.replaceAll("b", "."));
break;
case 5:
// length-limited stars {1,2}
result.append(".{1," + replacementPart.length() + "}");
break;
case 6:
// replace all chars with .
result.append(replacementPart.replaceAll(".", "."));
break;
case 7:
// OR with uppercase chars eg [aA] (many of these sorts of expression in the wild..
char[] chars = replacementPart.toCharArray();
for (char c : chars) {
result.append("[" + c + Character.toUpperCase(c) + "]");
}
break;
case 8:
// NOT a character - replace all b's with "not a"
result.append(replacementPart.replaceAll("b", "[^a]"));
break;
case 9:
// Make whole part repeatable 1 or more times
result.append("(" + replacementPart + ")+");
break;
case 10:
// Make whole part repeatable 0 or more times
result.append("(" + replacementPart + ")?");
break;
case 11:
// Make any digits replaced by character class
result.append(replacementPart.replaceAll("\\d", "\\\\d"));
break;
case 12:
// Make any whitespace chars replaced by not word class
result.append(replacementPart.replaceAll("\\s", "\\\\W"));
break;
case 13:
// Make any whitespace chars replace by whitespace class
result.append(replacementPart.replaceAll("\\s", "\\\\s"));
break;
default:
break;
}
// add any remaining tail, unchanged
if (substitutionPoint + substitutionLength <= docValue.length() - 1) {
result.append(docValue.substring(substitutionPoint + substitutionLength));
}
String regexPattern = result.toString();
// Assert our randomly generated regex actually matches the provided raw input using java's expression matcher
Pattern pattern = Pattern.compile(regexPattern);
Matcher matcher = pattern.matcher(docValue);
assertTrue("Java regex " + regexPattern + " did not match doc value " + docValue, matcher.matches());
RegExp regex = new RegExp(regexPattern);
Automaton automaton = regex.toAutomaton();
ByteRunAutomaton bytesMatcher = new ByteRunAutomaton(automaton);
BytesRef br = new BytesRef(docValue);
assertTrue(
"[" + regexPattern + "]should match [" + docValue + "]" + substitutionPoint + "-" + substitutionLength + "/"
+ docValue.length(),
bytesMatcher.run(br.bytes, br.offset, br.length)
);
return regexPattern;
}
}
| 1 | 34,458 | should use randomization ? | apache-lucene-solr | java |
@@ -102,7 +102,7 @@ func (c *CmdVolumeOptions) RunVolumeInfo(cmd *cobra.Command) error {
// controller's IP, status, iqn, replica IPs etc.
volumeInfo, err := NewVolumeInfo(mapiserver.GetURL()+VolumeAPIPath+c.volName, c.volName, c.namespace)
if err != nil {
- return err
+ return nil
}
// Initiallize an instance of ReplicaCollection, json response recieved from the replica controller. Collection contains status and other information of replica. | 1 | /*
Copyright 2017 The OpenEBS 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 command
import (
"errors"
"fmt"
"html/template"
"os"
"strconv"
"strings"
"text/tabwriter"
client "github.com/openebs/maya/pkg/client/jiva"
k8sclient "github.com/openebs/maya/pkg/client/k8s"
"github.com/openebs/maya/pkg/client/mapiserver"
"github.com/openebs/maya/pkg/util"
"github.com/openebs/maya/types/v1"
"github.com/spf13/cobra"
)
var (
volumeInfoCommandHelpText = `
This command fetches information and status of the various
aspects of a Volume such as ISCSI, Controller, and Replica.
Usage: mayactl volume info --volname <vol>
`
)
// Value keeps info of the values of a current address in replicaIPStatus map
type Value struct {
index int
status string
mode string
}
// PortalInfo keep info about the ISCSI Target Portal.
type PortalInfo struct {
IQN string
VolumeName string
Portal string
Size string
Status string
ReplicaCount string
}
// ReplicaInfo keep info about the replicas.
type ReplicaInfo struct {
IP string
AccessMode string
Status string
Name string
NodeName string
}
// cstorReplicaInfo holds information about the cstor replicas
type cstorReplicaInfo struct {
Name string
PoolName string
AccessMode string
Status string
NodeName string
IP string
}
// NewCmdVolumeInfo displays OpenEBS Volume information.
func NewCmdVolumeInfo() *cobra.Command {
cmd := &cobra.Command{
Use: "info",
Short: "Displays Openebs Volume information",
Long: volumeInfoCommandHelpText,
Example: `mayactl volume info --volname <vol>`,
Run: func(cmd *cobra.Command, args []string) {
util.CheckErr(options.Validate(cmd, false, false, true), util.Fatal)
util.CheckErr(options.RunVolumeInfo(cmd), util.Fatal)
},
}
cmd.Flags().StringVarP(&options.volName, "volname", "", options.volName,
"a unique volume name.")
return cmd
}
// RunVolumeInfo runs info command and make call to DisplayVolumeInfo to display the results
func (c *CmdVolumeOptions) RunVolumeInfo(cmd *cobra.Command) error {
volumeInfo := &VolumeInfo{}
// FetchVolumeInfo is called to get the volume controller's info such as
// controller's IP, status, iqn, replica IPs etc.
volumeInfo, err := NewVolumeInfo(mapiserver.GetURL()+VolumeAPIPath+c.volName, c.volName, c.namespace)
if err != nil {
return err
}
// Initiallize an instance of ReplicaCollection, json response recieved from the replica controller. Collection contains status and other information of replica.
collection := client.ReplicaCollection{}
if volumeInfo.GetCASType() == string(JivaStorageEngine) {
collection, err = getReplicaInfo(volumeInfo)
}
c.DisplayVolumeInfo(volumeInfo, collection)
return nil
}
// getReplicaInfo returns the collection of replicas available for jiva volumes
func getReplicaInfo(volumeInfo *VolumeInfo) (client.ReplicaCollection, error) {
controllerClient := client.ControllerClient{}
collection := client.ReplicaCollection{}
controllerStatuses := strings.Split(volumeInfo.GetControllerStatus(), ",")
// Iterating over controllerStatus
for _, controllerStatus := range controllerStatuses {
if controllerStatus != controllerStatusOk {
fmt.Printf("Unable to fetch volume details, Volume controller's status is '%s'.\n", controllerStatus)
return collection, errors.New("Unable to fetch volume details")
}
}
// controllerIP:9501/v1/replicas is to be parsed into this structure via GetVolumeStats.
// An API needs to be passed as argument.
_, err := controllerClient.GetVolumeStats(volumeInfo.GetClusterIP()+v1.ControllerPort, v1.InfoAPI, &collection)
if err != nil {
fmt.Printf("Cannot get volume stats %v", err)
}
return collection, err
}
// updateReplicaInfo parses replica information to replicaInfo structure
func updateReplicasInfo(replicaInfo map[int]*ReplicaInfo) error {
K8sClient, err := k8sclient.NewK8sClient("")
if err != nil {
return err
}
pods, err := K8sClient.GetPods()
if err != nil {
return err
}
for _, replica := range replicaInfo {
for _, pod := range pods {
if pod.Status.PodIP == replica.IP {
replica.NodeName = pod.Spec.NodeName
replica.Name = pod.ObjectMeta.Name
}
}
}
return nil
}
// DisplayVolumeInfo displays the outputs in standard I/O.
// Currently it displays volume access modes and target portal details only.
func (c *CmdVolumeOptions) DisplayVolumeInfo(v *VolumeInfo, collection client.ReplicaCollection) error {
var (
// address and mode are used here as blackbox for the replica info
// address keeps the ip and access mode details respectively.
address, mode []string
replicaCount int
portalInfo PortalInfo
)
const (
jivaReplicaTemplate = `
Replica Details :
-----------------
{{ printf "NAME\t ACCESSMODE\t STATUS\t IP\t NODE" }}
{{ printf "-----\t -----------\t -------\t ---\t -----" }} {{range $key, $value := .}}
{{ printf "%s\t" $value.Name }} {{ printf "%s\t" $value.AccessMode }} {{ printf "%s\t" $value.Status }} {{ printf "%s\t" $value.IP }} {{ $value.NodeName }} {{end}}
`
cstorReplicaTemplate = `
Replica Details :
-----------------
{{ printf "%s\t" "NAME"}} {{ printf "%s\t" "STATUS"}} {{ printf "%s\t" "POOL NAME"}} {{ printf "%s\t" "NODE"}}
{{ printf "----\t ------\t ---------\t -----" }} {{range $key, $value := .}}
{{ printf "%s\t" $value.Name }} {{ printf "%s\t" $value.Status }} {{ printf "%s\t" $value.PoolName }} {{ $value.NodeName }} {{end}}
`
portalTemplate = `
Portal Details :
----------------
IQN : {{.IQN}}
Volume : {{.VolumeName}}
Portal : {{.Portal}}
Size : {{.Size}}
Status : {{.Status}}
Replica Count : {{.ReplicaCount}}
`
)
portalInfo = PortalInfo{
v.GetIQN(),
v.GetVolumeName(),
v.GetTargetPortal(),
v.GetVolumeSize(),
v.GetControllerStatus(),
v.GetReplicaCount(),
}
tmpl, err := template.New("VolumeInfo").Parse(portalTemplate)
if err != nil {
fmt.Println("Error displaying output, found error :", err)
return nil
}
err = tmpl.Execute(os.Stdout, portalInfo)
if err != nil {
fmt.Println("Error displaying volume details, found error :", err)
return nil
}
if v.GetCASType() == string(JivaStorageEngine) {
replicaCount, _ = strconv.Atoi(v.GetReplicaCount())
// This case will occur only if user has manually specified zero replica.
if replicaCount == 0 || len(v.GetReplicaStatus()) == 0 {
fmt.Println("None of the replicas are running, please check the volume pod's status by running [kubectl describe pod -l=openebs/replica --all-namespaces] or try again later.")
return nil
}
// Splitting strings with delimiter ','
replicaStatusStrings := strings.Split(v.GetReplicaStatus(), ",")
addressIPStrings := strings.Split(v.GetReplicaIP(), ",")
// making a map of replica ip and their respective status,index and mode
replicaIPStatus := make(map[string]*Value)
// Creating a map of address and mode. The IP is chosed as key so that the status of that corresponding replica can be merged in linear time complexity
for index, IP := range addressIPStrings {
if strings.Contains(IP, "nil") {
// appending address with index to avoid same key conflict as the IP is returned as `nil` in case of error
replicaIPStatus[IP+string(index)] = &Value{index: index, status: replicaStatusStrings[index], mode: "NA"}
} else {
replicaIPStatus[IP] = &Value{index: index, status: replicaStatusStrings[index], mode: "NA"}
}
}
// We get the info of the running replicas from the collection.data.
// We are appending modes if available in collection.data to replicaIPStatus
replicaInfo := make(map[int]*ReplicaInfo)
for key := range collection.Data {
address = append(address, strings.TrimSuffix(strings.TrimPrefix(collection.Data[key].Address, "tcp://"), v1.ReplicaPort))
mode = append(mode, collection.Data[key].Mode)
if _, ok := replicaIPStatus[address[key]]; ok {
replicaIPStatus[address[key]].mode = mode[key]
}
}
for IP, replicaStatus := range replicaIPStatus {
// checking if the first three letters is nil or not if it is nil then the ip is not avaiable
if strings.Contains(IP, "nil") {
replicaInfo[replicaStatus.index] = &ReplicaInfo{"NA", replicaStatus.mode, replicaStatus.status, "NA", "NA"}
} else {
replicaInfo[replicaStatus.index] = &ReplicaInfo{IP, replicaStatus.mode, replicaStatus.status, "NA", "NA"}
}
}
// updating the replica info to replica structure
err = updateReplicasInfo(replicaInfo)
if err != nil {
fmt.Println("Error in getting specific information from K8s. Please try again.")
}
// parsing the information to replicastatus template
tmpl = template.New("ReplicaInfo")
tmpl = template.Must(tmpl.Parse(jivaReplicaTemplate))
w := tabwriter.NewWriter(os.Stdout, v1.MinWidth, v1.MaxWidth, v1.Padding, ' ', 0)
err = tmpl.Execute(w, replicaInfo)
if err != nil {
fmt.Println("Unable to display volume info, found error : ", err)
}
w.Flush()
} else if v.GetCASType() == string(CstorStorageEngine) {
// Converting replica count character to int
replicaCount, err = strconv.Atoi(v.GetReplicaCount())
if err != nil {
fmt.Println("Invalid replica count")
return nil
}
// Spitting the replica status
replicaStatus := strings.Split(v.GetControllerStatus(), ",")
poolName := strings.Split(v.GetStoragePool(), ",")
cvrName := strings.Split(v.GetCVRName(), ",")
nodeName := strings.Split(v.GetNodeName(), ",")
// Confirming replica status, poolname , cvrName, nodeName are equal to replica count
if replicaCount != len(replicaStatus) || replicaCount != len(poolName) || replicaCount != len(cvrName) || replicaCount != len(nodeName) {
fmt.Println("Invalid response received from maya-api service")
return nil
}
replicaInfo := []cstorReplicaInfo{}
// Iterating over the values replica values and appending to the structure
for i := 0; i < replicaCount; i++ {
replicaInfo = append(replicaInfo, cstorReplicaInfo{
Name: cvrName[i],
PoolName: poolName[i],
AccessMode: "N/A",
Status: strings.Title(replicaStatus[i]),
NodeName: nodeName[i],
IP: "N/A",
})
}
// Parsing the information to cstorReplicaInfo template
cstorTemplate := template.New("CstorReplicaInfo")
cstorTemplate = template.Must(cstorTemplate.Parse(cstorReplicaTemplate))
// Executing tabwriter on above template
w := tabwriter.NewWriter(os.Stdout, v1.MinWidth, v1.MaxWidth, v1.Padding, ' ', 0)
err = cstorTemplate.Execute(w, replicaInfo)
if err != nil {
fmt.Println("Unable to display volume info, found error : ", err)
}
w.Flush()
} else {
fmt.Println("Unsupported Volume Type")
}
return nil
}
| 1 | 9,365 | returning nil because we want to mayactl to exit with 0 status code. | openebs-maya | go |
@@ -112,7 +112,7 @@ static void send_response(struct st_h2o_status_collector_t *collector)
resp[cur_resp++] = (h2o_iovec_t){H2O_STRLIT("\n}\n")};
req->res.status = 200;
- h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, H2O_STRLIT("text/plain; charset=utf-8"));
+ h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, H2O_STRLIT("application/json; charset=utf-8"));
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CACHE_CONTROL, H2O_STRLIT("no-cache, no-store"));
h2o_start_response(req, &generator);
h2o_send(req, resp, h2o_memis(req->input.method.base, req->input.method.len, H2O_STRLIT("HEAD")) ? 0 : nr_resp, 1); | 1 | /*
* Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku
*
* 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 "h2o.h"
extern h2o_status_handler_t events_status_handler;
extern h2o_status_handler_t requests_status_handler;
struct st_h2o_status_logger_t {
h2o_logger_t super;
};
struct st_h2o_root_status_handler_t {
h2o_handler_t super;
H2O_VECTOR(h2o_multithread_receiver_t *) receivers;
};
struct st_h2o_status_context_t {
h2o_context_t *ctx;
h2o_multithread_receiver_t receiver;
};
struct st_status_ctx_t {
int active;
void *ctx;
};
struct st_h2o_status_collector_t {
struct {
h2o_req_t *req;
h2o_multithread_receiver_t *receiver;
} src;
size_t num_remaining_threads_atomic;
H2O_VECTOR(struct st_status_ctx_t) status_ctx;
};
struct st_h2o_status_message_t {
h2o_multithread_message_t super;
struct st_h2o_status_collector_t *collector;
};
static void collect_reqs_of_context(struct st_h2o_status_collector_t *collector, h2o_context_t *ctx)
{
int i;
for (i = 0; i < ctx->globalconf->statuses.size; i++) {
struct st_status_ctx_t *sc = collector->status_ctx.entries + i;
h2o_status_handler_t *sh = ctx->globalconf->statuses.entries + i;
if (sc->active && sh->per_thread != NULL)
sh->per_thread(sc->ctx, ctx);
}
if (__sync_sub_and_fetch(&collector->num_remaining_threads_atomic, 1) == 0) {
struct st_h2o_status_message_t *message = h2o_mem_alloc(sizeof(*message));
message->super = (h2o_multithread_message_t){{NULL}};
message->collector = collector;
h2o_multithread_send_message(collector->src.receiver, &message->super);
}
}
static void send_response(struct st_h2o_status_collector_t *collector)
{
static h2o_generator_t generator = {NULL, NULL};
h2o_req_t *req;
size_t nr_statuses;
int i;
int cur_resp = 0;
req = collector->src.req;
if (!req) {
h2o_mem_release_shared(collector);
return;
}
nr_statuses = req->conn->ctx->globalconf->statuses.size;
size_t nr_resp = nr_statuses + 2; // 2 for the footer and header
h2o_iovec_t resp[nr_resp];
memset(resp, 0, sizeof(resp[0]) * nr_resp);
resp[cur_resp++] = (h2o_iovec_t){H2O_STRLIT("{\n")};
int coma_removed = 0;
for (i = 0; i < req->conn->ctx->globalconf->statuses.size; i++) {
h2o_status_handler_t *sh = &req->conn->ctx->globalconf->statuses.entries[i];
if (!collector->status_ctx.entries[i].active) {
continue;
}
resp[cur_resp++] = sh->final(collector->status_ctx.entries[i].ctx, req->conn->ctx->globalconf, req);
if (resp[cur_resp - 1].len > 0 && !coma_removed) {
/* requests come in with a leading coma, replace if with a space */
resp[cur_resp - 1].base[0] = ' ';
coma_removed = 1;
}
}
resp[cur_resp++] = (h2o_iovec_t){H2O_STRLIT("\n}\n")};
req->res.status = 200;
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, H2O_STRLIT("text/plain; charset=utf-8"));
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CACHE_CONTROL, H2O_STRLIT("no-cache, no-store"));
h2o_start_response(req, &generator);
h2o_send(req, resp, h2o_memis(req->input.method.base, req->input.method.len, H2O_STRLIT("HEAD")) ? 0 : nr_resp, 1);
h2o_mem_release_shared(collector);
}
static void on_collect_notify(h2o_multithread_receiver_t *receiver, h2o_linklist_t *messages)
{
struct st_h2o_status_context_t *status_ctx = H2O_STRUCT_FROM_MEMBER(struct st_h2o_status_context_t, receiver, receiver);
while (!h2o_linklist_is_empty(messages)) {
struct st_h2o_status_message_t *message = H2O_STRUCT_FROM_MEMBER(struct st_h2o_status_message_t, super, messages->next);
struct st_h2o_status_collector_t *collector = message->collector;
h2o_linklist_unlink(&message->super.link);
free(message);
if (__sync_add_and_fetch(&collector->num_remaining_threads_atomic, 0) != 0) {
collect_reqs_of_context(collector, status_ctx->ctx);
} else {
send_response(collector);
}
}
}
static void on_collector_dispose(void *_collector)
{
}
static void on_req_close(void *p)
{
struct st_h2o_status_collector_t *collector = *(void **)p;
collector->src.req = NULL;
h2o_mem_release_shared(collector);
}
static int on_req_json(struct st_h2o_root_status_handler_t *self, h2o_req_t *req, h2o_iovec_t status_list)
{
{ /* construct collector and send request to every thread */
struct st_h2o_status_context_t *status_ctx = h2o_context_get_handler_context(req->conn->ctx, &self->super);
struct st_h2o_status_collector_t *collector = h2o_mem_alloc_shared(NULL, sizeof(*collector), on_collector_dispose);
size_t i;
memset(collector, 0, sizeof(*collector));
for (i = 0; i < req->conn->ctx->globalconf->statuses.size; i++) {
h2o_status_handler_t *sh;
h2o_vector_reserve(&req->pool, &collector->status_ctx, collector->status_ctx.size + 1);
sh = &req->conn->ctx->globalconf->statuses.entries[i];
if (status_list.base) {
if (!h2o_contains_token(status_list.base, status_list.len, sh->name.base, sh->name.len, ',')) {
collector->status_ctx.entries[collector->status_ctx.size].active = 0;
goto Skip;
}
}
if (sh->init) {
collector->status_ctx.entries[collector->status_ctx.size].ctx = sh->init();
}
collector->status_ctx.entries[collector->status_ctx.size].active = 1;
Skip:
collector->status_ctx.size++;
}
collector->src.req = req;
collector->src.receiver = &status_ctx->receiver;
collector->num_remaining_threads_atomic = self->receivers.size;
for (i = 0; i != self->receivers.size; ++i) {
struct st_h2o_status_message_t *message = h2o_mem_alloc(sizeof(*message));
*message = (struct st_h2o_status_message_t){{{NULL}}, collector};
h2o_multithread_send_message(self->receivers.entries[i], &message->super);
}
/* collector is also retained by the on_req_close callback */
*(struct st_h2o_status_collector_t **)h2o_mem_alloc_shared(&req->pool, sizeof(collector), on_req_close) = collector;
h2o_mem_addref_shared(collector);
}
return 0;
}
static int on_req(h2o_handler_t *_self, h2o_req_t *req)
{
struct st_h2o_root_status_handler_t *self = (void *)_self;
size_t prefix_len = req->pathconf->path.len - (req->pathconf->path.base[req->pathconf->path.len - 1] == '/');
h2o_iovec_t local_path = h2o_iovec_init(req->path_normalized.base + prefix_len, req->path_normalized.len - prefix_len);
if (local_path.len == 0 || h2o_memis(local_path.base, local_path.len, H2O_STRLIT("/"))) {
/* root of the handler returns HTML that renders the status */
h2o_iovec_t fn;
const char *root = getenv("H2O_ROOT");
if (root == NULL)
root = H2O_TO_STR(H2O_ROOT);
fn = h2o_concat(&req->pool, h2o_iovec_init(root, strlen(root)), h2o_iovec_init(H2O_STRLIT("/share/h2o/status/index.html")));
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CACHE_CONTROL, H2O_STRLIT("no-cache"));
return h2o_file_send(req, 200, "OK", fn.base, h2o_iovec_init(H2O_STRLIT("text/html; charset=utf-8")), 0);
} else if (h2o_memis(local_path.base, local_path.len, H2O_STRLIT("/json"))) {
int ret;
/* "/json" maps to the JSON API */
h2o_iovec_t status_list = {NULL, 0}; /* NULL means we'll show all statuses */
if (req->query_at != SIZE_MAX && (req->path.len - req->query_at > 6)) {
if (h2o_memis(&req->path.base[req->query_at], 6, "?show=", 6)) {
status_list = h2o_iovec_init(&req->path.base[req->query_at + 6], req->path.len - req->query_at - 6);
}
}
ret = on_req_json(self, req, status_list);
return ret;
}
return -1;
}
static void on_context_init(h2o_handler_t *_self, h2o_context_t *ctx)
{
struct st_h2o_root_status_handler_t *self = (void *)_self;
struct st_h2o_status_context_t *status_ctx = h2o_mem_alloc(sizeof(*status_ctx));
status_ctx->ctx = ctx;
h2o_multithread_register_receiver(ctx->queue, &status_ctx->receiver, on_collect_notify);
h2o_vector_reserve(NULL, &self->receivers, self->receivers.size + 1);
self->receivers.entries[self->receivers.size++] = &status_ctx->receiver;
h2o_context_set_handler_context(ctx, &self->super, status_ctx);
}
static void on_context_dispose(h2o_handler_t *_self, h2o_context_t *ctx)
{
struct st_h2o_root_status_handler_t *self = (void *)_self;
struct st_h2o_status_context_t *status_ctx = h2o_context_get_handler_context(ctx, &self->super);
size_t i;
for (i = 0; i != self->receivers.size; ++i)
if (self->receivers.entries[i] == &status_ctx->receiver)
break;
assert(i != self->receivers.size);
memmove(self->receivers.entries + i + 1, self->receivers.entries + i, self->receivers.size - i - 1);
--self->receivers.size;
h2o_multithread_unregister_receiver(ctx->queue, &status_ctx->receiver);
free(status_ctx);
}
void h2o_status_register(h2o_pathconf_t *conf)
{
struct st_h2o_root_status_handler_t *self = (void *)h2o_create_handler(conf, sizeof(*self));
self->super.on_context_init = on_context_init;
self->super.on_context_dispose = on_context_dispose;
self->super.on_req = on_req;
h2o_config_register_status_handler(conf->global, requests_status_handler);
h2o_config_register_status_handler(conf->global, events_status_handler);
}
| 1 | 11,329 | Is this change relevant to the PR? (and I believe we should use `text/plain` considering the fact that it can be displayed using web browsers...) | h2o-h2o | c |
@@ -9,12 +9,12 @@ namespace Microsoft.CodeAnalysis.Sarif
/// <summary>
/// The state of a result relative to a baseline of a previous run.
/// </summary>
- [GeneratedCode("Microsoft.Json.Schema.ToDotNet", "0.28.0.0")]
[Flags]
+ [GeneratedCode("Microsoft.Json.Schema.ToDotNet", "0.30.0.0")]
public enum SuppressionStates
{
None,
- SuppressedInSource = 0x1,
- SuppressedInBaseline = 0x2
+ SuppressedInSource = 1,
+ SuppressedInBaseline = 2
}
} | 1 | // Copyright (c) Microsoft. 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.CodeDom.Compiler;
namespace Microsoft.CodeAnalysis.Sarif
{
/// <summary>
/// The state of a result relative to a baseline of a previous run.
/// </summary>
[GeneratedCode("Microsoft.Json.Schema.ToDotNet", "0.28.0.0")]
[Flags]
public enum SuppressionStates
{
None,
SuppressedInSource = 0x1,
SuppressedInBaseline = 0x2
}
} | 1 | 10,780 | `[Flags]` is now auto-generated by an argument to the `EnumHint`. (The attributes happen to come out in this order. I don't think it's worth controlling the order.) #Resolved | microsoft-sarif-sdk | .cs |
@@ -376,6 +376,9 @@ configRetry:
} else {
// Use the syncer locally.
syncer = felixsyncer.New(backendClient, datastoreConfig.Spec, syncerToValidator)
+
+ log.Info("using resource updates where applicable")
+ configParams.SetUseResourceUpdates(true)
}
log.WithField("syncer", syncer).Info("Created Syncer")
| 1 | // Copyright (c) 2017-2019 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package daemon
import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"runtime"
"runtime/debug"
"strconv"
"sync"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
"github.com/projectcalico/felix/buildinfo"
"github.com/projectcalico/felix/calc"
"github.com/projectcalico/felix/config"
_ "github.com/projectcalico/felix/config"
dp "github.com/projectcalico/felix/dataplane"
"github.com/projectcalico/felix/logutils"
"github.com/projectcalico/felix/policysync"
"github.com/projectcalico/felix/proto"
"github.com/projectcalico/felix/statusrep"
"github.com/projectcalico/felix/usagerep"
"github.com/projectcalico/libcalico-go/lib/apiconfig"
apiv3 "github.com/projectcalico/libcalico-go/lib/apis/v3"
"github.com/projectcalico/libcalico-go/lib/backend"
bapi "github.com/projectcalico/libcalico-go/lib/backend/api"
"github.com/projectcalico/libcalico-go/lib/backend/model"
"github.com/projectcalico/libcalico-go/lib/backend/syncersv1/felixsyncer"
"github.com/projectcalico/libcalico-go/lib/backend/syncersv1/updateprocessors"
"github.com/projectcalico/libcalico-go/lib/backend/watchersyncer"
cerrors "github.com/projectcalico/libcalico-go/lib/errors"
"github.com/projectcalico/libcalico-go/lib/health"
lclogutils "github.com/projectcalico/libcalico-go/lib/logutils"
"github.com/projectcalico/libcalico-go/lib/set"
"github.com/projectcalico/pod2daemon/binder"
"github.com/projectcalico/typha/pkg/syncclient"
)
const usage = `Felix, the Calico per-host daemon.
Usage:
calico-felix [options]
Options:
-c --config-file=<filename> Config file to load [default: /etc/calico/felix.cfg].
--version Print the version and exit.
`
const (
// Our default value for GOGC if it is not set. This is the percentage that heap usage must
// grow by to trigger a garbage collection. Go's default is 100, meaning that 50% of the
// heap can be lost to garbage. We reduce it to this value to trade increased CPU usage for
// lower occupancy.
defaultGCPercent = 20
// String sent on the failure report channel to indicate we're shutting down for config
// change.
reasonConfigChanged = "config changed"
// Process return code used to report a config change. This is the same as the code used
// by SIGHUP, which means that the wrapper script also restarts Felix on a SIGHUP.
configChangedRC = 129
)
// Run is the entry point to run a Felix instance.
//
// Its main role is to sequence Felix's startup by:
//
// Initialising early logging config (log format and early debug settings).
//
// Parsing command line parameters.
//
// Loading datastore configuration from the environment or config file.
//
// Loading more configuration from the datastore (this is retried until success).
//
// Starting the configured internal (golang) or external dataplane driver.
//
// Starting the background processing goroutines, which load and keep in sync with the
// state from the datastore, the "calculation graph".
//
// Starting the usage reporting and prometheus metrics endpoint threads (if configured).
//
// Then, it defers to monitorAndManageShutdown(), which blocks until one of the components
// fails, then attempts a graceful shutdown. At that point, all the processing is in
// background goroutines.
//
// To avoid having to maintain rarely-used code paths, Felix handles updates to its
// main config parameters by exiting and allowing itself to be restarted by the init
// daemon.
func Run(configFile string, gitVersion string, buildDate string, gitRevision string) {
// Go's RNG is not seeded by default. Do that now.
rand.Seed(time.Now().UTC().UnixNano())
// Special-case handling for environment variable-configured logging:
// Initialise early so we can trace out config parsing.
logutils.ConfigureEarlyLogging()
ctx := context.Background()
if os.Getenv("GOGC") == "" {
// Tune the GC to trade off a little extra CPU usage for significantly lower
// occupancy at high scale. This is worthwhile because Felix runs per-host so
// any occupancy improvement is multiplied by the number of hosts.
log.Debugf("No GOGC value set, defaulting to %d%%.", defaultGCPercent)
debug.SetGCPercent(defaultGCPercent)
}
if len(buildinfo.GitVersion) == 0 && len(gitVersion) != 0 {
buildinfo.GitVersion = gitVersion
buildinfo.BuildDate = buildDate
buildinfo.GitRevision = gitRevision
}
buildInfoLogCxt := log.WithFields(log.Fields{
"version": buildinfo.GitVersion,
"builddate": buildinfo.BuildDate,
"gitcommit": buildinfo.GitRevision,
"GOMAXPROCS": runtime.GOMAXPROCS(0),
})
buildInfoLogCxt.Info("Felix starting up")
// Health monitoring, for liveness and readiness endpoints. The following loop can take a
// while before the datastore reports itself as ready - for example when there is data that
// needs to be migrated from a previous version - and we still want to Felix to report
// itself as live (but not ready) while we are waiting for that. So we create the
// aggregator upfront and will start serving health status over HTTP as soon as we see _any_
// config that indicates that.
healthAggregator := health.NewHealthAggregator()
const healthName = "felix-startup"
// Register this function as a reporter of liveness and readiness, with no timeout.
healthAggregator.RegisterReporter(healthName, &health.HealthReport{Live: true, Ready: true}, 0)
// Load the configuration from all the different sources including the
// datastore and merge. Keep retrying on failure. We'll sit in this
// loop until the datastore is ready.
log.Info("Loading configuration...")
var backendClient bapi.Client
var datastoreConfig apiconfig.CalicoAPIConfig
var configParams *config.Config
var typhaAddr string
var numClientsCreated int
configRetry:
for {
if numClientsCreated > 60 {
// If we're in a restart loop, periodically exit (so we can be restarted) since
// - it may solve the problem if there's something wrong with our process
// - it prevents us from leaking connections to the datastore.
exitWithCustomRC(configChangedRC, "Restarting to avoid leaking datastore connections")
}
// Make an initial report that says we're live but not yet ready.
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: false})
// Load locally-defined config, including the datastore connection
// parameters. First the environment variables.
configParams = config.New()
envConfig := config.LoadConfigFromEnvironment(os.Environ())
// Then, the config file.
log.Infof("Loading config file: %v", configFile)
fileConfig, err := config.LoadConfigFile(configFile)
if err != nil {
log.WithError(err).WithField("configFile", configFile).Error(
"Failed to load configuration file")
time.Sleep(1 * time.Second)
continue configRetry
}
// Parse and merge the local config.
configParams.UpdateFrom(envConfig, config.EnvironmentVariable)
if configParams.Err != nil {
log.WithError(configParams.Err).WithField("configFile", configFile).Error(
"Failed to parse configuration environment variable")
time.Sleep(1 * time.Second)
continue configRetry
}
configParams.UpdateFrom(fileConfig, config.ConfigFile)
if configParams.Err != nil {
log.WithError(configParams.Err).WithField("configFile", configFile).Error(
"Failed to parse configuration file")
time.Sleep(1 * time.Second)
continue configRetry
}
// Each time round this loop, check that we're serving health reports if we should
// be, or cancel any existing server if we should not be serving any more.
healthAggregator.ServeHTTP(configParams.HealthEnabled, configParams.HealthHost, configParams.HealthPort)
// We should now have enough config to connect to the datastore
// so we can load the remainder of the config.
datastoreConfig = configParams.DatastoreConfig()
// Can't dump the whole config because it may have sensitive information...
log.WithField("datastore", datastoreConfig.Spec.DatastoreType).Info("Connecting to datastore")
backendClient, err = backend.NewClient(datastoreConfig)
if err != nil {
log.WithError(err).Error("Failed to create datastore client")
time.Sleep(1 * time.Second)
continue configRetry
}
log.Info("Created datastore client")
numClientsCreated++
for {
globalConfig, hostConfig, err := loadConfigFromDatastore(
ctx, backendClient, configParams.FelixHostname)
if err == ErrNotReady {
log.Warn("Waiting for datastore to be initialized (or migrated)")
time.Sleep(1 * time.Second)
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: true})
continue
} else if err != nil {
log.WithError(err).Error("Failed to get config from datastore")
time.Sleep(1 * time.Second)
continue configRetry
}
configParams.UpdateFrom(globalConfig, config.DatastoreGlobal)
configParams.UpdateFrom(hostConfig, config.DatastorePerHost)
break
}
configParams.Validate()
if configParams.Err != nil {
log.WithError(configParams.Err).Error(
"Failed to parse/validate configuration from datastore.")
time.Sleep(1 * time.Second)
continue configRetry
}
// We now have some config flags that affect how we configure the syncer.
// After loading the config from the datastore, reconnect, possibly with new
// config. We don't need to re-load the configuration _again_ because the
// calculation graph will spot if the config has changed since we were initialised.
datastoreConfig = configParams.DatastoreConfig()
backendClient, err = backend.NewClient(datastoreConfig)
if err != nil {
log.WithError(err).Error("Failed to (re)connect to datastore")
time.Sleep(1 * time.Second)
continue configRetry
}
numClientsCreated++
// If we're configured to discover Typha, do that now so we can retry if we fail.
typhaAddr, err = discoverTyphaAddr(configParams, config.GetKubernetesService)
if err != nil {
log.WithError(err).Error("Typha discovery enabled but discovery failed.")
time.Sleep(1 * time.Second)
continue configRetry
}
break configRetry
}
if numClientsCreated > 2 {
// We don't have a way to close datastore connection so, if we reconnected after
// a failure to load config, restart felix to avoid leaking connections.
exitWithCustomRC(configChangedRC, "Restarting to avoid leaking datastore connections")
}
// We're now both live and ready.
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: true})
// Enable or disable the health HTTP server according to coalesced config.
healthAggregator.ServeHTTP(configParams.HealthEnabled, configParams.HealthHost, configParams.HealthPort)
// If we get here, we've loaded the configuration successfully.
// Update log levels before we do anything else.
logutils.ConfigureLogging(configParams)
// Since we may have enabled more logging, log with the build context
// again.
buildInfoLogCxt.WithField("config", configParams).Info(
"Successfully loaded configuration.")
// Start up the dataplane driver. This may be the internal go-based driver or an external
// one.
var dpDriver dp.DataplaneDriver
var dpDriverCmd *exec.Cmd
failureReportChan := make(chan string)
configChangedRestartCallback := func() { failureReportChan <- reasonConfigChanged }
dpDriver, dpDriverCmd = dp.StartDataplaneDriver(configParams, healthAggregator, configChangedRestartCallback)
// Initialise the glue logic that connects the calculation graph to/from the dataplane driver.
log.Info("Connect to the dataplane driver.")
var connToUsageRepUpdChan chan map[string]string
if configParams.UsageReportingEnabled {
// Make a channel for the connector to use to send updates to the usage reporter.
// (Otherwise, we pass in a nil channel, which disables such updates.)
connToUsageRepUpdChan = make(chan map[string]string, 1)
}
dpConnector := newConnector(configParams, connToUsageRepUpdChan, backendClient, dpDriver, failureReportChan)
// If enabled, create a server for the policy sync API. This allows clients to connect to
// Felix over a socket and receive policy updates.
var policySyncServer *policysync.Server
var policySyncProcessor *policysync.Processor
var policySyncAPIBinder binder.Binder
calcGraphClientChannels := []chan<- interface{}{dpConnector.ToDataplane}
if configParams.PolicySyncPathPrefix != "" {
log.WithField("policySyncPathPrefix", configParams.PolicySyncPathPrefix).Info(
"Policy sync API enabled. Creating the policy sync server.")
toPolicySync := make(chan interface{})
policySyncUIDAllocator := policysync.NewUIDAllocator()
policySyncProcessor = policysync.NewProcessor(toPolicySync)
policySyncServer = policysync.NewServer(
policySyncProcessor.JoinUpdates,
policySyncUIDAllocator.NextUID,
)
policySyncAPIBinder = binder.NewBinder(configParams.PolicySyncPathPrefix)
policySyncServer.RegisterGrpc(policySyncAPIBinder.Server())
calcGraphClientChannels = append(calcGraphClientChannels, toPolicySync)
}
// Now create the calculation graph, which receives updates from the
// datastore and outputs dataplane updates for the dataplane driver.
//
// The Syncer has its own thread and we use an extra thread for the
// Validator, just to pipeline that part of the calculation then the
// main calculation graph runs in a single thread for simplicity.
// The output of the calculation graph arrives at the dataplane
// connection via channel.
//
// Syncer -chan-> Validator -chan-> Calc graph -chan-> dataplane
// KVPair KVPair protobufs
// Get a Syncer from the datastore, or a connection to our remote sync daemon, Typha,
// which will feed the calculation graph with updates, bringing Felix into sync.
var syncer Startable
var typhaConnection *syncclient.SyncerClient
syncerToValidator := calc.NewSyncerCallbacksDecoupler()
if typhaAddr != "" {
// Use a remote Syncer, via the Typha server.
log.WithField("addr", typhaAddr).Info("Connecting to Typha.")
typhaConnection = syncclient.New(
typhaAddr,
buildinfo.GitVersion,
configParams.FelixHostname,
fmt.Sprintf("Revision: %s; Build date: %s",
buildinfo.GitRevision, buildinfo.BuildDate),
syncerToValidator,
&syncclient.Options{
ReadTimeout: configParams.TyphaReadTimeout,
WriteTimeout: configParams.TyphaWriteTimeout,
KeyFile: configParams.TyphaKeyFile,
CertFile: configParams.TyphaCertFile,
CAFile: configParams.TyphaCAFile,
ServerCN: configParams.TyphaCN,
ServerURISAN: configParams.TyphaURISAN,
},
)
} else {
// Use the syncer locally.
syncer = felixsyncer.New(backendClient, datastoreConfig.Spec, syncerToValidator)
}
log.WithField("syncer", syncer).Info("Created Syncer")
// Create the ipsets/active policy calculation graph, which will
// do the dynamic calculation of ipset memberships and active policies
// etc.
asyncCalcGraph := calc.NewAsyncCalcGraph(
configParams,
calcGraphClientChannels,
healthAggregator,
)
if configParams.UsageReportingEnabled {
// Usage reporting enabled, add stats collector to graph. When it detects an update
// to the stats, it makes a callback, which we use to send an update on a channel.
// We use a buffered channel here to avoid blocking the calculation graph.
statsChanIn := make(chan calc.StatsUpdate, 1)
statsCollector := calc.NewStatsCollector(func(stats calc.StatsUpdate) error {
statsChanIn <- stats
return nil
})
statsCollector.RegisterWith(asyncCalcGraph.CalcGraph)
// Rather than sending the updates directly to the usage reporting thread, we
// decouple with an extra goroutine. This prevents blocking the calculation graph
// goroutine if the usage reporting goroutine is blocked on IO, for example.
// Using a buffered channel wouldn't work here because the usage reporting
// goroutine can block for a long time on IO so we could build up a long queue.
statsChanOut := make(chan calc.StatsUpdate)
go func() {
var statsChanOutOrNil chan calc.StatsUpdate
var stats calc.StatsUpdate
for {
select {
case stats = <-statsChanIn:
// Got a stats update, activate the output channel.
log.WithField("stats", stats).Debug("Buffer: stats update received")
statsChanOutOrNil = statsChanOut
case statsChanOutOrNil <- stats:
// Passed on the update, deactivate the output channel until
// the next update.
log.WithField("stats", stats).Debug("Buffer: stats update sent")
statsChanOutOrNil = nil
}
}
}()
usageRep := usagerep.New(
configParams.UsageReportingInitialDelaySecs,
configParams.UsageReportingIntervalSecs,
statsChanOut,
connToUsageRepUpdChan,
)
go usageRep.PeriodicallyReportUsage(context.Background())
} else {
// Usage reporting disabled, but we still want a stats collector for the
// felix_cluster_* metrics. Register a no-op function as the callback.
statsCollector := calc.NewStatsCollector(func(stats calc.StatsUpdate) error {
return nil
})
statsCollector.RegisterWith(asyncCalcGraph.CalcGraph)
}
// Create the validator, which sits between the syncer and the
// calculation graph.
validator := calc.NewValidationFilter(asyncCalcGraph)
// Start the background processing threads.
if syncer != nil {
log.Infof("Starting the datastore Syncer")
syncer.Start()
} else {
log.Infof("Starting the Typha connection")
err := typhaConnection.Start(context.Background())
if err != nil {
log.WithError(err).Error("Failed to connect to Typha. Retrying...")
startTime := time.Now()
for err != nil && time.Since(startTime) < 30*time.Second {
// Set Ready to false and Live to true when unable to connect to typha
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: false})
err = typhaConnection.Start(context.Background())
if err == nil {
break
}
log.WithError(err).Debug("Retrying Typha connection")
time.Sleep(1 * time.Second)
}
if err != nil {
log.WithError(err).Fatal("Failed to connect to Typha")
} else {
log.Info("Connected to Typha after retries.")
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: true})
}
}
go func() {
typhaConnection.Finished.Wait()
failureReportChan <- "Connection to Typha failed"
}()
}
go syncerToValidator.SendTo(validator)
asyncCalcGraph.Start()
log.Infof("Started the processing graph")
var stopSignalChans []chan<- *sync.WaitGroup
if configParams.EndpointReportingEnabled {
delay := configParams.EndpointReportingDelaySecs
log.WithField("delay", delay).Info(
"Endpoint status reporting enabled, starting status reporter")
dpConnector.statusReporter = statusrep.NewEndpointStatusReporter(
configParams.FelixHostname,
configParams.OpenstackRegion,
dpConnector.StatusUpdatesFromDataplane,
dpConnector.InSync,
dpConnector.datastore,
delay,
delay*180,
)
dpConnector.statusReporter.Start()
}
// Start communicating with the dataplane driver.
dpConnector.Start()
if policySyncProcessor != nil {
log.WithField("policySyncPathPrefix", configParams.PolicySyncPathPrefix).Info(
"Policy sync API enabled. Starting the policy sync server.")
policySyncProcessor.Start()
sc := make(chan *sync.WaitGroup)
stopSignalChans = append(stopSignalChans, sc)
go policySyncAPIBinder.SearchAndBind(sc)
}
// Send the opening message to the dataplane driver, giving it its
// config.
dpConnector.ToDataplane <- &proto.ConfigUpdate{
Config: configParams.RawValues(),
}
if configParams.PrometheusMetricsEnabled {
log.Info("Prometheus metrics enabled. Starting server.")
gaugeHost := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "felix_host",
Help: "Configured Felix hostname (as a label), typically used in grouping/aggregating stats; the label defaults to the hostname of the host but can be overridden by configuration. The value of the gauge is always set to 1.",
ConstLabels: prometheus.Labels{"host": configParams.FelixHostname},
})
gaugeHost.Set(1)
prometheus.MustRegister(gaugeHost)
go servePrometheusMetrics(configParams)
}
// Register signal handlers to dump memory/CPU profiles.
logutils.RegisterProfilingSignalHandlers(configParams)
// Now monitor the worker process and our worker threads and shut
// down the process gracefully if they fail.
monitorAndManageShutdown(failureReportChan, dpDriverCmd, stopSignalChans)
}
func servePrometheusMetrics(configParams *config.Config) {
for {
log.WithFields(log.Fields{
"host": configParams.PrometheusMetricsHost,
"port": configParams.PrometheusMetricsPort,
}).Info("Starting prometheus metrics endpoint")
if configParams.PrometheusGoMetricsEnabled && configParams.PrometheusProcessMetricsEnabled {
log.Info("Including Golang & Process metrics")
} else {
if !configParams.PrometheusGoMetricsEnabled {
log.Info("Discarding Golang metrics")
prometheus.Unregister(prometheus.NewGoCollector())
}
if !configParams.PrometheusProcessMetricsEnabled {
log.Info("Discarding process metrics")
prometheus.Unregister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
}
}
http.Handle("/metrics", promhttp.Handler())
err := http.ListenAndServe(net.JoinHostPort(configParams.PrometheusMetricsHost, strconv.Itoa(configParams.PrometheusMetricsPort)), nil)
log.WithError(err).Error(
"Prometheus metrics endpoint failed, trying to restart it...")
time.Sleep(1 * time.Second)
}
}
func monitorAndManageShutdown(failureReportChan <-chan string, driverCmd *exec.Cmd, stopSignalChans []chan<- *sync.WaitGroup) {
// Ask the runtime to tell us if we get a term/int signal.
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM)
signal.Notify(signalChan, syscall.SIGINT)
signal.Notify(signalChan, syscall.SIGHUP)
// Start a background thread to tell us when the dataplane driver stops.
// If the driver stops unexpectedly, we'll terminate this process.
// If this process needs to stop, we'll kill the driver and then wait
// for the message from the background thread.
driverStoppedC := make(chan bool)
go func() {
if driverCmd == nil {
log.Info("No driver process to monitor")
return
}
err := driverCmd.Wait()
log.WithError(err).Warn("Driver process stopped")
driverStoppedC <- true
}()
// Wait for one of the channels to give us a reason to shut down.
driverAlreadyStopped := driverCmd == nil
receivedFatalSignal := false
var reason string
select {
case <-driverStoppedC:
reason = "Driver stopped"
driverAlreadyStopped = true
case sig := <-signalChan:
if sig == syscall.SIGHUP {
log.Warning("Received a SIGHUP, treating as a request to reload config")
reason = reasonConfigChanged
} else {
reason = fmt.Sprintf("Received OS signal %v", sig)
receivedFatalSignal = true
}
case reason = <-failureReportChan:
}
logCxt := log.WithField("reason", reason)
logCxt.Warn("Felix is shutting down")
// Notify other components to stop. Each notified component must call Done() on the wait
// group when it has completed its shutdown.
var stopWG sync.WaitGroup
for _, c := range stopSignalChans {
stopWG.Add(1)
select {
case c <- &stopWG:
default:
stopWG.Done()
}
}
stopWG.Wait()
if !driverAlreadyStopped {
// Driver may still be running, just in case the driver is
// unresponsive, start a thread to kill this process if we
// don't manage to kill the driver.
logCxt.Info("Driver still running, trying to shut it down...")
giveUpOnSigTerm := make(chan bool)
go func() {
time.Sleep(4 * time.Second)
giveUpOnSigTerm <- true
time.Sleep(1 * time.Second)
log.Fatal("Failed to wait for driver to exit, giving up.")
}()
// Signal to the driver to exit.
driverCmd.Process.Signal(syscall.SIGTERM)
select {
case <-driverStoppedC:
logCxt.Info("Driver shut down after SIGTERM")
case <-giveUpOnSigTerm:
logCxt.Error("Driver did not respond to SIGTERM, sending SIGKILL")
driverCmd.Process.Kill()
<-driverStoppedC
logCxt.Info("Driver shut down after SIGKILL")
}
}
if !receivedFatalSignal {
// We're exiting due to a failure or a config change, wait
// a couple of seconds to ensure that we don't go into a tight
// restart loop (which would make the init daemon in calico/node give
// up trying to restart us).
logCxt.Info("Sleeping to avoid tight restart loop.")
go func() {
time.Sleep(2 * time.Second)
if reason == reasonConfigChanged {
exitWithCustomRC(configChangedRC, "Exiting for config change")
return
}
logCxt.Fatal("Exiting.")
}()
for {
sig := <-signalChan
if sig == syscall.SIGHUP {
logCxt.Warning("Ignoring SIGHUP because we're already shutting down")
continue
}
logCxt.WithField("signal", sig).Fatal(
"Signal received while shutting down, exiting immediately")
}
}
logCxt.Fatal("Exiting immediately")
}
func exitWithCustomRC(rc int, message string) {
// Since log writing is done a background thread, we set the force-flush flag on this log to ensure that
// all the in-flight logs get written before we exit.
log.WithFields(log.Fields{
"rc": rc,
lclogutils.FieldForceFlush: true,
}).Info(message)
os.Exit(rc)
}
var (
ErrNotReady = errors.New("datastore is not ready or has not been initialised")
)
func loadConfigFromDatastore(
ctx context.Context, client bapi.Client, hostname string,
) (globalConfig, hostConfig map[string]string, err error) {
// The configuration is split over 3 different resource types and 4 different resource
// instances in the v3 data model:
// - ClusterInformation (global): name "default"
// - FelixConfiguration (global): name "default"
// - FelixConfiguration (per-host): name "node.<hostname>"
// - Node (per-host): name: <hostname>
// Get the global values and host specific values separately. We re-use the updateprocessor
// logic to convert the single v3 resource to a set of v1 key/values.
hostConfig = make(map[string]string)
globalConfig = make(map[string]string)
var ready bool
err = getAndMergeConfig(
ctx, client, globalConfig,
apiv3.KindClusterInformation, "default",
updateprocessors.NewClusterInfoUpdateProcessor(),
&ready,
)
if err != nil {
return
}
if !ready {
// The ClusterInformation struct should contain the ready flag, if it is not set, abort.
err = ErrNotReady
return
}
err = getAndMergeConfig(
ctx, client, globalConfig,
apiv3.KindFelixConfiguration, "default",
updateprocessors.NewFelixConfigUpdateProcessor(),
&ready,
)
if err != nil {
return
}
err = getAndMergeConfig(
ctx, client, hostConfig,
apiv3.KindFelixConfiguration, "node."+hostname,
updateprocessors.NewFelixConfigUpdateProcessor(),
&ready,
)
if err != nil {
return
}
err = getAndMergeConfig(
ctx, client, hostConfig,
apiv3.KindNode, hostname,
updateprocessors.NewFelixNodeUpdateProcessor(),
&ready,
)
if err != nil {
return
}
return
}
// getAndMergeConfig gets the v3 resource configuration extracts the separate config values
// (where each configuration value is stored in a field of the v3 resource Spec) and merges into
// the supplied map, as required by our v1-style configuration loader.
func getAndMergeConfig(
ctx context.Context, client bapi.Client, config map[string]string,
kind string, name string,
configConverter watchersyncer.SyncerUpdateProcessor,
ready *bool,
) error {
logCxt := log.WithFields(log.Fields{"kind": kind, "name": name})
cfg, err := client.Get(ctx, model.ResourceKey{
Kind: kind,
Name: name,
Namespace: "",
}, "")
if err != nil {
switch err.(type) {
case cerrors.ErrorResourceDoesNotExist:
logCxt.Info("No config of this type")
return nil
default:
logCxt.WithError(err).Info("Failed to load config from datastore")
return err
}
}
// Re-use the update processor logic implemented for the Syncer. We give it a v3 config
// object in a KVPair and it uses the annotations defined on it to split it into v1-style
// KV pairs. Log any errors - but don't fail completely to avoid cyclic restarts.
v1kvs, err := configConverter.Process(cfg)
if err != nil {
logCxt.WithError(err).Error("Failed to convert configuration")
}
// Loop through the converted values and update our config map with values from either the
// Global or Host configs.
for _, v1KV := range v1kvs {
if _, ok := v1KV.Key.(model.ReadyFlagKey); ok {
logCxt.WithField("ready", v1KV.Value).Info("Loaded ready flag")
if v1KV.Value == true {
*ready = true
}
} else if v1KV.Value != nil {
switch k := v1KV.Key.(type) {
case model.GlobalConfigKey:
config[k.Name] = v1KV.Value.(string)
case model.HostConfigKey:
config[k.Name] = v1KV.Value.(string)
default:
logCxt.WithField("KV", v1KV).Debug("Skipping config - not required for initial loading")
}
}
}
return nil
}
type DataplaneConnector struct {
config *config.Config
configUpdChan chan<- map[string]string
ToDataplane chan interface{}
StatusUpdatesFromDataplane chan interface{}
InSync chan bool
failureReportChan chan<- string
dataplane dp.DataplaneDriver
datastore bapi.Client
statusReporter *statusrep.EndpointStatusReporter
datastoreInSync bool
firstStatusReportSent bool
}
type Startable interface {
Start()
}
func newConnector(configParams *config.Config,
configUpdChan chan<- map[string]string,
datastore bapi.Client,
dataplane dp.DataplaneDriver,
failureReportChan chan<- string,
) *DataplaneConnector {
felixConn := &DataplaneConnector{
config: configParams,
configUpdChan: configUpdChan,
datastore: datastore,
ToDataplane: make(chan interface{}),
StatusUpdatesFromDataplane: make(chan interface{}),
InSync: make(chan bool, 1),
failureReportChan: failureReportChan,
dataplane: dataplane,
}
return felixConn
}
func (fc *DataplaneConnector) readMessagesFromDataplane() {
defer func() {
fc.shutDownProcess("Failed to read messages from dataplane")
}()
log.Info("Reading from dataplane driver pipe...")
ctx := context.Background()
for {
payload, err := fc.dataplane.RecvMessage()
if err != nil {
log.WithError(err).Error("Failed to read from front-end socket")
fc.shutDownProcess("Failed to read from front-end socket")
}
log.WithField("payload", payload).Debug("New message from dataplane")
switch msg := payload.(type) {
case *proto.ProcessStatusUpdate:
fc.handleProcessStatusUpdate(ctx, msg)
case *proto.WorkloadEndpointStatusUpdate:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
case *proto.WorkloadEndpointStatusRemove:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
case *proto.HostEndpointStatusUpdate:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
case *proto.HostEndpointStatusRemove:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
default:
log.WithField("msg", msg).Warning("Unknown message from dataplane")
}
log.Debug("Finished handling message from front-end")
}
}
func (fc *DataplaneConnector) handleProcessStatusUpdate(ctx context.Context, msg *proto.ProcessStatusUpdate) {
log.Debugf("Status update from dataplane driver: %v", *msg)
statusReport := model.StatusReport{
Timestamp: msg.IsoTimestamp,
UptimeSeconds: msg.Uptime,
FirstUpdate: !fc.firstStatusReportSent,
}
kv := model.KVPair{
Key: model.ActiveStatusReportKey{Hostname: fc.config.FelixHostname, RegionString: model.RegionString(fc.config.OpenstackRegion)},
Value: &statusReport,
TTL: fc.config.ReportingTTLSecs,
}
applyCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
_, err := fc.datastore.Apply(applyCtx, &kv)
cancel()
if err != nil {
if _, ok := err.(cerrors.ErrorOperationNotSupported); ok {
log.Debug("Datastore doesn't support status reports.")
return // and it won't support the last status key either.
} else {
log.Warningf("Failed to write status to datastore: %v", err)
}
} else {
fc.firstStatusReportSent = true
}
kv = model.KVPair{
Key: model.LastStatusReportKey{Hostname: fc.config.FelixHostname, RegionString: model.RegionString(fc.config.OpenstackRegion)},
Value: &statusReport,
}
applyCtx, cancel = context.WithTimeout(ctx, 2*time.Second)
_, err = fc.datastore.Apply(applyCtx, &kv)
cancel()
if err != nil {
log.Warningf("Failed to write status to datastore: %v", err)
}
}
var handledConfigChanges = set.From("CalicoVersion", "ClusterGUID", "ClusterType")
func (fc *DataplaneConnector) sendMessagesToDataplaneDriver() {
defer func() {
fc.shutDownProcess("Failed to send messages to dataplane")
}()
var config map[string]string
for {
msg := <-fc.ToDataplane
switch msg := msg.(type) {
case *proto.InSync:
log.Info("Datastore now in sync.")
if !fc.datastoreInSync {
log.Info("Datastore in sync for first time, sending message to status reporter.")
fc.datastoreInSync = true
fc.InSync <- true
}
case *proto.ConfigUpdate:
if config != nil {
log.WithFields(log.Fields{
"old": config,
"new": msg.Config,
}).Info("Config updated, checking whether we need to restart")
restartNeeded := false
for kNew, vNew := range msg.Config {
logCxt := log.WithFields(log.Fields{"key": kNew, "new": vNew})
if vOld, prs := config[kNew]; !prs {
logCxt = logCxt.WithField("updateType", "add")
} else if vNew != vOld {
logCxt = logCxt.WithFields(log.Fields{"old": vOld, "updateType": "update"})
} else {
continue
}
if handledConfigChanges.Contains(kNew) {
logCxt.Info("Config change can be handled without restart")
continue
}
logCxt.Warning("Config change requires restart")
restartNeeded = true
}
for kOld, vOld := range config {
logCxt := log.WithFields(log.Fields{"key": kOld, "old": vOld, "updateType": "delete"})
if _, prs := msg.Config[kOld]; prs {
// Key was present in the message so we've handled above.
continue
}
if handledConfigChanges.Contains(kOld) {
logCxt.Info("Config change can be handled without restart")
continue
}
logCxt.Warning("Config change requires restart")
restartNeeded = true
}
if restartNeeded {
fc.shutDownProcess("config changed")
}
}
// Take a copy of the config to compare against next time.
config = make(map[string]string)
for k, v := range msg.Config {
config[k] = v
}
if fc.configUpdChan != nil {
// Send the config over to the usage reporter.
fc.configUpdChan <- config
}
case *calc.DatastoreNotReady:
log.Warn("Datastore became unready, need to restart.")
fc.shutDownProcess("datastore became unready")
}
if err := fc.dataplane.SendMessage(msg); err != nil {
fc.shutDownProcess("Failed to write to dataplane driver")
}
}
}
func (fc *DataplaneConnector) shutDownProcess(reason string) {
// Send a failure report to the managed shutdown thread then give it
// a few seconds to do the shutdown.
fc.failureReportChan <- reason
time.Sleep(5 * time.Second)
// The graceful shutdown failed, terminate the process.
log.Panic("Managed shutdown failed. Panicking.")
}
func (fc *DataplaneConnector) Start() {
// Start a background thread to write to the dataplane driver.
go fc.sendMessagesToDataplaneDriver()
// Start background thread to read messages from dataplane driver.
go fc.readMessagesFromDataplane()
}
var ErrServiceNotReady = errors.New("Kubernetes service missing IP or port.")
func discoverTyphaAddr(configParams *config.Config, getKubernetesService func(namespace, name string) (*v1.Service, error)) (string, error) {
if configParams.TyphaAddr != "" {
// Explicit address; trumps other sources of config.
return configParams.TyphaAddr, nil
}
if configParams.TyphaK8sServiceName == "" {
// No explicit address, and no service name, not using Typha.
return "", nil
}
// If we get here, we need to look up the Typha service using the k8s API.
// TODO Typha: support Typha lookup without using rest.InClusterConfig().
svc, err := getKubernetesService(configParams.TyphaK8sNamespace, configParams.TyphaK8sServiceName)
if err != nil {
log.WithError(err).Error("Unable to get Typha service from Kubernetes.")
return "", err
}
host := svc.Spec.ClusterIP
log.WithField("clusterIP", host).Info("Found Typha ClusterIP.")
if host == "" {
log.WithError(err).Error("Typha service had no ClusterIP.")
return "", ErrServiceNotReady
}
for _, p := range svc.Spec.Ports {
if p.Name == "calico-typha" {
log.WithField("port", p).Info("Found Typha service port.")
typhaAddr := net.JoinHostPort(host, fmt.Sprintf("%v", p.Port))
return typhaAddr, nil
}
}
log.Error("Didn't find Typha service port.")
return "", ErrServiceNotReady
}
| 1 | 16,724 | I think same here - in general we don't need to use Setters / Getters since configParams isn't a public API. | projectcalico-felix | c |
@@ -62,8 +62,13 @@ func main() {
ddata, err := ioutil.ReadFile(os.Args[3])
failFast(err)
+ programstr := fmt.Sprintf("%s", pdata)
+
+ programbytes, err := logic.AssembleString(programstr)
+ failFast(err)
+
dsig := sec.Sign(logic.Msg{
- ProgramHash: crypto.HashObj(logic.Program(pdata)),
+ ProgramHash: crypto.HashObj(logic.Program(programbytes)),
Data: ddata,
})
| 1 | // Copyright (C) 2019-2020 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/>.
// dsign creates keys for signing data in LogicSig scripts.
//
// dsign creates signatures on data that will verify under
// the LogicSig ed25519verify opcode.
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/data/transactions/logic"
"github.com/algorand/go-algorand/protocol"
)
func failFast(err error) {
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) != 3 && len(os.Args) != 4 {
fmt.Fprintf(os.Stderr, "usage: %s <key-file> <lsig-file> <optional-data-file>\n", os.Args[0])
os.Exit(-1)
}
keyfname := os.Args[1]
lsigfname := os.Args[2]
kdata, err := ioutil.ReadFile(keyfname)
failFast(err)
var seed crypto.Seed
copy(seed[:], kdata)
sec := crypto.GenerateSignatureSecrets(seed)
if len(os.Args) == 4 {
// In this mode, interpret lsig-file as raw program bytes and produce a signature
// over the data file
pdata, err := ioutil.ReadFile(lsigfname)
failFast(err)
ddata, err := ioutil.ReadFile(os.Args[3])
failFast(err)
dsig := sec.Sign(logic.Msg{
ProgramHash: crypto.HashObj(logic.Program(pdata)),
Data: ddata,
})
fmt.Fprintf(os.Stdout, "%s", base64.StdEncoding.EncodeToString(dsig[:]))
} else {
// In this mode, interpret lsig-file as a LogicSig struct and sign the
// txid of the transaction passed over stdin
pdata, err := ioutil.ReadFile(lsigfname)
failFast(err)
var lsig transactions.LogicSig
err = protocol.Decode(pdata, &lsig)
failFast(err)
txdata, err := ioutil.ReadAll(os.Stdin)
failFast(err)
var txn transactions.SignedTxn
err = protocol.Decode(txdata, &txn)
failFast(err)
txID := txn.ID()
dsig := sec.Sign(logic.Msg{
ProgramHash: crypto.HashObj(logic.Program(lsig.Logic)),
Data: txID[:],
})
lsig.Args = [][]byte{dsig[:]}
var out transactions.SignedTxn
out.Txn = txn.Txn
out.Lsig = lsig
protocol.EncodeStream(os.Stdout, out)
}
}
| 1 | 37,355 | Why using `fmt.Sprintf` where `fmt.Sprint` would do the work (notice no `f` in function name)? | algorand-go-algorand | go |
@@ -257,6 +257,12 @@ class VirtualBufferTextInfo(browseMode.BrowseModeDocumentTextInfo,textInfos.offs
return lineStart.value,lineEnd.value
def _normalizeControlField(self,attrs):
+
+ ariaCurrent = attrs.get("IAccessible2::attribute_current")
+ if ariaCurrent != None:
+ attrs['current']= ariaCurrent
+ del attrs["IAccessible2::attribute_current"]
+
tableLayout=attrs.get('table-layout')
if tableLayout:
attrs['table-layout']=tableLayout=="1" | 1 | # -*- coding: UTF-8 -*-
#virtualBuffers/__init__.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2007-2015 NV Access Limited, Peter Vágner
import time
import threading
import ctypes
import collections
import itertools
import weakref
import wx
import review
import NVDAHelper
import XMLFormatting
import scriptHandler
from scriptHandler import isScriptWaiting, willSayAllResume
import speech
import NVDAObjects
import api
import sayAllHandler
import controlTypes
import textInfos.offsets
import config
import cursorManager
import browseMode
import gui
import eventHandler
import braille
import queueHandler
from logHandler import log
import ui
import aria
import nvwave
import treeInterceptorHandler
import watchdog
VBufStorage_findDirection_forward=0
VBufStorage_findDirection_back=1
VBufStorage_findDirection_up=2
VBufRemote_nodeHandle_t=ctypes.c_ulonglong
class VBufStorage_findMatch_word(unicode):
pass
VBufStorage_findMatch_notEmpty = object()
FINDBYATTRIBS_ESCAPE_TABLE = {
# Symbols that are escaped in the attributes string.
ord(u":"): ur"\\:",
ord(u";"): ur"\\;",
ord(u"\\"): u"\\\\\\\\",
}
# Symbols that must be escaped for a regular expression.
FINDBYATTRIBS_ESCAPE_TABLE.update({(ord(s), u"\\" + s) for s in u"^$.*+?()[]{}|"})
def _prepareForFindByAttributes(attribs):
escape = lambda text: unicode(text).translate(FINDBYATTRIBS_ESCAPE_TABLE)
reqAttrs = []
regexp = []
if isinstance(attribs, dict):
# Single option.
attribs = (attribs,)
# All options will match against all requested attributes,
# so first build the list of requested attributes.
for option in attribs:
for name in option:
reqAttrs.append(unicode(name))
# Now build the regular expression.
for option in attribs:
optRegexp = []
for name in reqAttrs:
optRegexp.append("%s:" % escape(name))
values = option.get(name)
if not values:
# The value isn't tested for this attribute, so match any (or no) value.
optRegexp.append(r"(?:\\;|[^;])*;")
elif values[0] is VBufStorage_findMatch_notEmpty:
# There must be a value for this attribute.
optRegexp.append(r"(?:\\;|[^;])+;")
elif isinstance(values[0], VBufStorage_findMatch_word):
# Assume all are word matches.
optRegexp.append(r"(?:\\;|[^;])*\b(?:")
optRegexp.append("|".join(escape(val) for val in values))
optRegexp.append(r")\b(?:\\;|[^;])*;")
else:
# Assume all are exact matches or None (must not exist).
optRegexp.append("(?:" )
optRegexp.append("|".join((escape(val)+u';') if val is not None else u';' for val in values))
optRegexp.append(")")
regexp.append("".join(optRegexp))
return u" ".join(reqAttrs), u"|".join(regexp)
class VirtualBufferQuickNavItem(browseMode.TextInfoQuickNavItem):
def __init__(self,itemType,document,vbufNode,startOffset,endOffset):
textInfo=document.makeTextInfo(textInfos.offsets.Offsets(startOffset,endOffset))
super(VirtualBufferQuickNavItem,self).__init__(itemType,document,textInfo)
docHandle=ctypes.c_int()
ID=ctypes.c_int()
NVDAHelper.localLib.VBuf_getIdentifierFromControlFieldNode(document.VBufHandle, vbufNode, ctypes.byref(docHandle), ctypes.byref(ID))
self.vbufFieldIdentifier=(docHandle.value,ID.value)
self.vbufNode=vbufNode
@property
def obj(self):
return self.document.getNVDAObjectFromIdentifier(*self.vbufFieldIdentifier)
@property
def label(self):
if self.itemType == "landmark":
attrs = self.textInfo._getControlFieldAttribs(self.vbufFieldIdentifier[0], self.vbufFieldIdentifier[1])
name = attrs.get("name", "")
if name:
name += " "
return name + aria.landmarkRoles[attrs["landmark"]]
else:
return super(VirtualBufferQuickNavItem,self).label
def isChild(self,parent):
if self.itemType == "heading":
try:
if (int(self.textInfo._getControlFieldAttribs(self.vbufFieldIdentifier[0], self.vbufFieldIdentifier[1])["level"])
> int(parent.textInfo._getControlFieldAttribs(parent.vbufFieldIdentifier[0], parent.vbufFieldIdentifier[1])["level"])):
return True
except (KeyError, ValueError, TypeError):
return False
return super(VirtualBufferQuickNavItem,self).isChild(parent)
class VirtualBufferTextInfo(browseMode.BrowseModeDocumentTextInfo,textInfos.offsets.OffsetsTextInfo):
allowMoveToOffsetPastEnd=False #: no need for end insertion point as vbuf is not editable.
UNIT_CONTROLFIELD = "controlField"
def _getControlFieldAttribs(self, docHandle, id):
info = self.copy()
info.expand(textInfos.UNIT_CHARACTER)
for field in reversed(info.getTextWithFields()):
if not (isinstance(field, textInfos.FieldCommand) and field.command == "controlStart"):
# Not a control field.
continue
attrs = field.field
if int(attrs["controlIdentifier_docHandle"]) == docHandle and int(attrs["controlIdentifier_ID"]) == id:
return attrs
raise LookupError
def _getFieldIdentifierFromOffset(self, offset):
startOffset = ctypes.c_int()
endOffset = ctypes.c_int()
docHandle = ctypes.c_int()
ID = ctypes.c_int()
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_locateControlFieldNodeAtOffset(self.obj.VBufHandle, offset, ctypes.byref(startOffset), ctypes.byref(endOffset), ctypes.byref(docHandle), ctypes.byref(ID),ctypes.byref(node))
return docHandle.value, ID.value
def _getOffsetsFromFieldIdentifier(self, docHandle, ID):
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_getControlFieldNodeWithIdentifier(self.obj.VBufHandle, docHandle, ID,ctypes.byref(node))
if not node:
raise LookupError
start = ctypes.c_int()
end = ctypes.c_int()
NVDAHelper.localLib.VBuf_getFieldNodeOffsets(self.obj.VBufHandle, node, ctypes.byref(start), ctypes.byref(end))
return start.value, end.value
def _getPointFromOffset(self,offset):
o = self._getNVDAObjectFromOffset(offset)
left, top, width, height = o.location
return textInfos.Point(left + width / 2, top + height / 2)
def _getNVDAObjectFromOffset(self,offset):
docHandle,ID=self._getFieldIdentifierFromOffset(offset)
return self.obj.getNVDAObjectFromIdentifier(docHandle,ID)
def _getOffsetsFromNVDAObjectInBuffer(self,obj):
docHandle,ID=self.obj.getIdentifierFromNVDAObject(obj)
return self._getOffsetsFromFieldIdentifier(docHandle,ID)
def _getOffsetsFromNVDAObject(self, obj):
while True:
try:
return self._getOffsetsFromNVDAObjectInBuffer(obj)
except LookupError:
pass
# Interactive list/combo box/tree view descendants aren't rendered into the buffer, even though they are still considered part of it.
# Use the container in this case.
obj = obj.parent
if not obj or obj.role not in (controlTypes.ROLE_LIST, controlTypes.ROLE_COMBOBOX, controlTypes.ROLE_GROUPING, controlTypes.ROLE_TREEVIEW, controlTypes.ROLE_TREEVIEWITEM):
break
raise LookupError
def __init__(self,obj,position):
self.obj=obj
super(VirtualBufferTextInfo,self).__init__(obj,position)
def _getSelectionOffsets(self):
start=ctypes.c_int()
end=ctypes.c_int()
NVDAHelper.localLib.VBuf_getSelectionOffsets(self.obj.VBufHandle,ctypes.byref(start),ctypes.byref(end))
return start.value,end.value
def _setSelectionOffsets(self,start,end):
NVDAHelper.localLib.VBuf_setSelectionOffsets(self.obj.VBufHandle,start,end)
def _getCaretOffset(self):
return self._getSelectionOffsets()[0]
def _setCaretOffset(self,offset):
return self._setSelectionOffsets(offset,offset)
def _getStoryLength(self):
return NVDAHelper.localLib.VBuf_getTextLength(self.obj.VBufHandle)
def _getTextRange(self,start,end):
if start==end:
return u""
return NVDAHelper.VBuf_getTextInRange(self.obj.VBufHandle,start,end,False) or u""
def getTextWithFields(self,formatConfig=None):
start=self._startOffset
end=self._endOffset
if start==end:
return ""
text=NVDAHelper.VBuf_getTextInRange(self.obj.VBufHandle,start,end,True)
if not text:
return ""
commandList=XMLFormatting.XMLTextParser().parse(text)
for index in xrange(len(commandList)):
if isinstance(commandList[index],textInfos.FieldCommand):
field=commandList[index].field
if isinstance(field,textInfos.ControlField):
commandList[index].field=self._normalizeControlField(field)
elif isinstance(field,textInfos.FormatField):
commandList[index].field=self._normalizeFormatField(field)
return commandList
def _getWordOffsets(self,offset):
#Use VBuf_getBufferLineOffsets with out screen layout to find out the range of the current field
lineStart=ctypes.c_int()
lineEnd=ctypes.c_int()
NVDAHelper.localLib.VBuf_getLineOffsets(self.obj.VBufHandle,offset,0,False,ctypes.byref(lineStart),ctypes.byref(lineEnd))
word_startOffset,word_endOffset=super(VirtualBufferTextInfo,self)._getWordOffsets(offset)
return (max(lineStart.value,word_startOffset),min(lineEnd.value,word_endOffset))
def _getLineOffsets(self,offset):
lineStart=ctypes.c_int()
lineEnd=ctypes.c_int()
NVDAHelper.localLib.VBuf_getLineOffsets(self.obj.VBufHandle,offset,config.conf["virtualBuffers"]["maxLineLength"],config.conf["virtualBuffers"]["useScreenLayout"],ctypes.byref(lineStart),ctypes.byref(lineEnd))
return lineStart.value,lineEnd.value
def _getParagraphOffsets(self,offset):
lineStart=ctypes.c_int()
lineEnd=ctypes.c_int()
NVDAHelper.localLib.VBuf_getLineOffsets(self.obj.VBufHandle,offset,0,True,ctypes.byref(lineStart),ctypes.byref(lineEnd))
return lineStart.value,lineEnd.value
def _normalizeControlField(self,attrs):
tableLayout=attrs.get('table-layout')
if tableLayout:
attrs['table-layout']=tableLayout=="1"
isHidden=attrs.get('isHidden')
if isHidden:
attrs['isHidden']=isHidden=="1"
# Handle table row and column headers.
for axis in "row", "column":
attr = attrs.pop("table-%sheadercells" % axis, None)
if not attr:
continue
cellIdentifiers = [identifier.split(",") for identifier in attr.split(";") if identifier]
# Get the text for the header cells.
textList = []
for docHandle, ID in cellIdentifiers:
try:
start, end = self._getOffsetsFromFieldIdentifier(int(docHandle), int(ID))
except (LookupError, ValueError):
continue
textList.append(self.obj.makeTextInfo(textInfos.offsets.Offsets(start, end)).text)
attrs["table-%sheadertext" % axis] = "\n".join(textList)
if attrs.get("landmark") == "region" and not attrs.get("name"):
# We only consider region to be a landmark if it has a name.
del attrs["landmark"]
# Expose a unique ID on the controlField for quick and safe comparison using the virtualBuffer field's docHandle and ID
docHandle=attrs.get('controlIdentifier_docHandle')
ID=attrs.get('controlIdentifier_ID')
if docHandle is not None and ID is not None:
attrs['uniqueID']=(docHandle,ID)
return attrs
def _normalizeFormatField(self, attrs):
return attrs
def _getLineNumFromOffset(self, offset):
return None
def _get_fieldIdentifierAtStart(self):
return self._getFieldIdentifierFromOffset( self._startOffset)
def _getUnitOffsets(self, unit, offset):
if unit == self.UNIT_CONTROLFIELD:
startOffset=ctypes.c_int()
endOffset=ctypes.c_int()
docHandle=ctypes.c_int()
ID=ctypes.c_int()
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_locateControlFieldNodeAtOffset(self.obj.VBufHandle,offset,ctypes.byref(startOffset),ctypes.byref(endOffset),ctypes.byref(docHandle),ctypes.byref(ID),ctypes.byref(node))
return startOffset.value,endOffset.value
return super(VirtualBufferTextInfo, self)._getUnitOffsets(unit, offset)
def _get_clipboardText(self):
# Blocks should start on a new line, but they don't necessarily have an end of line indicator.
# Therefore, get the text in block (paragraph) chunks and join the chunks with \r\n.
blocks = (block.strip("\r\n") for block in self.getTextInChunks(textInfos.UNIT_PARAGRAPH))
return "\r\n".join(blocks)
def activate(self):
self.obj._activatePosition(self)
def getMathMl(self, field):
docHandle = int(field["controlIdentifier_docHandle"])
nodeId = int(field["controlIdentifier_ID"])
obj = self.obj.getNVDAObjectFromIdentifier(docHandle, nodeId)
return obj.mathMl
class VirtualBuffer(browseMode.BrowseModeDocumentTreeInterceptor):
TextInfo=VirtualBufferTextInfo
#: Maps root identifiers (docHandle and ID) to buffers.
rootIdentifiers = weakref.WeakValueDictionary()
def __init__(self,rootNVDAObject,backendName=None):
super(VirtualBuffer,self).__init__(rootNVDAObject)
self.backendName=backendName
self.VBufHandle=None
self.isLoading=False
self.rootDocHandle,self.rootID=self.getIdentifierFromNVDAObject(self.rootNVDAObject)
self.rootIdentifiers[self.rootDocHandle, self.rootID] = self
def prepare(self):
self.shouldPrepare=False
self.loadBuffer()
def _get_shouldPrepare(self):
return not self.isLoading and not self.VBufHandle
def terminate(self):
super(VirtualBuffer,self).terminate()
if not self.VBufHandle:
return
self.unloadBuffer()
def _get_isReady(self):
return bool(self.VBufHandle and not self.isLoading)
def loadBuffer(self):
self.isLoading = True
self._loadProgressCallLater = wx.CallLater(1000, self._loadProgress)
threading.Thread(target=self._loadBuffer).start()
def _loadBuffer(self):
try:
self.VBufHandle=NVDAHelper.localLib.VBuf_createBuffer(self.rootNVDAObject.appModule.helperLocalBindingHandle,self.rootDocHandle,self.rootID,unicode(self.backendName))
if not self.VBufHandle:
raise RuntimeError("Could not remotely create virtualBuffer")
except:
log.error("", exc_info=True)
queueHandler.queueFunction(queueHandler.eventQueue, self._loadBufferDone, success=False)
return
queueHandler.queueFunction(queueHandler.eventQueue, self._loadBufferDone)
def _loadBufferDone(self, success=True):
self._loadProgressCallLater.Stop()
del self._loadProgressCallLater
self.isLoading = False
if not success:
self.passThrough=True
return
if self._hadFirstGainFocus:
# If this buffer has already had focus once while loaded, this is a refresh.
# Translators: Reported when a page reloads (example: after refreshing a webpage).
ui.message(_("Refreshed"))
if api.getFocusObject().treeInterceptor == self:
self.event_treeInterceptor_gainFocus()
def _loadProgress(self):
# Translators: Reported while loading a document.
ui.message(_("Loading document..."))
def unloadBuffer(self):
if self.VBufHandle is not None:
try:
watchdog.cancellableExecute(NVDAHelper.localLib.VBuf_destroyBuffer, ctypes.byref(ctypes.c_int(self.VBufHandle)))
except WindowsError:
pass
self.VBufHandle=None
def isNVDAObjectPartOfLayoutTable(self,obj):
docHandle,ID=self.getIdentifierFromNVDAObject(obj)
ID=unicode(ID)
info=self.makeTextInfo(obj)
info.collapse()
info.expand(textInfos.UNIT_CHARACTER)
fieldCommands=[x for x in info.getTextWithFields() if isinstance(x,textInfos.FieldCommand)]
tableLayout=None
tableID=None
for fieldCommand in fieldCommands:
fieldID=fieldCommand.field.get("controlIdentifier_ID") if fieldCommand.field else None
if fieldID==ID:
tableLayout=fieldCommand.field.get('table-layout')
if tableLayout is not None:
return tableLayout
tableID=fieldCommand.field.get('table-id')
break
if tableID is None:
return False
for fieldCommand in fieldCommands:
fieldID=fieldCommand.field.get("controlIdentifier_ID") if fieldCommand.field else None
if fieldID==tableID:
tableLayout=fieldCommand.field.get('table-layout',False)
break
return tableLayout
def getNVDAObjectFromIdentifier(self, docHandle, ID):
"""Retrieve an NVDAObject for a given node identifier.
Subclasses must override this method.
@param docHandle: The document handle.
@type docHandle: int
@param ID: The ID of the node.
@type ID: int
@return: The NVDAObject.
@rtype: L{NVDAObjects.NVDAObject}
"""
raise NotImplementedError
def getIdentifierFromNVDAObject(self,obj):
"""Retreaves the virtualBuffer field identifier from an NVDAObject.
@param obj: the NVDAObject to retreave the field identifier from.
@type obj: L{NVDAObject}
@returns: a the field identifier as a doc handle and ID paire.
@rtype: 2-tuple.
"""
raise NotImplementedError
def script_refreshBuffer(self,gesture):
if scriptHandler.isScriptWaiting():
# This script may cause subsequently queued scripts to fail, so don't execute.
return
self.unloadBuffer()
self.loadBuffer()
# Translators: the description for the refreshBuffer script on virtualBuffers.
script_refreshBuffer.__doc__ = _("Refreshes the document content")
def script_toggleScreenLayout(self,gesture):
config.conf["virtualBuffers"]["useScreenLayout"]=not config.conf["virtualBuffers"]["useScreenLayout"]
if config.conf["virtualBuffers"]["useScreenLayout"]:
# Translators: Presented when use screen layout option is toggled.
ui.message(_("Use screen layout on"))
else:
# Translators: Presented when use screen layout option is toggled.
ui.message(_("Use screen layout off"))
# Translators: the description for the toggleScreenLayout script on virtualBuffers.
script_toggleScreenLayout.__doc__ = _("Toggles on and off if the screen layout is preserved while rendering the document content")
def _searchableAttributesForNodeType(self,nodeType):
pass
def _iterNodesByType(self,nodeType,direction="next",pos=None):
attribs=self._searchableAttribsForNodeType(nodeType)
if not attribs:
raise NotImplementedError
return self._iterNodesByAttribs(attribs, direction, pos,nodeType)
def _iterNodesByAttribs(self, attribs, direction="next", pos=None,nodeType=None):
offset=pos._startOffset if pos else -1
reqAttrs, regexp = _prepareForFindByAttributes(attribs)
startOffset=ctypes.c_int()
endOffset=ctypes.c_int()
if direction=="next":
direction=VBufStorage_findDirection_forward
elif direction=="previous":
direction=VBufStorage_findDirection_back
elif direction=="up":
direction=VBufStorage_findDirection_up
else:
raise ValueError("unknown direction: %s"%direction)
while True:
try:
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_findNodeByAttributes(self.VBufHandle,offset,direction,reqAttrs,regexp,ctypes.byref(startOffset),ctypes.byref(endOffset),ctypes.byref(node))
except:
return
if not node:
return
yield VirtualBufferQuickNavItem(nodeType,self,node,startOffset.value,endOffset.value)
offset=startOffset
def _getTableCellCoords(self, info):
if info.isCollapsed:
info = info.copy()
info.expand(textInfos.UNIT_CHARACTER)
for field in reversed(info.getTextWithFields()):
if not (isinstance(field, textInfos.FieldCommand) and field.command == "controlStart"):
# Not a control field.
continue
attrs = field.field
if "table-id" in attrs and "table-rownumber" in attrs:
break
else:
raise LookupError("Not in a table cell")
return (int(attrs["table-id"]),
int(attrs["table-rownumber"]), int(attrs["table-columnnumber"]),
int(attrs.get("table-rowsspanned", 1)), int(attrs.get("table-columnsspanned", 1)))
def _iterTableCells(self, tableID, startPos=None, direction="next", row=None, column=None):
attrs = {"table-id": [str(tableID)]}
# row could be 0.
if row is not None:
attrs["table-rownumber"] = [str(row)]
if column is not None:
attrs["table-columnnumber"] = [str(column)]
results = self._iterNodesByAttribs(attrs, pos=startPos, direction=direction)
if not startPos and not row and not column and direction == "next":
# The first match will be the table itself, so skip it.
next(results)
for item in results:
yield item.textInfo
def _getNearestTableCell(self, tableID, startPos, origRow, origCol, origRowSpan, origColSpan, movement, axis):
if not axis:
# First or last.
if movement == "first":
startPos = None
direction = "next"
elif movement == "last":
startPos = self.makeTextInfo(textInfos.POSITION_LAST)
direction = "previous"
try:
return next(self._iterTableCells(tableID, startPos=startPos, direction=direction))
except StopIteration:
raise LookupError
# Determine destination row and column.
destRow = origRow
destCol = origCol
if axis == "row":
destRow += origRowSpan if movement == "next" else -1
elif axis == "column":
destCol += origColSpan if movement == "next" else -1
if destCol < 1:
# Optimisation: We're definitely at the edge of the column.
raise LookupError
# Optimisation: Try searching for exact destination coordinates.
# This won't work if they are covered by a cell spanning multiple rows/cols, but this won't be true in the majority of cases.
try:
return next(self._iterTableCells(tableID, row=destRow, column=destCol))
except StopIteration:
pass
# Cells are grouped by row, so in most cases, we simply need to search in the right direction.
for info in self._iterTableCells(tableID, direction=movement, startPos=startPos):
_ignore, row, col, rowSpan, colSpan = self._getTableCellCoords(info)
if row <= destRow < row + rowSpan and col <= destCol < col + colSpan:
return info
elif row > destRow and movement == "next":
# Optimisation: We've gone forward past destRow, so we know we won't find the cell.
# We can't reverse this logic when moving backwards because there might be a prior cell on an earlier row which spans multiple rows.
break
if axis == "row" or (axis == "column" and movement == "previous"):
# In most cases, there's nothing more to try.
raise LookupError
else:
# We're moving forward by column.
# In this case, there might be a cell on an earlier row which spans multiple rows.
# Therefore, try searching backwards.
for info in self._iterTableCells(tableID, direction="previous", startPos=startPos):
_ignore, row, col, rowSpan, colSpan = self._getTableCellCoords(info)
if row <= destRow < row + rowSpan and col <= destCol < col + colSpan:
return info
else:
raise LookupError
def _tableMovementScriptHelper(self, movement="next", axis=None):
if isScriptWaiting():
return
formatConfig=config.conf["documentFormatting"].copy()
formatConfig["reportTables"]=True
formatConfig["includeLayoutTables"]=True
try:
tableID, origRow, origCol, origRowSpan, origColSpan = self._getTableCellCoords(self.selection)
except LookupError:
# Translators: The message reported when a user attempts to use a table movement command
# when the cursor is not within a table.
ui.message(_("Not in a table cell"))
return
try:
info = self._getNearestTableCell(tableID, self.selection, origRow, origCol, origRowSpan, origColSpan, movement, axis)
except LookupError:
# Translators: The message reported when a user attempts to use a table movement command
# but the cursor can't be moved in that direction because it is at the edge of the table.
ui.message(_("Edge of table"))
# Retrieve the cell on which we started.
info = next(self._iterTableCells(tableID, row=origRow, column=origCol))
speech.speakTextInfo(info,formatConfig=formatConfig,reason=controlTypes.REASON_CARET)
info.collapse()
self.selection = info
def script_nextRow(self, gesture):
self._tableMovementScriptHelper(axis="row", movement="next")
# Translators: the description for the next table row script on virtualBuffers.
script_nextRow.__doc__ = _("moves to the next table row")
def script_previousRow(self, gesture):
self._tableMovementScriptHelper(axis="row", movement="previous")
# Translators: the description for the previous table row script on virtualBuffers.
script_previousRow.__doc__ = _("moves to the previous table row")
def script_nextColumn(self, gesture):
self._tableMovementScriptHelper(axis="column", movement="next")
# Translators: the description for the next table column script on virtualBuffers.
script_nextColumn.__doc__ = _("moves to the next table column")
def script_previousColumn(self, gesture):
self._tableMovementScriptHelper(axis="column", movement="previous")
# Translators: the description for the previous table column script on virtualBuffers.
script_previousColumn.__doc__ = _("moves to the previous table column")
def _isSuitableNotLinkBlock(self,range):
return (range._endOffset-range._startOffset)>=self.NOT_LINK_BLOCK_MIN_LEN
def getEnclosingContainerRange(self,range):
formatConfig=config.conf['documentFormatting'].copy()
formatConfig.update({"reportBlockQuotes":True,"reportTables":True,"reportLists":True,"reportFrames":True})
controlFields=[]
for cmd in range.getTextWithFields():
if not isinstance(cmd,textInfos.FieldCommand) or cmd.command!="controlStart":
break
controlFields.append(cmd.field)
containerField=None
while controlFields:
field=controlFields.pop()
if field.getPresentationCategory(controlFields,formatConfig)==field.PRESCAT_CONTAINER:
containerField=field
break
if not containerField: return None
docHandle=int(containerField['controlIdentifier_docHandle'])
ID=int(containerField['controlIdentifier_ID'])
offsets=range._getOffsetsFromFieldIdentifier(docHandle,ID)
return self.makeTextInfo(textInfos.offsets.Offsets(*offsets))
@classmethod
def changeNotify(cls, rootDocHandle, rootID):
try:
queueHandler.queueFunction(queueHandler.eventQueue, cls.rootIdentifiers[rootDocHandle, rootID]._handleUpdate)
except KeyError:
pass
def _handleUpdate(self):
"""Handle an update to this buffer.
"""
braille.handler.handleUpdate(self)
def getControlFieldForNVDAObject(self, obj):
docHandle, objId = self.getIdentifierFromNVDAObject(obj)
objId = unicode(objId)
info = self.makeTextInfo(obj)
info.collapse()
info.expand(textInfos.UNIT_CHARACTER)
for item in info.getTextWithFields():
if not isinstance(item, textInfos.FieldCommand) or not item.field:
continue
fieldId = item.field.get("controlIdentifier_ID")
if fieldId == objId:
return item.field
raise LookupError
__gestures = {
"kb:NVDA+f5": "refreshBuffer",
"kb:NVDA+v": "toggleScreenLayout",
"kb:control+alt+downArrow": "nextRow",
"kb:control+alt+upArrow": "previousRow",
"kb:control+alt+rightArrow": "nextColumn",
"kb:control+alt+leftArrow": "previousColumn",
}
| 1 | 18,433 | Extraneous blank line. | nvaccess-nvda | py |
@@ -43,5 +43,5 @@ var errWalletNotFound = fmt.Errorf("wallet not found")
var errSQLiteWrongType = fmt.Errorf("sqlite wallet driver returned wrong wallet type")
var errNameTooLong = fmt.Errorf("wallet name too long, must be <= %d bytes", sqliteMaxWalletNameLen)
var errIDTooLong = fmt.Errorf("wallet id too long, must be <= %d bytes", sqliteMaxWalletIDLen)
-var errMsigWrongAddr = fmt.Errorf("given multisig preimage hashes to wrong address")
+var errMsigWrongAddr = fmt.Errorf("given multisig preimage hashes to neither Sender or AuthAddr")
var errMsigWrongKey = fmt.Errorf("given key is not a possible signer for this multisig") | 1 | // Copyright (C) 2019-2020 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 driver
import (
"fmt"
)
var errDatabase = fmt.Errorf("database error")
var errDatabaseConnect = fmt.Errorf("error connecting to database")
var errKeyNotFound = fmt.Errorf("key does not exist in this wallet")
var errMsigDataNotFound = fmt.Errorf("multisig information (pks, threshold) for address does not exist in this wallet")
var errSKToPK = fmt.Errorf("could not convert secret key to public key")
var errSKToSeed = fmt.Errorf("could not convert secret key to seed")
var errTampering = fmt.Errorf("derived public key mismatch, something fishy is going on with this wallet")
var errNoMnemonicUX = fmt.Errorf("sqlite wallet driver cannot display mnemonics")
var errKeyExists = fmt.Errorf("key already exists in wallet")
var errDeriveKey = fmt.Errorf("scrypt lib could not derive key from password")
var errWrongDriver = fmt.Errorf("found database with wrong driver name in wallets dir")
var errRandBytes = fmt.Errorf("error reading random bytes")
var errTooManyKeys = fmt.Errorf("too many keys")
var errWrongDriverVer = fmt.Errorf("found database with wrong driver version in wallets dir")
var errDecrypt = fmt.Errorf("error decrypting. wrong password?")
var errTypeMismatch = fmt.Errorf("error decrypting, found the wrong type of data. something fishy is going on with this wallet")
var errSameName = fmt.Errorf("wallet with same name already exists")
var errSameID = fmt.Errorf("wallet with same id already exists")
var errIDConflict = fmt.Errorf("multiple wallets with the same ID exist. cannot continue")
var errWalletNotFound = fmt.Errorf("wallet not found")
var errSQLiteWrongType = fmt.Errorf("sqlite wallet driver returned wrong wallet type")
var errNameTooLong = fmt.Errorf("wallet name too long, must be <= %d bytes", sqliteMaxWalletNameLen)
var errIDTooLong = fmt.Errorf("wallet id too long, must be <= %d bytes", sqliteMaxWalletIDLen)
var errMsigWrongAddr = fmt.Errorf("given multisig preimage hashes to wrong address")
var errMsigWrongKey = fmt.Errorf("given key is not a possible signer for this multisig")
| 1 | 39,488 | nit: syntax : neither -> nor | algorand-go-algorand | go |
@@ -45,11 +45,11 @@ namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Log4Net
loggingEvent.Properties[CorrelationIdentifier.VersionKey] = tracer.Settings.ServiceVersion ?? string.Empty;
loggingEvent.Properties[CorrelationIdentifier.EnvKey] = tracer.Settings.Environment ?? string.Empty;
- var span = tracer.ActiveScope?.Span;
- if (span is not null)
+ var spanContext = tracer.DistributedSpanContext;
+ if (spanContext is not null)
{
- loggingEvent.Properties[CorrelationIdentifier.TraceIdKey] = span.TraceId;
- loggingEvent.Properties[CorrelationIdentifier.SpanIdKey] = span.SpanId;
+ loggingEvent.Properties[CorrelationIdentifier.TraceIdKey] = spanContext[HttpHeaderNames.TraceId];
+ loggingEvent.Properties[CorrelationIdentifier.SpanIdKey] = spanContext[HttpHeaderNames.ParentId];
}
}
| 1 | // <copyright file="AppenderAttachedImplIntegration.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
using System;
using System.ComponentModel;
using Datadog.Trace.ClrProfiler.CallTarget;
namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Log4Net
{
/// <summary>
/// LoggerFactoryScopeProvider.ForEach<TState> calltarget instrumentation
/// </summary>
[InstrumentMethod(
AssemblyName = "log4net",
TypeName = "log4net.Util.AppenderAttachedImpl",
MethodName = "AppendLoopOnAppenders",
ReturnTypeName = ClrNames.Int32,
ParameterTypeNames = new[] { "log4net.Core.LoggingEvent" },
MinimumVersion = "1.0.0",
MaximumVersion = "2.*.*",
IntegrationName = "Log4Net")]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public class AppenderAttachedImplIntegration
{
/// <summary>
/// OnMethodBegin callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <typeparam name="TLoggingEvent">The type of the logging event</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <param name="loggingEvent">The logging event</param>
/// <returns>Calltarget state value</returns>
public static CallTargetState OnMethodBegin<TTarget, TLoggingEvent>(TTarget instance, TLoggingEvent loggingEvent)
where TLoggingEvent : ILoggingEvent
{
var tracer = Tracer.Instance;
if (tracer.Settings.LogsInjectionEnabled &&
!loggingEvent.Properties.Contains(CorrelationIdentifier.ServiceKey))
{
loggingEvent.Properties[CorrelationIdentifier.ServiceKey] = tracer.DefaultServiceName ?? string.Empty;
loggingEvent.Properties[CorrelationIdentifier.VersionKey] = tracer.Settings.ServiceVersion ?? string.Empty;
loggingEvent.Properties[CorrelationIdentifier.EnvKey] = tracer.Settings.Environment ?? string.Empty;
var span = tracer.ActiveScope?.Span;
if (span is not null)
{
loggingEvent.Properties[CorrelationIdentifier.TraceIdKey] = span.TraceId;
loggingEvent.Properties[CorrelationIdentifier.SpanIdKey] = span.SpanId;
}
}
return new CallTargetState(scope: null, state: null);
}
/// <summary>
/// OnMethodEnd callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <typeparam name="TReturn">Type of the return value</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <param name="returnValue">Original return value</param>
/// <param name="exception">Exception instance in case the original code threw an exception.</param>
/// <param name="state">Calltarget state value</param>
/// <returns>A response value, in an async scenario will be T of Task of T</returns>
public static CallTargetReturn<TReturn> OnMethodEnd<TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state)
{
return new CallTargetReturn<TReturn>(returnValue);
}
}
}
| 1 | 25,064 | Is it safe to assume that these two keys are always present? `this[string]` will throw a `KeyNotFoundException` if they are not. | DataDog-dd-trace-dotnet | .cs |
@@ -689,8 +689,9 @@ public class ExecutionController extends EventHandler implements ExecutorManager
this.maxConcurrentRunsPerFlowMap);
if (running.size() > maxConcurrentRuns) {
this.commonMetrics.markSubmitFlowSkip();
- throw new ExecutorManagerException("Flow " + flowId
- + " has more than " + maxConcurrentRuns + " concurrent runs. Skipping",
+ throw new ExecutorManagerException("Flow with id " +
+ (exflow.getFlowDefinitionId() > 0 ? exflow.getFlowDefinitionId() : flowId)
+ + " has more than " + maxConcurrentRuns + " concurrent runs. Execution not created.",
ExecutorManagerException.Reason.SkippedExecution);
} else if (options.getConcurrentOption().equals(
ExecutionOptions.CONCURRENT_OPTION_PIPELINE)) { | 1 | /*
* Copyright 2018 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.executor;
import azkaban.Constants.ConfigurationKeys;
import azkaban.event.EventHandler;
import azkaban.flow.FlowUtils;
import azkaban.metrics.CommonMetrics;
import azkaban.project.Project;
import azkaban.project.ProjectWhitelist;
import azkaban.utils.FileIOUtils.LogData;
import azkaban.utils.Pair;
import azkaban.utils.Props;
import java.io.IOException;
import java.lang.Thread.State;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Controls flow executions on web server. This module implements the polling model
* in the new AZ dispatching design. It's injected only when azkaban.poll.model is configured to
* true. It will ultimately replace ExecutorManager in the future.
*/
@Singleton
public class ExecutionController extends EventHandler implements ExecutorManagerAdapter {
private static final Logger logger = LoggerFactory.getLogger(ExecutionController.class);
private static final Duration RECENTLY_FINISHED_LIFETIME = Duration.ofMinutes(10);
private final ExecutorLoader executorLoader;
private final ExecutorApiGateway apiGateway;
private final AlerterHolder alerterHolder;
private final ExecutorHealthChecker executorHealthChecker;
private final int maxConcurrentRunsOneFlow;
private final Map<Pair<String, String>, Integer> maxConcurrentRunsPerFlowMap;
private final CommonMetrics commonMetrics;
private final Props azkProps;
@Inject
ExecutionController(final Props azkProps, final ExecutorLoader executorLoader,
final CommonMetrics commonMetrics,
final ExecutorApiGateway apiGateway, final AlerterHolder alerterHolder, final
ExecutorHealthChecker executorHealthChecker) {
this.azkProps = azkProps;
this.executorLoader = executorLoader;
this.commonMetrics = commonMetrics;
this.apiGateway = apiGateway;
this.alerterHolder = alerterHolder;
this.executorHealthChecker = executorHealthChecker;
this.maxConcurrentRunsOneFlow = ExecutorUtils.getMaxConcurrentRunsOneFlow(azkProps);
this.maxConcurrentRunsPerFlowMap = ExecutorUtils.getMaxConcurentRunsPerFlowMap(azkProps);
}
@Override
public void setupExecutors() throws ExecutorManagerException {
// Todo: deprecate this method
}
@Override
public void disableQueueProcessorThread() {
// Todo: deprecate this method
}
@Override
public void enableQueueProcessorThread() {
// Todo: deprecate this method
}
@Override
public State getExecutorManagerThreadState() {
// Todo: deprecate this method
return State.RUNNABLE;
}
@Override
public boolean isExecutorManagerThreadActive() {
// Todo: deprecate this method
return true;
}
@Override
public long getLastExecutorManagerThreadCheckTime() {
// Todo: deprecate this method
return 1L;
}
@Override
public Collection<Executor> getAllActiveExecutors() {
List<Executor> executors = new ArrayList<>();
try {
executors = this.executorLoader.fetchActiveExecutors();
} catch (final ExecutorManagerException e) {
logger.error("Failed to get all active executors.", e);
}
return executors;
}
@Override
public Executor fetchExecutor(final int executorId) throws ExecutorManagerException {
return this.executorLoader.fetchExecutor(executorId);
}
@Override
public Set<String> getPrimaryServerHosts() {
final HashSet<String> ports = new HashSet<>();
try {
for (final Executor executor : this.executorLoader.fetchActiveExecutors()) {
ports.add(executor.getHost() + ":" + executor.getPort());
}
} catch (final ExecutorManagerException e) {
logger.error("Failed to get primary server hosts.", e);
}
return ports;
}
@Override
public Set<String> getAllActiveExecutorServerHosts() {
final Set<String> ports = getPrimaryServerHosts();
// include executor which were initially active and still has flows running
try {
for (final Pair<ExecutionReference, ExecutableFlow> running : this.executorLoader
.fetchActiveFlows().values()) {
final ExecutionReference ref = running.getFirst();
if (ref.getExecutor().isPresent()) {
final Executor executor = ref.getExecutor().get();
ports.add(executor.getHost() + ":" + executor.getPort());
}
}
} catch (final ExecutorManagerException e) {
logger.error("Failed to get all active executor server hosts.", e);
}
return ports;
}
/**
* Gets a list of all the unfinished (both dispatched and non-dispatched) executions for a
* given project and flow {@inheritDoc}.
*
* @see azkaban.executor.ExecutorManagerAdapter#getRunningFlows(int, java.lang.String)
*/
@Override
public List<Integer> getRunningFlows(final int projectId, final String flowId) {
final List<Integer> executionIds = new ArrayList<>();
try {
executionIds.addAll(getRunningFlowsHelper(projectId, flowId,
this.executorLoader.fetchUnfinishedFlows().values()));
} catch (final ExecutorManagerException e) {
logger.error("Failed to get running flows for project " + projectId + ", flow "
+ flowId, e);
}
return executionIds;
}
/* Helper method for getRunningFlows */
private List<Integer> getRunningFlowsHelper(final int projectId, final String flowId,
final Collection<Pair<ExecutionReference, ExecutableFlow>> collection) {
final List<Integer> executionIds = new ArrayList<>();
for (final Pair<ExecutionReference, ExecutableFlow> ref : collection) {
if (ref.getSecond().getFlowId().equals(flowId)
&& ref.getSecond().getProjectId() == projectId) {
executionIds.add(ref.getFirst().getExecId());
}
}
return executionIds;
}
@Override
public List<Pair<ExecutableFlow, Optional<Executor>>> getActiveFlowsWithExecutor()
throws IOException {
final List<Pair<ExecutableFlow, Optional<Executor>>> flows = new ArrayList<>();
try {
getActiveFlowsWithExecutorHelper(flows, this.executorLoader.fetchUnfinishedFlows().values());
} catch (final ExecutorManagerException e) {
logger.error("Failed to get active flows with executor.", e);
}
return flows;
}
/* Helper method for getActiveFlowsWithExecutor */
private void getActiveFlowsWithExecutorHelper(
final List<Pair<ExecutableFlow, Optional<Executor>>> flows,
final Collection<Pair<ExecutionReference, ExecutableFlow>> collection) {
for (final Pair<ExecutionReference, ExecutableFlow> ref : collection) {
flows.add(new Pair<>(ref.getSecond(), ref
.getFirst().getExecutor()));
}
}
/**
* Checks whether the given flow has an active (running, non-dispatched) execution from
* database. {@inheritDoc}
*/
@Override
public boolean isFlowRunning(final int projectId, final String flowId) {
boolean isRunning = false;
try {
isRunning = isFlowRunningHelper(projectId, flowId,
this.executorLoader.fetchUnfinishedFlows().values());
} catch (final ExecutorManagerException e) {
logger.error(
"Failed to check if the flow is running for project " + projectId + ", flow " + flowId,
e);
}
return isRunning;
}
/* Search a running flow in a collection */
private boolean isFlowRunningHelper(final int projectId, final String flowId,
final Collection<Pair<ExecutionReference, ExecutableFlow>> collection) {
for (final Pair<ExecutionReference, ExecutableFlow> ref : collection) {
if (ref.getSecond().getProjectId() == projectId
&& ref.getSecond().getFlowId().equals(flowId)) {
return true;
}
}
return false;
}
/**
* Fetch ExecutableFlow from database. {@inheritDoc}
*/
@Override
public ExecutableFlow getExecutableFlow(final int execId)
throws ExecutorManagerException {
return this.executorLoader.fetchExecutableFlow(execId);
}
/**
* Get all running (unfinished) flows from database. {@inheritDoc}
*/
@Override
public List<ExecutableFlow> getRunningFlows() {
final ArrayList<ExecutableFlow> flows = new ArrayList<>();
try {
getFlowsHelper(flows, this.executorLoader.fetchUnfinishedFlows().values());
} catch (final ExecutorManagerException e) {
logger.error("Failed to get running flows.", e);
}
return flows;
}
/**
* Helper method to get all flows from collection.
*/
private void getFlowsHelper(final ArrayList<ExecutableFlow> flows,
final Collection<Pair<ExecutionReference, ExecutableFlow>> collection) {
collection.stream().forEach(ref -> flows.add(ref.getSecond()));
}
/**
* Get execution ids of all running (unfinished) flows from database.
*/
public List<Integer> getRunningFlowIds() {
final List<Integer> allIds = new ArrayList<>();
try {
getExecutionIdsHelper(allIds, this.executorLoader.fetchUnfinishedFlows().values());
} catch (final ExecutorManagerException e) {
this.logger.error("Failed to get running flow ids.", e);
}
return allIds;
}
/**
* Get execution ids of all non-dispatched flows from database.
*/
public List<Integer> getQueuedFlowIds() {
final List<Integer> allIds = new ArrayList<>();
try {
getExecutionIdsHelper(allIds, this.executorLoader.fetchQueuedFlows());
} catch (final ExecutorManagerException e) {
this.logger.error("Failed to get queued flow ids.", e);
}
return allIds;
}
/* Helper method to get all execution ids from collection in sorted order. */
private void getExecutionIdsHelper(final List<Integer> allIds,
final Collection<Pair<ExecutionReference, ExecutableFlow>> collection) {
collection.stream().forEach(ref -> allIds.add(ref.getSecond().getExecutionId()));
Collections.sort(allIds);
}
/**
* Get the number of non-dispatched flows from database. {@inheritDoc}
*/
@Override
public long getQueuedFlowSize() {
long size = 0L;
try {
size = this.executorLoader.fetchQueuedFlows().size();
} catch (final ExecutorManagerException e) {
this.logger.error("Failed to get queued flow size.", e);
}
return size;
}
@Override
public List<ExecutableFlow> getRecentlyFinishedFlows() {
List<ExecutableFlow> flows = new ArrayList<>();
try {
flows = this.executorLoader.fetchRecentlyFinishedFlows(
RECENTLY_FINISHED_LIFETIME);
} catch (final ExecutorManagerException e) {
logger.error("Failed to fetch recently finished flows.", e);
}
return flows;
}
@Override
public List<ExecutableFlow> getExecutableFlows(final int skip, final int size)
throws ExecutorManagerException {
final List<ExecutableFlow> flows = this.executorLoader.fetchFlowHistory(skip, size);
return flows;
}
@Override
public List<ExecutableFlow> getExecutableFlows(final String flowIdContains,
final int skip, final int size) throws ExecutorManagerException {
final List<ExecutableFlow> flows =
this.executorLoader.fetchFlowHistory(null, '%' + flowIdContains + '%', null,
0, -1, -1, skip, size);
return flows;
}
@Override
public List<ExecutableFlow> getExecutableFlows(final String projContain,
final String flowContain, final String userContain, final int status, final long begin,
final long end,
final int skip, final int size) throws ExecutorManagerException {
final List<ExecutableFlow> flows =
this.executorLoader.fetchFlowHistory(projContain, flowContain, userContain,
status, begin, end, skip, size);
return flows;
}
@Override
public List<ExecutableJobInfo> getExecutableJobs(final Project project,
final String jobId, final int skip, final int size) throws ExecutorManagerException {
final List<ExecutableJobInfo> nodes =
this.executorLoader.fetchJobHistory(project.getId(), jobId, skip, size);
return nodes;
}
@Override
public int getNumberOfJobExecutions(final Project project, final String jobId)
throws ExecutorManagerException {
return this.executorLoader.fetchNumExecutableNodes(project.getId(), jobId);
}
@Override
public LogData getExecutableFlowLog(final ExecutableFlow exFlow, final int offset,
final int length) throws ExecutorManagerException {
final Pair<ExecutionReference, ExecutableFlow> pair = this.executorLoader
.fetchActiveFlowByExecId(exFlow.getExecutionId());
if (pair != null) {
final Pair<String, String> typeParam = new Pair<>("type", "flow");
final Pair<String, String> offsetParam =
new Pair<>("offset", String.valueOf(offset));
final Pair<String, String> lengthParam =
new Pair<>("length", String.valueOf(length));
@SuppressWarnings("unchecked") final Map<String, Object> result =
this.apiGateway.callWithReference(pair.getFirst(), ConnectorParams.LOG_ACTION,
typeParam, offsetParam, lengthParam);
return LogData.createLogDataFromObject(result);
} else {
final LogData value =
this.executorLoader.fetchLogs(exFlow.getExecutionId(), "", 0, offset,
length);
return value;
}
}
@Override
public LogData getExecutionJobLog(final ExecutableFlow exFlow, final String jobId,
final int offset, final int length, final int attempt) throws ExecutorManagerException {
final Pair<ExecutionReference, ExecutableFlow> pair = this.executorLoader
.fetchActiveFlowByExecId(exFlow.getExecutionId());
if (pair != null) {
final Pair<String, String> typeParam = new Pair<>("type", "job");
final Pair<String, String> jobIdParam =
new Pair<>("jobId", jobId);
final Pair<String, String> offsetParam =
new Pair<>("offset", String.valueOf(offset));
final Pair<String, String> lengthParam =
new Pair<>("length", String.valueOf(length));
final Pair<String, String> attemptParam =
new Pair<>("attempt", String.valueOf(attempt));
@SuppressWarnings("unchecked") final Map<String, Object> result =
this.apiGateway.callWithReference(pair.getFirst(), ConnectorParams.LOG_ACTION,
typeParam, jobIdParam, offsetParam, lengthParam, attemptParam);
return LogData.createLogDataFromObject(result);
} else {
final LogData value =
this.executorLoader.fetchLogs(exFlow.getExecutionId(), jobId, attempt,
offset, length);
return value;
}
}
@Override
public List<Object> getExecutionJobStats(final ExecutableFlow exFlow, final String jobId,
final int attempt) throws ExecutorManagerException {
final Pair<ExecutionReference, ExecutableFlow> pair =
this.executorLoader.fetchActiveFlowByExecId(exFlow.getExecutionId());
if (pair == null) {
return this.executorLoader.fetchAttachments(exFlow.getExecutionId(), jobId,
attempt);
}
final Pair<String, String> jobIdParam = new Pair<>("jobId", jobId);
final Pair<String, String> attemptParam =
new Pair<>("attempt", String.valueOf(attempt));
@SuppressWarnings("unchecked") final Map<String, Object> result =
this.apiGateway.callWithReference(pair.getFirst(), ConnectorParams.ATTACHMENTS_ACTION,
jobIdParam, attemptParam);
@SuppressWarnings("unchecked") final List<Object> jobStats = (List<Object>) result
.get("attachments");
return jobStats;
}
/**
* If the Resource Manager and Job History server urls are configured, find all the
* Hadoop/Spark application ids present in the Azkaban job's log and then construct the url to
* job logs in the Hadoop/Spark server for each application id found. Application ids are
* returned in the order they appear in the Azkaban job log.
*
* @param exFlow The executable flow.
* @param jobId The job id.
* @param attempt The job execution attempt.
* @return The map of (application id, job log url)
*/
@Override
public Map<String, String> getExternalJobLogUrls(final ExecutableFlow exFlow, final String jobId,
final int attempt) {
final Map<String, String> jobLogUrlsByAppId = new LinkedHashMap<>();
if (!this.azkProps.containsKey(ConfigurationKeys.RESOURCE_MANAGER_JOB_URL) ||
!this.azkProps.containsKey(ConfigurationKeys.HISTORY_SERVER_JOB_URL) ||
!this.azkProps.containsKey(ConfigurationKeys.SPARK_HISTORY_SERVER_JOB_URL)) {
return jobLogUrlsByAppId;
}
final Set<String> applicationIds = getApplicationIds(exFlow, jobId, attempt);
for (final String applicationId : applicationIds) {
final String jobLogUrl = ExecutionControllerUtils
.createJobLinkUrl(exFlow, jobId, applicationId, this.azkProps);
if (jobLogUrl != null) {
jobLogUrlsByAppId.put(applicationId, jobLogUrl);
}
}
return jobLogUrlsByAppId;
}
/**
* Find all the Hadoop/Spark application ids present in the Azkaban job log. When iterating
* over the set returned by this method the application ids are in the same order they appear
* in the log.
*
* @param exFlow The executable flow.
* @param jobId The job id.
* @param attempt The job execution attempt.
* @return The application ids found.
*/
Set<String> getApplicationIds(final ExecutableFlow exFlow, final String jobId,
final int attempt) {
final Set<String> applicationIds = new LinkedHashSet<>();
int offset = 0;
try {
LogData data = getExecutionJobLog(exFlow, jobId, offset, 50000, attempt);
while (data != null && data.getLength() > 0) {
this.logger.info("Get application ID for execution " + exFlow.getExecutionId() + ", job"
+ " " + jobId + ", attempt " + attempt + ", data offset " + offset);
String logData = data.getData();
final int indexOfLastSpace = logData.lastIndexOf(' ');
final int indexOfLastTab = logData.lastIndexOf('\t');
final int indexOfLastEoL = logData.lastIndexOf('\n');
final int indexOfLastDelim = Math
.max(indexOfLastEoL, Math.max(indexOfLastSpace, indexOfLastTab));
if (indexOfLastDelim > -1) {
// index + 1 to avoid looping forever if indexOfLastDelim is zero
logData = logData.substring(0, indexOfLastDelim + 1);
}
applicationIds.addAll(ExecutionControllerUtils.findApplicationIdsFromLog(logData));
offset = data.getOffset() + logData.length();
data = getExecutionJobLog(exFlow, jobId, offset, 50000, attempt);
}
} catch (final ExecutorManagerException e) {
this.logger.error("Failed to get application ID for execution " + exFlow.getExecutionId() +
", job " + jobId + ", attempt " + attempt + ", data offset " + offset, e);
}
return applicationIds;
}
/**
* If a flow is already dispatched to an executor, cancel by calling Executor. Else if it's still
* queued in DB, remove it from DB queue and finalize. {@inheritDoc}
*/
@Override
public void cancelFlow(final ExecutableFlow exFlow, final String userId)
throws ExecutorManagerException {
synchronized (exFlow) {
final Map<Integer, Pair<ExecutionReference, ExecutableFlow>> unfinishedFlows = this.executorLoader
.fetchUnfinishedFlows();
if (unfinishedFlows.containsKey(exFlow.getExecutionId())) {
final Pair<ExecutionReference, ExecutableFlow> pair = unfinishedFlows
.get(exFlow.getExecutionId());
if (pair.getFirst().getExecutor().isPresent()) {
// Flow is already dispatched to an executor, so call that executor to cancel the flow.
this.apiGateway
.callWithReferenceByUser(pair.getFirst(), ConnectorParams.CANCEL_ACTION, userId);
} else {
// Flow is still queued, need to finalize it and update the status in DB.
ExecutionControllerUtils.finalizeFlow(this.executorLoader, this.alerterHolder, exFlow,
"Cancelled before dispatching to executor", null);
}
} else {
throw new ExecutorManagerException("Execution "
+ exFlow.getExecutionId() + " of flow " + exFlow.getFlowId()
+ " isn't running.");
}
}
}
@Override
public void resumeFlow(final ExecutableFlow exFlow, final String userId)
throws ExecutorManagerException {
synchronized (exFlow) {
final Pair<ExecutionReference, ExecutableFlow> pair =
this.executorLoader.fetchActiveFlowByExecId(exFlow.getExecutionId());
if (pair == null) {
throw new ExecutorManagerException("Execution "
+ exFlow.getExecutionId() + " of flow " + exFlow.getFlowId()
+ " isn't running.");
}
this.apiGateway
.callWithReferenceByUser(pair.getFirst(), ConnectorParams.RESUME_ACTION, userId);
}
}
@Override
public void pauseFlow(final ExecutableFlow exFlow, final String userId)
throws ExecutorManagerException {
synchronized (exFlow) {
final Pair<ExecutionReference, ExecutableFlow> pair =
this.executorLoader.fetchActiveFlowByExecId(exFlow.getExecutionId());
if (pair == null) {
throw new ExecutorManagerException("Execution "
+ exFlow.getExecutionId() + " of flow " + exFlow.getFlowId()
+ " isn't running.");
}
this.apiGateway
.callWithReferenceByUser(pair.getFirst(), ConnectorParams.PAUSE_ACTION, userId);
}
}
@Override
public void retryFailures(final ExecutableFlow exFlow, final String userId)
throws ExecutorManagerException {
modifyExecutingJobs(exFlow, ConnectorParams.MODIFY_RETRY_FAILURES, userId);
}
@SuppressWarnings("unchecked")
private Map<String, Object> modifyExecutingJobs(final ExecutableFlow exFlow,
final String command, final String userId, final String... jobIds)
throws ExecutorManagerException {
synchronized (exFlow) {
final Pair<ExecutionReference, ExecutableFlow> pair =
this.executorLoader.fetchActiveFlowByExecId(exFlow.getExecutionId());
if (pair == null) {
throw new ExecutorManagerException("Execution "
+ exFlow.getExecutionId() + " of flow " + exFlow.getFlowId()
+ " isn't running.");
}
final Map<String, Object> response;
if (jobIds != null && jobIds.length > 0) {
for (final String jobId : jobIds) {
if (!jobId.isEmpty()) {
final ExecutableNode node = exFlow.getExecutableNode(jobId);
if (node == null) {
throw new ExecutorManagerException("Job " + jobId
+ " doesn't exist in execution " + exFlow.getExecutionId()
+ ".");
}
}
}
final String ids = StringUtils.join(jobIds, ',');
response =
this.apiGateway.callWithReferenceByUser(pair.getFirst(),
ConnectorParams.MODIFY_EXECUTION_ACTION, userId,
new Pair<>(
ConnectorParams.MODIFY_EXECUTION_ACTION_TYPE, command),
new Pair<>(ConnectorParams.MODIFY_JOBS_LIST, ids));
} else {
response =
this.apiGateway.callWithReferenceByUser(pair.getFirst(),
ConnectorParams.MODIFY_EXECUTION_ACTION, userId,
new Pair<>(
ConnectorParams.MODIFY_EXECUTION_ACTION_TYPE, command));
}
return response;
}
}
@Override
public Map<String, String> doRampActions(List<Map<String, Object>> rampActions)
throws ExecutorManagerException {
return this.executorLoader.doRampActions(rampActions);
}
/**
* When a flow is submitted, insert a new execution into the database queue. {@inheritDoc}
*/
@Override
public String submitExecutableFlow(final ExecutableFlow exflow, final String userId)
throws ExecutorManagerException {
if (exflow.isLocked()) {
// Skip execution for locked flows.
final String message = String.format("Flow %s for project %s is locked.", exflow.getId(),
exflow.getProjectName());
logger.info(message);
return message;
}
final String exFlowKey = exflow.getProjectName() + "." + exflow.getId() + ".submitFlow";
// Use project and flow name to prevent race condition when same flow is submitted by API and
// schedule at the same time
// causing two same flow submission entering this piece.
synchronized (exFlowKey.intern()) {
final String flowId = exflow.getFlowId();
logger.info("Submitting execution flow " + flowId + " by " + userId);
String message = "";
final int projectId = exflow.getProjectId();
exflow.setSubmitUser(userId);
exflow.setStatus(Status.PREPARING);
exflow.setSubmitTime(System.currentTimeMillis());
final List<Integer> running = getRunningFlows(projectId, flowId);
ExecutionOptions options = exflow.getExecutionOptions();
if (options == null) {
options = new ExecutionOptions();
}
if (options.getDisabledJobs() != null) {
FlowUtils.applyDisabledJobs(options.getDisabledJobs(), exflow);
}
if (!running.isEmpty()) {
final int maxConcurrentRuns = ExecutorUtils.getMaxConcurrentRunsForFlow(
exflow.getProjectName(), flowId, this.maxConcurrentRunsOneFlow,
this.maxConcurrentRunsPerFlowMap);
if (running.size() > maxConcurrentRuns) {
this.commonMetrics.markSubmitFlowSkip();
throw new ExecutorManagerException("Flow " + flowId
+ " has more than " + maxConcurrentRuns + " concurrent runs. Skipping",
ExecutorManagerException.Reason.SkippedExecution);
} else if (options.getConcurrentOption().equals(
ExecutionOptions.CONCURRENT_OPTION_PIPELINE)) {
Collections.sort(running);
final Integer runningExecId = running.get(running.size() - 1);
options.setPipelineExecutionId(runningExecId);
message =
"Flow " + flowId + " is already running with exec id "
+ runningExecId + ". Pipelining level "
+ options.getPipelineLevel() + ". \n";
} else if (options.getConcurrentOption().equals(
ExecutionOptions.CONCURRENT_OPTION_SKIP)) {
this.commonMetrics.markSubmitFlowSkip();
throw new ExecutorManagerException("Flow " + flowId
+ " is already running. Skipping execution.",
ExecutorManagerException.Reason.SkippedExecution);
} else {
message =
"Flow " + flowId + " is already running with exec id "
+ StringUtils.join(running, ",")
+ ". Will execute concurrently. \n";
}
}
final boolean memoryCheck =
!ProjectWhitelist.isProjectWhitelisted(exflow.getProjectId(),
ProjectWhitelist.WhitelistType.MemoryCheck);
options.setMemoryCheck(memoryCheck);
// The exflow id is set by the loader. So it's unavailable until after
// this call.
this.executorLoader.uploadExecutableFlow(exflow);
this.commonMetrics.markSubmitFlowSuccess();
message += "Execution queued successfully with exec id " + exflow.getExecutionId();
return message;
}
}
@Override
public Map<String, Object> callExecutorStats(final int executorId, final String action,
final Pair<String, String>... params) throws IOException, ExecutorManagerException {
final Executor executor = fetchExecutor(executorId);
final List<Pair<String, String>> paramList = new ArrayList<>();
if (params != null) {
paramList.addAll(Arrays.asList(params));
}
paramList.add(new Pair<>(ConnectorParams.ACTION_PARAM, action));
return this.apiGateway.callForJsonObjectMap(executor.getHost(), executor.getPort(),
"/stats", paramList);
}
@Override
public Map<String, Object> callExecutorJMX(final String hostPort, final String action,
final String mBean) throws IOException {
final List<Pair<String, String>> paramList =
new ArrayList<>();
paramList.add(new Pair<>(action, ""));
if (mBean != null) {
paramList.add(new Pair<>(ConnectorParams.JMX_MBEAN, mBean));
}
final String[] hostPortSplit = hostPort.split(":");
return this.apiGateway.callForJsonObjectMap(hostPortSplit[0],
Integer.valueOf(hostPortSplit[1]), "/jmx", paramList);
}
@Override
public void start() {
this.executorHealthChecker.start();
}
@Override
public void shutdown() {
this.executorHealthChecker.shutdown();
}
@Override
public int getExecutableFlows(final int projectId, final String flowId, final int from,
final int length, final List<ExecutableFlow> outputList)
throws ExecutorManagerException {
final List<ExecutableFlow> flows =
this.executorLoader.fetchFlowHistory(projectId, flowId, from, length);
outputList.addAll(flows);
return this.executorLoader.fetchNumExecutableFlows(projectId, flowId);
}
@Override
public List<ExecutableFlow> getExecutableFlows(final int projectId, final String flowId,
final int from, final int length, final Status status) throws ExecutorManagerException {
return this.executorLoader.fetchFlowHistory(projectId, flowId, from, length,
status);
}
}
| 1 | 18,775 | Is the `flowDefinitionId` sufficient to uniquely identify the flow or does it need to be the tuple `<flowId,flowDefinitionId>` ? | azkaban-azkaban | java |
@@ -1774,6 +1774,7 @@ return [
'DateTime::add' => ['static', 'interval'=>'DateInterval'],
'DateTime::createFromFormat' => ['static|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'DateTime::createFromImmutable' => ['static', 'datetTimeImmutable'=>'DateTimeImmutable'],
+'DateTime::createFromInterface' => ['DateTimeInterface', 'self'],
'DateTime::diff' => ['DateInterval|false', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTime::format' => ['string|false', 'format'=>'string'],
'DateTime::getLastErrors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'], | 1 | <?php // phpcs:ignoreFile
namespace Phan\Language\Internal;
/**
* CURRENT PHP TARGET VERSION: 7.4
* The version above has to match Psalm\Internal\Codebase\InternalCallMapHandler::PHP_(MAJOR|MINOR)_VERSION
*
* Format
*
* '<function_name>' => ['<return_type>, '<arg_name>'=>'<arg_type>']
* alternative signature for the same function
* '<function_name\'1>' => ['<return_type>, '<arg_name>'=>'<arg_type>']
*
* A '&' in front of the <arg_name> means the arg is always passed by reference.
* (i.e. ReflectionParameter->isPassedByReference())
* This was previously only used in cases where the function actually created the
* variable in the local scope.
* Some reference arguments will have prefixes in <arg_name> to indicate the way the argument is used.
* Currently, the only prefixes with meaning are 'rw_' (read-write) and 'w_' (write).
* Those prefixes don't mean anything for non-references.
* Code using these signatures should remove those prefixes from messages rendered to the user.
* 1. '&rw_<arg_name>' indicates that a parameter with a value is expected to be passed in, and may be modified.
* Phan will warn if the variable has an incompatible type, or is undefined.
* 2. '&w_<arg_name>' indicates that a parameter is expected to be passed in, and the value will be ignored, and may be overwritten.
* 3. The absence of a prefix is treated by Phan the same way as having the prefix 'w_' (Some may be changed to 'rw_name'). These will have prefixes added later.
*
* So, for functions like sort() where technically the arg is by-ref,
* indicate the reference param's signature by-ref and read-write,
* as `'&rw_array'=>'array'`
* so that Phan won't create it in the local scope
*
* However, for a function like preg_match() where the 3rd arg is an array of sub-pattern matches (and optional),
* this arg needs to be marked as by-ref and write-only, as `'&w_matches='=>'array'`.
*
* A '=' following the <arg_name> indicates this arg is optional.
*
* The <arg_name> can begin with '...' to indicate the arg is variadic.
* '...args=' indicates it is both variadic and optional.
*
* Some reference arguments will have prefixes in <arg_name> to indicate the way the argument is used.
* Currently, the only prefixes with meaning are 'rw_' and 'w_'.
* Code using these signatures should remove those prefixes from messages rendered to the user.
* 1. '&rw_name' indicates that a parameter with a value is expected to be passed in, and may be modified.
* 2. '&w_name' indicates that a parameter is expected to be passed in, and the value will be ignored, and may be overwritten.
*
* This file contains the signatures for the most recent minor release of PHP supported by phan (php 7.2)
*
* Changes:
*
* In Phan 0.12.3,
*
* - This started using array shapes for union types (array{...}).
*
* \Phan\Language\UnionType->withFlattenedArrayShapeOrLiteralTypeInstances() may be of help to programmatically convert these to array<string,T1>|array<string,T2>
*
* - This started using array shapes with optional fields for union types (array{key?:int}).
* A `?` after the array shape field's key indicates that the field is optional.
*
* - This started adding param signatures and return signatures to `callable` types.
* E.g. 'usort' => ['bool', '&rw_array_arg'=>'array', 'cmp_function'=>'callable(mixed,mixed):int'].
* See NEWS.md for 0.12.3 for possible syntax. A suffix of `=` within `callable(...)` means that a parameter is optional.
*
* (Phan assumes that callbacks with optional arguments can be cast to callbacks with/without those args (Similar to inheritance checks)
* (e.g. callable(T1,T2=) can be cast to callable(T1) or callable(T1,T2), in the same way that a subclass would check).
* For some signatures, e.g. set_error_handler, this results in repetition, because callable(T1=) can't cast to callable(T1).
*
* Sources of stub info:
*
* 1. Reflection
* 2. docs.php.net's SVN repo or website, and examples (See internal/internalsignatures.php)
*
* See https://secure.php.net/manual/en/copyright.php
*
* The PHP manual text and comments are covered by the [Creative Commons Attribution 3.0 License](http://creativecommons.org/licenses/by/3.0/legalcode),
* copyright (c) the PHP Documentation Group
* 3. Various websites documenting individual extensions
* 4. PHPStorm stubs (For anything missing from the above sources)
* See internal/internalsignatures.php
*
* Available from https://github.com/JetBrains/phpstorm-stubs under the [Apache 2 license](https://www.apache.org/licenses/LICENSE-2.0)
*
* @phan-file-suppress PhanPluginMixedKeyNoKey (read by Phan when analyzing this file)
*
* Note: Some of Phan's inferences about return types are written as plugins for functions/methods where the return type depends on the parameter types.
* E.g. src/Phan/Plugin/Internal/DependentReturnTypeOverridePlugin.php is one plugin
*/
return [
'_' => ['string', 'message'=>'string'],
'__halt_compiler' => ['void'],
'abs' => ['int', 'num'=>'int'],
'abs\'1' => ['float', 'num'=>'float'],
'abs\'2' => ['numeric', 'num'=>'numeric'],
'accelerator_get_configuration' => ['array'],
'accelerator_get_scripts' => ['array'],
'accelerator_get_status' => ['array', 'fetch_scripts'=>'bool'],
'accelerator_reset' => [''],
'accelerator_set_status' => ['void', 'status'=>'bool'],
'acos' => ['float', 'num'=>'float'],
'acosh' => ['float', 'num'=>'float'],
'addcslashes' => ['string', 'string'=>'string', 'characters'=>'string'],
'addslashes' => ['string', 'string'=>'string'],
'AMQPBasicProperties::__construct' => ['void', 'content_type='=>'string', 'content_encoding='=>'string', 'headers='=>'array', 'delivery_mode='=>'int', 'priority='=>'int', 'correlation_id='=>'string', 'reply_to='=>'string', 'expiration='=>'string', 'message_id='=>'string', 'timestamp='=>'int', 'type='=>'string', 'user_id='=>'string', 'app_id='=>'string', 'cluster_id='=>'string'],
'AMQPBasicProperties::getAppId' => ['string'],
'AMQPBasicProperties::getClusterId' => ['string'],
'AMQPBasicProperties::getContentEncoding' => ['string'],
'AMQPBasicProperties::getContentType' => ['string'],
'AMQPBasicProperties::getCorrelationId' => ['string'],
'AMQPBasicProperties::getDeliveryMode' => ['int'],
'AMQPBasicProperties::getExpiration' => ['string'],
'AMQPBasicProperties::getHeaders' => ['array'],
'AMQPBasicProperties::getMessageId' => ['string'],
'AMQPBasicProperties::getPriority' => ['int'],
'AMQPBasicProperties::getReplyTo' => ['string'],
'AMQPBasicProperties::getTimestamp' => ['string'],
'AMQPBasicProperties::getType' => ['string'],
'AMQPBasicProperties::getUserId' => ['string'],
'AMQPChannel::__construct' => ['void', 'amqp_connection'=>'AMQPConnection'],
'AMQPChannel::basicRecover' => ['', 'requeue='=>'bool'],
'AMQPChannel::close' => [''],
'AMQPChannel::commitTransaction' => ['bool'],
'AMQPChannel::confirmSelect' => [''],
'AMQPChannel::getChannelId' => ['int'],
'AMQPChannel::getConnection' => ['AMQPConnection'],
'AMQPChannel::getConsumers' => ['AMQPQueue[]'],
'AMQPChannel::getPrefetchCount' => ['int'],
'AMQPChannel::getPrefetchSize' => ['int'],
'AMQPChannel::isConnected' => ['bool'],
'AMQPChannel::qos' => ['bool', 'size'=>'int', 'count'=>'int'],
'AMQPChannel::rollbackTransaction' => ['bool'],
'AMQPChannel::setConfirmCallback' => ['', 'ack_callback='=>'?callable', 'nack_callback='=>'?callable'],
'AMQPChannel::setPrefetchCount' => ['bool', 'count'=>'int'],
'AMQPChannel::setPrefetchSize' => ['bool', 'size'=>'int'],
'AMQPChannel::setReturnCallback' => ['', 'return_callback='=>'?callable'],
'AMQPChannel::startTransaction' => ['bool'],
'AMQPChannel::waitForBasicReturn' => ['', 'timeout='=>'float'],
'AMQPChannel::waitForConfirm' => ['', 'timeout='=>'float'],
'AMQPConnection::__construct' => ['void', 'credentials='=>'array'],
'AMQPConnection::connect' => ['bool'],
'AMQPConnection::disconnect' => ['bool'],
'AMQPConnection::getCACert' => ['string'],
'AMQPConnection::getCert' => ['string'],
'AMQPConnection::getHeartbeatInterval' => ['int'],
'AMQPConnection::getHost' => ['string'],
'AMQPConnection::getKey' => ['string'],
'AMQPConnection::getLogin' => ['string'],
'AMQPConnection::getMaxChannels' => ['?int'],
'AMQPConnection::getMaxFrameSize' => ['int'],
'AMQPConnection::getPassword' => ['string'],
'AMQPConnection::getPort' => ['int'],
'AMQPConnection::getReadTimeout' => ['float'],
'AMQPConnection::getTimeout' => ['float'],
'AMQPConnection::getUsedChannels' => ['int'],
'AMQPConnection::getVerify' => ['bool'],
'AMQPConnection::getVhost' => ['string'],
'AMQPConnection::getWriteTimeout' => ['float'],
'AMQPConnection::isConnected' => ['bool'],
'AMQPConnection::isPersistent' => ['?bool'],
'AMQPConnection::pconnect' => ['bool'],
'AMQPConnection::pdisconnect' => ['bool'],
'AMQPConnection::preconnect' => ['bool'],
'AMQPConnection::reconnect' => ['bool'],
'AMQPConnection::setCACert' => ['', 'cacert'=>'string'],
'AMQPConnection::setCert' => ['', 'cert'=>'string'],
'AMQPConnection::setHost' => ['bool', 'host'=>'string'],
'AMQPConnection::setKey' => ['', 'key'=>'string'],
'AMQPConnection::setLogin' => ['bool', 'login'=>'string'],
'AMQPConnection::setPassword' => ['bool', 'password'=>'string'],
'AMQPConnection::setPort' => ['bool', 'port'=>'int'],
'AMQPConnection::setReadTimeout' => ['bool', 'timeout'=>'int'],
'AMQPConnection::setTimeout' => ['bool', 'timeout'=>'int'],
'AMQPConnection::setVerify' => ['', 'verify'=>'bool'],
'AMQPConnection::setVhost' => ['bool', 'vhost'=>'string'],
'AMQPConnection::setWriteTimeout' => ['bool', 'timeout'=>'int'],
'AMQPDecimal::__construct' => ['void', 'exponent'=>'', 'significand'=>''],
'AMQPDecimal::getExponent' => ['int'],
'AMQPDecimal::getSignificand' => ['int'],
'AMQPEnvelope::__construct' => ['void'],
'AMQPEnvelope::getAppId' => ['string'],
'AMQPEnvelope::getBody' => ['string'],
'AMQPEnvelope::getClusterId' => ['string'],
'AMQPEnvelope::getConsumerTag' => ['string'],
'AMQPEnvelope::getContentEncoding' => ['string'],
'AMQPEnvelope::getContentType' => ['string'],
'AMQPEnvelope::getCorrelationId' => ['string'],
'AMQPEnvelope::getDeliveryMode' => ['int'],
'AMQPEnvelope::getDeliveryTag' => ['string'],
'AMQPEnvelope::getExchangeName' => ['string'],
'AMQPEnvelope::getExpiration' => ['string'],
'AMQPEnvelope::getHeader' => ['string|false', 'header_key'=>'string'],
'AMQPEnvelope::getHeaders' => ['array'],
'AMQPEnvelope::getMessageId' => ['string'],
'AMQPEnvelope::getPriority' => ['int'],
'AMQPEnvelope::getReplyTo' => ['string'],
'AMQPEnvelope::getRoutingKey' => ['string'],
'AMQPEnvelope::getTimeStamp' => ['string'],
'AMQPEnvelope::getType' => ['string'],
'AMQPEnvelope::getUserId' => ['string'],
'AMQPEnvelope::hasHeader' => ['bool', 'header_key'=>'string'],
'AMQPEnvelope::isRedelivery' => ['bool'],
'AMQPExchange::__construct' => ['void', 'amqp_channel'=>'AMQPChannel'],
'AMQPExchange::bind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPExchange::declareExchange' => ['bool'],
'AMQPExchange::delete' => ['bool', 'exchangeName='=>'string', 'flags='=>'int'],
'AMQPExchange::getArgument' => ['int|string|false', 'key'=>'string'],
'AMQPExchange::getArguments' => ['array'],
'AMQPExchange::getChannel' => ['AMQPChannel'],
'AMQPExchange::getConnection' => ['AMQPConnection'],
'AMQPExchange::getFlags' => ['int'],
'AMQPExchange::getName' => ['string'],
'AMQPExchange::getType' => ['string'],
'AMQPExchange::hasArgument' => ['bool', 'key'=>'string'],
'AMQPExchange::publish' => ['bool', 'message'=>'string', 'routing_key='=>'string', 'flags='=>'int', 'attributes='=>'array'],
'AMQPExchange::setArgument' => ['bool', 'key'=>'string', 'value'=>'int|string'],
'AMQPExchange::setArguments' => ['bool', 'arguments'=>'array'],
'AMQPExchange::setFlags' => ['bool', 'flags'=>'int'],
'AMQPExchange::setName' => ['bool', 'exchange_name'=>'string'],
'AMQPExchange::setType' => ['bool', 'exchange_type'=>'string'],
'AMQPExchange::unbind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPQueue::__construct' => ['void', 'amqp_channel'=>'AMQPChannel'],
'AMQPQueue::ack' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::bind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPQueue::cancel' => ['bool', 'consumer_tag='=>'string'],
'AMQPQueue::consume' => ['void', 'callback='=>'?callable', 'flags='=>'int', 'consumerTag='=>'string'],
'AMQPQueue::declareQueue' => ['int'],
'AMQPQueue::delete' => ['int', 'flags='=>'int'],
'AMQPQueue::get' => ['AMQPEnvelope|false', 'flags='=>'int'],
'AMQPQueue::getArgument' => ['int|string|false', 'key'=>'string'],
'AMQPQueue::getArguments' => ['array'],
'AMQPQueue::getChannel' => ['AMQPChannel'],
'AMQPQueue::getConnection' => ['AMQPConnection'],
'AMQPQueue::getConsumerTag' => ['?string'],
'AMQPQueue::getFlags' => ['int'],
'AMQPQueue::getName' => ['string'],
'AMQPQueue::hasArgument' => ['bool', 'key'=>'string'],
'AMQPQueue::nack' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::purge' => ['bool'],
'AMQPQueue::reject' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::setArgument' => ['bool', 'key'=>'string', 'value'=>'mixed'],
'AMQPQueue::setArguments' => ['bool', 'arguments'=>'array'],
'AMQPQueue::setFlags' => ['bool', 'flags'=>'int'],
'AMQPQueue::setName' => ['bool', 'queue_name'=>'string'],
'AMQPQueue::unbind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPTimestamp::__construct' => ['void', 'timestamp'=>'string'],
'AMQPTimestamp::__toString' => ['string'],
'AMQPTimestamp::getTimestamp' => ['string'],
'apache_child_terminate' => ['bool'],
'apache_get_modules' => ['array'],
'apache_get_version' => ['string|false'],
'apache_getenv' => ['string|false', 'variable'=>'string', 'walk_to_top='=>'bool'],
'apache_lookup_uri' => ['object', 'filename'=>'string'],
'apache_note' => ['string|false', 'note_name'=>'string', 'note_value='=>'string'],
'apache_request_headers' => ['array|false'],
'apache_reset_timeout' => ['bool'],
'apache_response_headers' => ['array|false'],
'apache_setenv' => ['bool', 'variable'=>'string', 'value'=>'string', 'walk_to_top='=>'bool'],
'apc_add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'ttl='=>'int'],
'apc_add\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'apc_bin_dump' => ['string|false|null', 'files='=>'array', 'user_vars='=>'array'],
'apc_bin_dumpfile' => ['int|false', 'files'=>'array', 'user_vars'=>'array', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'apc_bin_load' => ['bool', 'data'=>'string', 'flags='=>'int'],
'apc_bin_loadfile' => ['bool', 'filename'=>'string', 'context='=>'resource', 'flags='=>'int'],
'apc_cache_info' => ['array|false', 'cache_type='=>'string', 'limited='=>'bool'],
'apc_cas' => ['bool', 'key'=>'string', 'old'=>'int', 'new'=>'int'],
'apc_clear_cache' => ['bool', 'cache_type='=>'string'],
'apc_compile_file' => ['bool', 'filename'=>'string', 'atomic='=>'bool'],
'apc_dec' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool'],
'apc_define_constants' => ['bool', 'key'=>'string', 'constants'=>'array', 'case_sensitive='=>'bool'],
'apc_delete' => ['bool', 'key'=>'string|string[]|APCIterator'],
'apc_delete_file' => ['bool|string[]', 'keys'=>'mixed'],
'apc_exists' => ['bool', 'keys'=>'string'],
'apc_exists\'1' => ['array', 'keys'=>'string[]'],
'apc_fetch' => ['mixed|false', 'key'=>'string', '&w_success='=>'bool'],
'apc_fetch\'1' => ['array|false', 'key'=>'string[]', '&w_success='=>'bool'],
'apc_inc' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool'],
'apc_load_constants' => ['bool', 'key'=>'string', 'case_sensitive='=>'bool'],
'apc_sma_info' => ['array|false', 'limited='=>'bool'],
'apc_store' => ['bool', 'key'=>'string', 'var'=>'', 'ttl='=>'int'],
'apc_store\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'APCIterator::__construct' => ['void', 'cache'=>'string', 'search='=>'null|string|string[]', 'format='=>'int', 'chunk_size='=>'int', 'list='=>'int'],
'APCIterator::current' => ['mixed|false'],
'APCIterator::getTotalCount' => ['int|false'],
'APCIterator::getTotalHits' => ['int|false'],
'APCIterator::getTotalSize' => ['int|false'],
'APCIterator::key' => ['string'],
'APCIterator::next' => ['void'],
'APCIterator::rewind' => ['void'],
'APCIterator::valid' => ['bool'],
'apcu_add' => ['bool', 'key'=>'string', 'var'=>'', 'ttl='=>'int'],
'apcu_add\'1' => ['array<string,int>', 'values'=>'array<string,mixed>', 'unused='=>'', 'ttl='=>'int'],
'apcu_cache_info' => ['array<string,mixed>|false', 'limited='=>'bool'],
'apcu_cas' => ['bool', 'key'=>'string', 'old'=>'int', 'new'=>'int'],
'apcu_clear_cache' => ['bool'],
'apcu_dec' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool', 'ttl='=>'int'],
'apcu_delete' => ['bool', 'key'=>'string|APCuIterator'],
'apcu_delete\'1' => ['list<string>', 'key'=>'string[]'],
'apcu_enabled' => ['bool'],
'apcu_entry' => ['mixed', 'key'=>'string', 'generator'=>'callable', 'ttl='=>'int'],
'apcu_exists' => ['bool', 'keys'=>'string'],
'apcu_exists\'1' => ['array', 'keys'=>'string[]'],
'apcu_fetch' => ['mixed|false', 'key'=>'string', '&w_success='=>'bool'],
'apcu_fetch\'1' => ['array|false', 'key'=>'string[]', '&w_success='=>'bool'],
'apcu_inc' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool', 'ttl='=>'int'],
'apcu_key_info' => ['?array', 'key'=>'string'],
'apcu_sma_info' => ['array|false', 'limited='=>'bool'],
'apcu_store' => ['bool', 'key'=>'string', 'var='=>'', 'ttl='=>'int'],
'apcu_store\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'APCuIterator::__construct' => ['void', 'search='=>'string|string[]|null', 'format='=>'int', 'chunk_size='=>'int', 'list='=>'int'],
'APCuIterator::current' => ['mixed'],
'APCuIterator::getTotalCount' => ['int'],
'APCuIterator::getTotalHits' => ['int'],
'APCuIterator::getTotalSize' => ['int'],
'APCuIterator::key' => ['string'],
'APCuIterator::next' => ['void'],
'APCuIterator::rewind' => ['void'],
'APCuIterator::valid' => ['bool'],
'apd_breakpoint' => ['bool', 'debug_level'=>'int'],
'apd_callstack' => ['array'],
'apd_clunk' => ['void', 'warning'=>'string', 'delimiter='=>'string'],
'apd_continue' => ['bool', 'debug_level'=>'int'],
'apd_croak' => ['void', 'warning'=>'string', 'delimiter='=>'string'],
'apd_dump_function_table' => ['void'],
'apd_dump_persistent_resources' => ['array'],
'apd_dump_regular_resources' => ['array'],
'apd_echo' => ['bool', 'output'=>'string'],
'apd_get_active_symbols' => ['array'],
'apd_set_pprof_trace' => ['string', 'dump_directory='=>'string', 'fragment='=>'string'],
'apd_set_session' => ['void', 'debug_level'=>'int'],
'apd_set_session_trace' => ['void', 'debug_level'=>'int', 'dump_directory='=>'string'],
'apd_set_session_trace_socket' => ['bool', 'tcp_server'=>'string', 'socket_type'=>'int', 'port'=>'int', 'debug_level'=>'int'],
'AppendIterator::__construct' => ['void'],
'AppendIterator::append' => ['void', 'iterator'=>'Iterator'],
'AppendIterator::current' => ['mixed'],
'AppendIterator::getArrayIterator' => ['ArrayIterator'],
'AppendIterator::getInnerIterator' => ['Iterator'],
'AppendIterator::getIteratorIndex' => ['int'],
'AppendIterator::key' => ['int|string|float|bool'],
'AppendIterator::next' => ['void'],
'AppendIterator::rewind' => ['void'],
'AppendIterator::valid' => ['bool'],
'ArgumentCountError::__clone' => ['void'],
'ArgumentCountError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'ArgumentCountError::__toString' => ['string'],
'ArgumentCountError::__wakeup' => ['void'],
'ArgumentCountError::getCode' => ['int'],
'ArgumentCountError::getFile' => ['string'],
'ArgumentCountError::getLine' => ['int'],
'ArgumentCountError::getMessage' => ['string'],
'ArgumentCountError::getPrevious' => ['?Throwable'],
'ArgumentCountError::getTrace' => ['list<array<string,mixed>>'],
'ArgumentCountError::getTraceAsString' => ['string'],
'ArithmeticError::__clone' => ['void'],
'ArithmeticError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'ArithmeticError::__toString' => ['string'],
'ArithmeticError::__wakeup' => ['void'],
'ArithmeticError::getCode' => ['int'],
'ArithmeticError::getFile' => ['string'],
'ArithmeticError::getLine' => ['int'],
'ArithmeticError::getMessage' => ['string'],
'ArithmeticError::getPrevious' => ['?Throwable'],
'ArithmeticError::getTrace' => ['list<array<string,mixed>>'],
'ArithmeticError::getTraceAsString' => ['string'],
'array_change_key_case' => ['associative-array', 'array'=>'array', 'case='=>'int'],
'array_chunk' => ['list<array[]>', 'array'=>'array', 'length'=>'int', 'preserve_keys='=>'bool'],
'array_column' => ['array', 'array'=>'array', 'column_key'=>'mixed', 'index_key='=>'mixed'],
'array_combine' => ['array|false', 'keys'=>'string[]|int[]', 'values'=>'array'],
'array_count_values' => ['associative-array<mixed,int>', 'array'=>'array'],
'array_diff' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_assoc' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_key' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_diff_ukey' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_ukey\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_fill' => ['array<int,mixed>', 'start_index'=>'int', 'count'=>'int', 'value'=>'mixed'],
'array_fill_keys' => ['array', 'keys'=>'array', 'value'=>'mixed'],
'array_filter' => ['associative-array', 'array'=>'array', 'callback='=>'callable(mixed,mixed=):scalar', 'mode='=>'int'],
'array_flip' => ['associative-array<mixed,int>|associative-array<mixed,string>', 'array'=>'array'],
'array_intersect' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_assoc' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_key' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_intersect_ukey' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_ukey\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_key_exists' => ['bool', 'key'=>'string|int', 'array'=>'array|ArrayObject'],
'array_key_first' => ['int|string|null', 'array'=>'array'],
'array_key_last' => ['int|string|null', 'array'=>'array'],
'array_keys' => ['list<string|int>', 'array'=>'array', 'filter_value='=>'mixed', 'strict='=>'bool'],
'array_map' => ['array', 'callback'=>'?callable', 'array'=>'array', '...arrays='=>'array'],
'array_merge' => ['array', 'arrays'=>'array', '...args='=>'array'],
'array_merge_recursive' => ['array', 'arrays'=>'array', '...args='=>'array'],
'array_multisort' => ['bool', '&rw_array'=>'array', 'rest='=>'array|int', 'array1_sort_flags='=>'array|int', '...args='=>'array|int'],
'array_pad' => ['array', 'array'=>'array', 'length'=>'int', 'value'=>'mixed'],
'array_pop' => ['mixed', '&rw_array'=>'array'],
'array_product' => ['int|float', 'array'=>'array'],
'array_push' => ['int', '&rw_array'=>'array', 'values'=>'mixed', '...vars='=>'mixed'],
'array_rand' => ['int|string|array<int,int>|array<int,string>', 'array'=>'non-empty-array', 'num'=>'int'],
'array_rand\'1' => ['int|string', 'array'=>'array'],
'array_reduce' => ['mixed', 'array'=>'array', 'callback'=>'callable(mixed,mixed):mixed', 'initial='=>'mixed'],
'array_replace' => ['?array', 'array'=>'array', 'replacements'=>'array', '...args='=>'array'],
'array_replace_recursive' => ['array', 'array'=>'array', 'replacements'=>'array', '...args='=>'array'],
'array_reverse' => ['array', 'array'=>'array', 'preserve_keys='=>'bool'],
'array_search' => ['int|string|false', 'needle'=>'mixed', 'haystack'=>'array', 'strict='=>'bool'],
'array_shift' => ['mixed|null', '&rw_array'=>'array'],
'array_slice' => ['array', 'array'=>'array', 'offset'=>'int', 'length='=>'?int', 'preserve_keys='=>'bool'],
'array_splice' => ['array', '&rw_array'=>'array', 'offset'=>'int', 'length='=>'int', 'replacement='=>'array|string'],
'array_sum' => ['int|float', 'array'=>'array'],
'array_udiff' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_assoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_assoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_assoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_assoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_unique' => ['associative-array', 'array'=>'array', 'flags='=>'int'],
'array_unshift' => ['int', '&rw_array'=>'array', 'values'=>'mixed', '...vars='=>'mixed'],
'array_values' => ['list<mixed>', 'array'=>'array'],
'array_walk' => ['bool', '&rw_array'=>'array', 'callback'=>'callable', 'arg='=>'mixed'],
'array_walk_recursive' => ['bool', '&rw_array'=>'array', 'callback'=>'callable', 'arg='=>'mixed'],
'ArrayAccess::offsetExists' => ['bool', 'offset'=>'mixed'],
'ArrayAccess::offsetGet' => ['mixed', 'offset'=>'mixed'],
'ArrayAccess::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'ArrayAccess::offsetUnset' => ['void', 'offset'=>'mixed'],
'ArrayIterator::__construct' => ['void', 'array='=>'array|object', 'flags='=>'int'],
'ArrayIterator::append' => ['void', 'value'=>'mixed'],
'ArrayIterator::asort' => ['void'],
'ArrayIterator::count' => ['int'],
'ArrayIterator::current' => ['mixed'],
'ArrayIterator::getArrayCopy' => ['array'],
'ArrayIterator::getFlags' => ['int'],
'ArrayIterator::key' => ['int|string|false'],
'ArrayIterator::ksort' => ['void'],
'ArrayIterator::natcasesort' => ['void'],
'ArrayIterator::natsort' => ['void'],
'ArrayIterator::next' => ['void'],
'ArrayIterator::offsetExists' => ['bool', 'index'=>'string|int'],
'ArrayIterator::offsetGet' => ['mixed', 'index'=>'string|int'],
'ArrayIterator::offsetSet' => ['void', 'index'=>'string|int', 'newval'=>'mixed'],
'ArrayIterator::offsetUnset' => ['void', 'index'=>'string|int'],
'ArrayIterator::rewind' => ['void'],
'ArrayIterator::seek' => ['void', 'position'=>'int'],
'ArrayIterator::serialize' => ['string'],
'ArrayIterator::setFlags' => ['void', 'flags'=>'string'],
'ArrayIterator::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayIterator::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayIterator::unserialize' => ['void', 'serialized'=>'string'],
'ArrayIterator::valid' => ['bool'],
'ArrayObject::__construct' => ['void', 'input='=>'array|object', 'flags='=>'int', 'iterator_class='=>'string'],
'ArrayObject::append' => ['void', 'value'=>'mixed'],
'ArrayObject::asort' => ['void'],
'ArrayObject::count' => ['int'],
'ArrayObject::exchangeArray' => ['array', 'ar'=>'mixed'],
'ArrayObject::getArrayCopy' => ['array'],
'ArrayObject::getFlags' => ['int'],
'ArrayObject::getIterator' => ['ArrayIterator'],
'ArrayObject::getIteratorClass' => ['string'],
'ArrayObject::ksort' => ['void'],
'ArrayObject::natcasesort' => ['void'],
'ArrayObject::natsort' => ['void'],
'ArrayObject::offsetExists' => ['bool', 'index'=>'int|string'],
'ArrayObject::offsetGet' => ['mixed|null', 'index'=>'int|string'],
'ArrayObject::offsetSet' => ['void', 'index'=>'int|string', 'newval'=>'mixed'],
'ArrayObject::offsetUnset' => ['void', 'index'=>'int|string'],
'ArrayObject::serialize' => ['string'],
'ArrayObject::setFlags' => ['void', 'flags'=>'int'],
'ArrayObject::setIteratorClass' => ['void', 'iterator_class'=>'string'],
'ArrayObject::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayObject::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayObject::unserialize' => ['void', 'serialized'=>'string'],
'arsort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'asin' => ['float', 'num'=>'float'],
'asinh' => ['float', 'num'=>'float'],
'asort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'assert' => ['bool', 'assertion'=>'string|bool|int', 'description='=>'string|Throwable|null'],
'assert_options' => ['mixed|false', 'option'=>'int', 'value='=>'mixed'],
'ast\get_kind_name' => ['string', 'kind'=>'int'],
'ast\get_metadata' => ['array<int,ast\Metadata>'],
'ast\get_supported_versions' => ['array<int,int>', 'exclude_deprecated='=>'bool'],
'ast\kind_uses_flags' => ['bool', 'kind'=>'int'],
'ast\Node::__construct' => ['void', 'kind='=>'int', 'flags='=>'int', 'children='=>'ast\Node\Decl[]|ast\Node[]|int[]|string[]|float[]|bool[]|null[]', 'start_line='=>'int'],
'ast\parse_code' => ['ast\Node', 'code'=>'string', 'version'=>'int', 'filename='=>'string'],
'ast\parse_file' => ['ast\Node', 'filename'=>'string', 'version'=>'int'],
'atan' => ['float', 'num'=>'float'],
'atan2' => ['float', 'y'=>'float', 'x'=>'float'],
'atanh' => ['float', 'num'=>'float'],
'BadFunctionCallException::__clone' => ['void'],
'BadFunctionCallException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?BadFunctionCallException'],
'BadFunctionCallException::__toString' => ['string'],
'BadFunctionCallException::getCode' => ['int'],
'BadFunctionCallException::getFile' => ['string'],
'BadFunctionCallException::getLine' => ['int'],
'BadFunctionCallException::getMessage' => ['string'],
'BadFunctionCallException::getPrevious' => ['?Throwable|?BadFunctionCallException'],
'BadFunctionCallException::getTrace' => ['list<array<string,mixed>>'],
'BadFunctionCallException::getTraceAsString' => ['string'],
'BadMethodCallException::__clone' => ['void'],
'BadMethodCallException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?BadMethodCallException'],
'BadMethodCallException::__toString' => ['string'],
'BadMethodCallException::getCode' => ['int'],
'BadMethodCallException::getFile' => ['string'],
'BadMethodCallException::getLine' => ['int'],
'BadMethodCallException::getMessage' => ['string'],
'BadMethodCallException::getPrevious' => ['?Throwable|?BadMethodCallException'],
'BadMethodCallException::getTrace' => ['list<array<string,mixed>>'],
'BadMethodCallException::getTraceAsString' => ['string'],
'base64_decode' => ['string|false', 'string'=>'string', 'strict='=>'bool'],
'base64_encode' => ['string', 'string'=>'string'],
'base_convert' => ['string', 'num'=>'string', 'from_base'=>'int', 'to_base'=>'int'],
'basename' => ['string', 'path'=>'string', 'suffix='=>'string'],
'bbcode_add_element' => ['bool', 'bbcode_container'=>'resource', 'tag_name'=>'string', 'tag_rules'=>'array'],
'bbcode_add_smiley' => ['bool', 'bbcode_container'=>'resource', 'smiley'=>'string', 'replace_by'=>'string'],
'bbcode_create' => ['resource', 'bbcode_initial_tags='=>'array'],
'bbcode_destroy' => ['bool', 'bbcode_container'=>'resource'],
'bbcode_parse' => ['string', 'bbcode_container'=>'resource', 'to_parse'=>'string'],
'bbcode_set_arg_parser' => ['bool', 'bbcode_container'=>'resource', 'bbcode_arg_parser'=>'resource'],
'bbcode_set_flags' => ['bool', 'bbcode_container'=>'resource', 'flags'=>'int', 'mode='=>'int'],
'bcadd' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int'],
'bccomp' => ['int', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int'],
'bcdiv' => ['?numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int'],
'bcmod' => ['?numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int'],
'bcmul' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int'],
'bcompiler_load' => ['bool', 'filename'=>'string'],
'bcompiler_load_exe' => ['bool', 'filename'=>'string'],
'bcompiler_parse_class' => ['bool', 'class'=>'string', 'callback'=>'string'],
'bcompiler_read' => ['bool', 'filehandle'=>'resource'],
'bcompiler_write_class' => ['bool', 'filehandle'=>'resource', 'classname'=>'string', 'extends='=>'string'],
'bcompiler_write_constant' => ['bool', 'filehandle'=>'resource', 'constantname'=>'string'],
'bcompiler_write_exe_footer' => ['bool', 'filehandle'=>'resource', 'startpos'=>'int'],
'bcompiler_write_file' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcompiler_write_footer' => ['bool', 'filehandle'=>'resource'],
'bcompiler_write_function' => ['bool', 'filehandle'=>'resource', 'functionname'=>'string'],
'bcompiler_write_functions_from_file' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcompiler_write_header' => ['bool', 'filehandle'=>'resource', 'write_ver='=>'string'],
'bcompiler_write_included_filename' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcpow' => ['numeric-string', 'num'=>'numeric-string', 'exponent'=>'numeric-string', 'scale='=>'int'],
'bcpowmod' => ['?numeric-string', 'num'=>'numeric-string', 'exponent'=>'numeric-string', 'modulus'=>'numeric-string', 'scale='=>'int'],
'bcscale' => ['int', 'scale='=>'int'],
'bcsqrt' => ['?numeric-string', 'num'=>'numeric-string', 'scale='=>'int'],
'bcsub' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int'],
'bin2hex' => ['string', 'string'=>'string'],
'bind_textdomain_codeset' => ['string', 'domain'=>'string', 'codeset'=>'string'],
'bindec' => ['float|int', 'binary_string'=>'string'],
'bindtextdomain' => ['string', 'domain'=>'string', 'directory'=>'string'],
'birdstep_autocommit' => ['bool', 'index'=>'int'],
'birdstep_close' => ['bool', 'id'=>'int'],
'birdstep_commit' => ['bool', 'index'=>'int'],
'birdstep_connect' => ['int', 'server'=>'string', 'user'=>'string', 'pass'=>'string'],
'birdstep_exec' => ['int', 'index'=>'int', 'exec_str'=>'string'],
'birdstep_fetch' => ['bool', 'index'=>'int'],
'birdstep_fieldname' => ['string', 'index'=>'int', 'col'=>'int'],
'birdstep_fieldnum' => ['int', 'index'=>'int'],
'birdstep_freeresult' => ['bool', 'index'=>'int'],
'birdstep_off_autocommit' => ['bool', 'index'=>'int'],
'birdstep_result' => ['', 'index'=>'int', 'col'=>''],
'birdstep_rollback' => ['bool', 'index'=>'int'],
'blenc_encrypt' => ['string', 'plaintext'=>'string', 'encodedfile'=>'string', 'encryption_key='=>'string'],
'boolval' => ['bool', 'value'=>'mixed'],
'bson_decode' => ['array', 'bson'=>'string'],
'bson_encode' => ['string', 'anything'=>'mixed'],
'bzclose' => ['bool', 'bz'=>'resource'],
'bzcompress' => ['string|int', 'data'=>'string', 'block_size='=>'int', 'work_factor='=>'int'],
'bzdecompress' => ['string|int', 'data'=>'string', 'use_less_memory='=>'int'],
'bzerrno' => ['int', 'bz'=>'resource'],
'bzerror' => ['array', 'bz'=>'resource'],
'bzerrstr' => ['string', 'bz'=>'resource'],
'bzflush' => ['bool', 'bz'=>'resource'],
'bzopen' => ['resource|false', 'file'=>'string|resource', 'mode'=>'string'],
'bzread' => ['string|false', 'bz'=>'resource', 'length='=>'int'],
'bzwrite' => ['int|false', 'bz'=>'resource', 'data'=>'string', 'length='=>'int'],
'CachingIterator::__construct' => ['void', 'iterator'=>'Iterator', 'flags='=>''],
'CachingIterator::__toString' => ['string'],
'CachingIterator::count' => ['int'],
'CachingIterator::current' => ['mixed'],
'CachingIterator::getCache' => ['array'],
'CachingIterator::getFlags' => ['int'],
'CachingIterator::getInnerIterator' => ['Iterator'],
'CachingIterator::hasNext' => ['bool'],
'CachingIterator::key' => ['int|string|float|bool'],
'CachingIterator::next' => ['void'],
'CachingIterator::offsetExists' => ['bool', 'index'=>'string'],
'CachingIterator::offsetGet' => ['mixed', 'index'=>'string'],
'CachingIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'mixed'],
'CachingIterator::offsetUnset' => ['void', 'index'=>'string'],
'CachingIterator::rewind' => ['void'],
'CachingIterator::setFlags' => ['void', 'flags'=>'int'],
'CachingIterator::valid' => ['bool'],
'Cairo::availableFonts' => ['array'],
'Cairo::availableSurfaces' => ['array'],
'Cairo::statusToString' => ['string', 'status'=>'int'],
'Cairo::version' => ['int'],
'Cairo::versionString' => ['string'],
'cairo_append_path' => ['', 'path'=>'cairopath', 'context'=>'cairocontext'],
'cairo_arc' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'cairo_arc_negative' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'cairo_available_fonts' => ['array'],
'cairo_available_surfaces' => ['array'],
'cairo_clip' => ['', 'context'=>'cairocontext'],
'cairo_clip_extents' => ['array', 'context'=>'cairocontext'],
'cairo_clip_preserve' => ['', 'context'=>'cairocontext'],
'cairo_clip_rectangle_list' => ['array', 'context'=>'cairocontext'],
'cairo_close_path' => ['', 'context'=>'cairocontext'],
'cairo_copy_page' => ['', 'context'=>'cairocontext'],
'cairo_copy_path' => ['CairoPath', 'context'=>'cairocontext'],
'cairo_copy_path_flat' => ['CairoPath', 'context'=>'cairocontext'],
'cairo_create' => ['CairoContext', 'surface'=>'cairosurface'],
'cairo_curve_to' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float', 'context'=>'cairocontext'],
'cairo_device_to_user' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'cairo_device_to_user_distance' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'cairo_fill' => ['', 'context'=>'cairocontext'],
'cairo_fill_extents' => ['array', 'context'=>'cairocontext'],
'cairo_fill_preserve' => ['', 'context'=>'cairocontext'],
'cairo_font_extents' => ['array', 'context'=>'cairocontext'],
'cairo_font_face_get_type' => ['int', 'fontface'=>'cairofontface'],
'cairo_font_face_status' => ['int', 'fontface'=>'cairofontface'],
'cairo_font_options_create' => ['CairoFontOptions'],
'cairo_font_options_equal' => ['bool', 'options'=>'cairofontoptions', 'other'=>'cairofontoptions'],
'cairo_font_options_get_antialias' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_hint_metrics' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_hint_style' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_subpixel_order' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_hash' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_merge' => ['void', 'options'=>'cairofontoptions', 'other'=>'cairofontoptions'],
'cairo_font_options_set_antialias' => ['void', 'options'=>'cairofontoptions', 'antialias'=>'int'],
'cairo_font_options_set_hint_metrics' => ['void', 'options'=>'cairofontoptions', 'hint_metrics'=>'int'],
'cairo_font_options_set_hint_style' => ['void', 'options'=>'cairofontoptions', 'hint_style'=>'int'],
'cairo_font_options_set_subpixel_order' => ['void', 'options'=>'cairofontoptions', 'subpixel_order'=>'int'],
'cairo_font_options_status' => ['int', 'options'=>'cairofontoptions'],
'cairo_format_stride_for_width' => ['int', 'format'=>'int', 'width'=>'int'],
'cairo_get_antialias' => ['int', 'context'=>'cairocontext'],
'cairo_get_current_point' => ['array', 'context'=>'cairocontext'],
'cairo_get_dash' => ['array', 'context'=>'cairocontext'],
'cairo_get_dash_count' => ['int', 'context'=>'cairocontext'],
'cairo_get_fill_rule' => ['int', 'context'=>'cairocontext'],
'cairo_get_font_face' => ['', 'context'=>'cairocontext'],
'cairo_get_font_matrix' => ['', 'context'=>'cairocontext'],
'cairo_get_font_options' => ['', 'context'=>'cairocontext'],
'cairo_get_group_target' => ['', 'context'=>'cairocontext'],
'cairo_get_line_cap' => ['int', 'context'=>'cairocontext'],
'cairo_get_line_join' => ['int', 'context'=>'cairocontext'],
'cairo_get_line_width' => ['float', 'context'=>'cairocontext'],
'cairo_get_matrix' => ['', 'context'=>'cairocontext'],
'cairo_get_miter_limit' => ['float', 'context'=>'cairocontext'],
'cairo_get_operator' => ['int', 'context'=>'cairocontext'],
'cairo_get_scaled_font' => ['', 'context'=>'cairocontext'],
'cairo_get_source' => ['', 'context'=>'cairocontext'],
'cairo_get_target' => ['', 'context'=>'cairocontext'],
'cairo_get_tolerance' => ['float', 'context'=>'cairocontext'],
'cairo_glyph_path' => ['', 'glyphs'=>'array', 'context'=>'cairocontext'],
'cairo_has_current_point' => ['bool', 'context'=>'cairocontext'],
'cairo_identity_matrix' => ['', 'context'=>'cairocontext'],
'cairo_image_surface_create' => ['CairoImageSurface', 'format'=>'int', 'width'=>'int', 'height'=>'int'],
'cairo_image_surface_create_for_data' => ['CairoImageSurface', 'data'=>'string', 'format'=>'int', 'width'=>'int', 'height'=>'int', 'stride='=>'int'],
'cairo_image_surface_create_from_png' => ['CairoImageSurface', 'file'=>'string'],
'cairo_image_surface_get_data' => ['string', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_format' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_height' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_stride' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_width' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_in_fill' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_in_stroke' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_line_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_mask' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'cairo_mask_surface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'cairo_matrix_create_scale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'cairo_matrix_init' => ['object', 'xx='=>'float', 'yx='=>'float', 'xy='=>'float', 'yy='=>'float', 'x0='=>'float', 'y0='=>'float'],
'cairo_matrix_init_identity' => ['object'],
'cairo_matrix_init_rotate' => ['object', 'radians'=>'float'],
'cairo_matrix_init_scale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'cairo_matrix_init_translate' => ['object', 'tx'=>'float', 'ty'=>'float'],
'cairo_matrix_invert' => ['void', 'matrix'=>'cairomatrix'],
'cairo_matrix_multiply' => ['CairoMatrix', 'matrix1'=>'cairomatrix', 'matrix2'=>'cairomatrix'],
'cairo_matrix_rotate' => ['', 'matrix'=>'cairomatrix', 'radians'=>'float'],
'cairo_matrix_scale' => ['', 'sx'=>'float', 'sy'=>'float', 'context'=>'cairocontext'],
'cairo_matrix_transform_distance' => ['array', 'matrix'=>'cairomatrix', 'dx'=>'float', 'dy'=>'float'],
'cairo_matrix_transform_point' => ['array', 'matrix'=>'cairomatrix', 'dx'=>'float', 'dy'=>'float'],
'cairo_matrix_translate' => ['void', 'matrix'=>'cairomatrix', 'tx'=>'float', 'ty'=>'float'],
'cairo_move_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_new_path' => ['', 'context'=>'cairocontext'],
'cairo_new_sub_path' => ['', 'context'=>'cairocontext'],
'cairo_paint' => ['', 'context'=>'cairocontext'],
'cairo_paint_with_alpha' => ['', 'alpha'=>'string', 'context'=>'cairocontext'],
'cairo_path_extents' => ['array', 'context'=>'cairocontext'],
'cairo_pattern_add_color_stop_rgb' => ['void', 'pattern'=>'cairogradientpattern', 'offset'=>'float', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'cairo_pattern_add_color_stop_rgba' => ['void', 'pattern'=>'cairogradientpattern', 'offset'=>'float', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha'=>'float'],
'cairo_pattern_create_for_surface' => ['CairoPattern', 'surface'=>'cairosurface'],
'cairo_pattern_create_linear' => ['CairoPattern', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float'],
'cairo_pattern_create_radial' => ['CairoPattern', 'x0'=>'float', 'y0'=>'float', 'r0'=>'float', 'x1'=>'float', 'y1'=>'float', 'r1'=>'float'],
'cairo_pattern_create_rgb' => ['CairoPattern', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'cairo_pattern_create_rgba' => ['CairoPattern', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha'=>'float'],
'cairo_pattern_get_color_stop_count' => ['int', 'pattern'=>'cairogradientpattern'],
'cairo_pattern_get_color_stop_rgba' => ['array', 'pattern'=>'cairogradientpattern', 'index'=>'int'],
'cairo_pattern_get_extend' => ['int', 'pattern'=>'string'],
'cairo_pattern_get_filter' => ['int', 'pattern'=>'cairosurfacepattern'],
'cairo_pattern_get_linear_points' => ['array', 'pattern'=>'cairolineargradient'],
'cairo_pattern_get_matrix' => ['CairoMatrix', 'pattern'=>'cairopattern'],
'cairo_pattern_get_radial_circles' => ['array', 'pattern'=>'cairoradialgradient'],
'cairo_pattern_get_rgba' => ['array', 'pattern'=>'cairosolidpattern'],
'cairo_pattern_get_surface' => ['CairoSurface', 'pattern'=>'cairosurfacepattern'],
'cairo_pattern_get_type' => ['int', 'pattern'=>'cairopattern'],
'cairo_pattern_set_extend' => ['void', 'pattern'=>'string', 'extend'=>'string'],
'cairo_pattern_set_filter' => ['void', 'pattern'=>'cairosurfacepattern', 'filter'=>'int'],
'cairo_pattern_set_matrix' => ['void', 'pattern'=>'cairopattern', 'matrix'=>'cairomatrix'],
'cairo_pattern_status' => ['int', 'pattern'=>'cairopattern'],
'cairo_pdf_surface_create' => ['CairoPdfSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_pdf_surface_set_size' => ['void', 'surface'=>'cairopdfsurface', 'width'=>'float', 'height'=>'float'],
'cairo_pop_group' => ['', 'context'=>'cairocontext'],
'cairo_pop_group_to_source' => ['', 'context'=>'cairocontext'],
'cairo_ps_get_levels' => ['array'],
'cairo_ps_level_to_string' => ['string', 'level'=>'int'],
'cairo_ps_surface_create' => ['CairoPsSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_ps_surface_dsc_begin_page_setup' => ['void', 'surface'=>'cairopssurface'],
'cairo_ps_surface_dsc_begin_setup' => ['void', 'surface'=>'cairopssurface'],
'cairo_ps_surface_dsc_comment' => ['void', 'surface'=>'cairopssurface', 'comment'=>'string'],
'cairo_ps_surface_get_eps' => ['bool', 'surface'=>'cairopssurface'],
'cairo_ps_surface_restrict_to_level' => ['void', 'surface'=>'cairopssurface', 'level'=>'int'],
'cairo_ps_surface_set_eps' => ['void', 'surface'=>'cairopssurface', 'level'=>'bool'],
'cairo_ps_surface_set_size' => ['void', 'surface'=>'cairopssurface', 'width'=>'float', 'height'=>'float'],
'cairo_push_group' => ['', 'context'=>'cairocontext'],
'cairo_push_group_with_content' => ['', 'content'=>'string', 'context'=>'cairocontext'],
'cairo_rectangle' => ['', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string', 'context'=>'cairocontext'],
'cairo_rel_curve_to' => ['', 'x1'=>'string', 'y1'=>'string', 'x2'=>'string', 'y2'=>'string', 'x3'=>'string', 'y3'=>'string', 'context'=>'cairocontext'],
'cairo_rel_line_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_rel_move_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_reset_clip' => ['', 'context'=>'cairocontext'],
'cairo_restore' => ['', 'context'=>'cairocontext'],
'cairo_rotate' => ['', 'sx'=>'string', 'sy'=>'string', 'context'=>'cairocontext', 'angle'=>'string'],
'cairo_save' => ['', 'context'=>'cairocontext'],
'cairo_scale' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_scaled_font_create' => ['CairoScaledFont', 'fontface'=>'cairofontface', 'matrix'=>'cairomatrix', 'ctm'=>'cairomatrix', 'fontoptions'=>'cairofontoptions'],
'cairo_scaled_font_extents' => ['array', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_ctm' => ['CairoMatrix', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_face' => ['CairoFontFace', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_matrix' => ['CairoFontOptions', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_options' => ['CairoFontOptions', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_scale_matrix' => ['CairoMatrix', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_type' => ['int', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_glyph_extents' => ['array', 'scaledfont'=>'cairoscaledfont', 'glyphs'=>'array'],
'cairo_scaled_font_status' => ['int', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_text_extents' => ['array', 'scaledfont'=>'cairoscaledfont', 'text'=>'string'],
'cairo_select_font_face' => ['', 'family'=>'string', 'slant='=>'string', 'weight='=>'string', 'context='=>'cairocontext'],
'cairo_set_antialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'cairo_set_dash' => ['', 'dashes'=>'array', 'offset='=>'string', 'context='=>'cairocontext'],
'cairo_set_fill_rule' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_font_face' => ['', 'fontface'=>'cairofontface', 'context'=>'cairocontext'],
'cairo_set_font_matrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_set_font_options' => ['', 'fontoptions'=>'cairofontoptions', 'context'=>'cairocontext'],
'cairo_set_font_size' => ['', 'size'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_cap' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_join' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_width' => ['', 'width'=>'string', 'context'=>'cairocontext'],
'cairo_set_matrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_set_miter_limit' => ['', 'limit'=>'string', 'context'=>'cairocontext'],
'cairo_set_operator' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_scaled_font' => ['', 'scaledfont'=>'cairoscaledfont', 'context'=>'cairocontext'],
'cairo_set_source' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'cairo_set_source_surface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'cairo_set_tolerance' => ['', 'tolerance'=>'string', 'context'=>'cairocontext'],
'cairo_show_page' => ['', 'context'=>'cairocontext'],
'cairo_show_text' => ['', 'text'=>'string', 'context'=>'cairocontext'],
'cairo_status' => ['int', 'context'=>'cairocontext'],
'cairo_status_to_string' => ['string', 'status'=>'int'],
'cairo_stroke' => ['', 'context'=>'cairocontext'],
'cairo_stroke_extents' => ['array', 'context'=>'cairocontext'],
'cairo_stroke_preserve' => ['', 'context'=>'cairocontext'],
'cairo_surface_copy_page' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_create_similar' => ['CairoSurface', 'surface'=>'cairosurface', 'content'=>'int', 'width'=>'float', 'height'=>'float'],
'cairo_surface_finish' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_flush' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_get_content' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_get_device_offset' => ['array', 'surface'=>'cairosurface'],
'cairo_surface_get_font_options' => ['CairoFontOptions', 'surface'=>'cairosurface'],
'cairo_surface_get_type' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_mark_dirty' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_mark_dirty_rectangle' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'cairo_surface_set_device_offset' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float'],
'cairo_surface_set_fallback_resolution' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float'],
'cairo_surface_show_page' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_status' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_write_to_png' => ['void', 'surface'=>'cairosurface', 'stream'=>'resource'],
'cairo_svg_get_versions' => ['array'],
'cairo_svg_surface_create' => ['CairoSvgSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_svg_surface_get_versions' => ['array'],
'cairo_svg_surface_restrict_to_version' => ['void', 'surface'=>'cairosvgsurface', 'version'=>'int'],
'cairo_svg_version_to_string' => ['string', 'version'=>'int'],
'cairo_text_extents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'cairo_text_path' => ['', 'string'=>'string', 'context'=>'cairocontext', 'text'=>'string'],
'cairo_transform' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_translate' => ['', 'tx'=>'string', 'ty'=>'string', 'context'=>'cairocontext', 'x'=>'string', 'y'=>'string'],
'cairo_user_to_device' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_user_to_device_distance' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_version' => ['int'],
'cairo_version_string' => ['string'],
'CairoContext::__construct' => ['void', 'surface'=>'CairoSurface'],
'CairoContext::appendPath' => ['', 'path'=>'cairopath', 'context'=>'cairocontext'],
'CairoContext::arc' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'CairoContext::arcNegative' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'CairoContext::clip' => ['', 'context'=>'cairocontext'],
'CairoContext::clipExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::clipPreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::clipRectangleList' => ['array', 'context'=>'cairocontext'],
'CairoContext::closePath' => ['', 'context'=>'cairocontext'],
'CairoContext::copyPage' => ['', 'context'=>'cairocontext'],
'CairoContext::copyPath' => ['CairoPath', 'context'=>'cairocontext'],
'CairoContext::copyPathFlat' => ['CairoPath', 'context'=>'cairocontext'],
'CairoContext::curveTo' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float', 'context'=>'cairocontext'],
'CairoContext::deviceToUser' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'CairoContext::deviceToUserDistance' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'CairoContext::fill' => ['', 'context'=>'cairocontext'],
'CairoContext::fillExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::fillPreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::fontExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::getAntialias' => ['int', 'context'=>'cairocontext'],
'CairoContext::getCurrentPoint' => ['array', 'context'=>'cairocontext'],
'CairoContext::getDash' => ['array', 'context'=>'cairocontext'],
'CairoContext::getDashCount' => ['int', 'context'=>'cairocontext'],
'CairoContext::getFillRule' => ['int', 'context'=>'cairocontext'],
'CairoContext::getFontFace' => ['', 'context'=>'cairocontext'],
'CairoContext::getFontMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoContext::getGroupTarget' => ['', 'context'=>'cairocontext'],
'CairoContext::getLineCap' => ['int', 'context'=>'cairocontext'],
'CairoContext::getLineJoin' => ['int', 'context'=>'cairocontext'],
'CairoContext::getLineWidth' => ['float', 'context'=>'cairocontext'],
'CairoContext::getMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::getMiterLimit' => ['float', 'context'=>'cairocontext'],
'CairoContext::getOperator' => ['int', 'context'=>'cairocontext'],
'CairoContext::getScaledFont' => ['', 'context'=>'cairocontext'],
'CairoContext::getSource' => ['', 'context'=>'cairocontext'],
'CairoContext::getTarget' => ['', 'context'=>'cairocontext'],
'CairoContext::getTolerance' => ['float', 'context'=>'cairocontext'],
'CairoContext::glyphPath' => ['', 'glyphs'=>'array', 'context'=>'cairocontext'],
'CairoContext::hasCurrentPoint' => ['bool', 'context'=>'cairocontext'],
'CairoContext::identityMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::inFill' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::inStroke' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::lineTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::mask' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'CairoContext::maskSurface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'CairoContext::moveTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::newPath' => ['', 'context'=>'cairocontext'],
'CairoContext::newSubPath' => ['', 'context'=>'cairocontext'],
'CairoContext::paint' => ['', 'context'=>'cairocontext'],
'CairoContext::paintWithAlpha' => ['', 'alpha'=>'string', 'context'=>'cairocontext'],
'CairoContext::pathExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::popGroup' => ['', 'context'=>'cairocontext'],
'CairoContext::popGroupToSource' => ['', 'context'=>'cairocontext'],
'CairoContext::pushGroup' => ['', 'context'=>'cairocontext'],
'CairoContext::pushGroupWithContent' => ['', 'content'=>'string', 'context'=>'cairocontext'],
'CairoContext::rectangle' => ['', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string', 'context'=>'cairocontext'],
'CairoContext::relCurveTo' => ['', 'x1'=>'string', 'y1'=>'string', 'x2'=>'string', 'y2'=>'string', 'x3'=>'string', 'y3'=>'string', 'context'=>'cairocontext'],
'CairoContext::relLineTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::relMoveTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::resetClip' => ['', 'context'=>'cairocontext'],
'CairoContext::restore' => ['', 'context'=>'cairocontext'],
'CairoContext::rotate' => ['', 'angle'=>'string', 'context'=>'cairocontext'],
'CairoContext::save' => ['', 'context'=>'cairocontext'],
'CairoContext::scale' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::selectFontFace' => ['', 'family'=>'string', 'slant='=>'string', 'weight='=>'string', 'context='=>'cairocontext'],
'CairoContext::setAntialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'CairoContext::setDash' => ['', 'dashes'=>'array', 'offset='=>'string', 'context='=>'cairocontext'],
'CairoContext::setFillRule' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setFontFace' => ['', 'fontface'=>'cairofontface', 'context'=>'cairocontext'],
'CairoContext::setFontMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::setFontOptions' => ['', 'fontoptions'=>'cairofontoptions', 'context'=>'cairocontext'],
'CairoContext::setFontSize' => ['', 'size'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineCap' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineJoin' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineWidth' => ['', 'width'=>'string', 'context'=>'cairocontext'],
'CairoContext::setMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::setMiterLimit' => ['', 'limit'=>'string', 'context'=>'cairocontext'],
'CairoContext::setOperator' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setScaledFont' => ['', 'scaledfont'=>'cairoscaledfont', 'context'=>'cairocontext'],
'CairoContext::setSource' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'CairoContext::setSourceRGB' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'CairoContext::setSourceRGBA' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'CairoContext::setSourceSurface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'CairoContext::setTolerance' => ['', 'tolerance'=>'string', 'context'=>'cairocontext'],
'CairoContext::showPage' => ['', 'context'=>'cairocontext'],
'CairoContext::showText' => ['', 'text'=>'string', 'context'=>'cairocontext'],
'CairoContext::status' => ['int', 'context'=>'cairocontext'],
'CairoContext::stroke' => ['', 'context'=>'cairocontext'],
'CairoContext::strokeExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::strokePreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::textExtents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'CairoContext::textPath' => ['', 'string'=>'string', 'context'=>'cairocontext', 'text'=>'string'],
'CairoContext::transform' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::translate' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::userToDevice' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::userToDeviceDistance' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoFontFace::__construct' => ['void'],
'CairoFontFace::getType' => ['int'],
'CairoFontFace::status' => ['int', 'fontface'=>'cairofontface'],
'CairoFontOptions::__construct' => ['void'],
'CairoFontOptions::equal' => ['bool', 'other'=>'string'],
'CairoFontOptions::getAntialias' => ['int', 'context'=>'cairocontext'],
'CairoFontOptions::getHintMetrics' => ['int'],
'CairoFontOptions::getHintStyle' => ['int'],
'CairoFontOptions::getSubpixelOrder' => ['int'],
'CairoFontOptions::hash' => ['int'],
'CairoFontOptions::merge' => ['void', 'other'=>'string'],
'CairoFontOptions::setAntialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'CairoFontOptions::setHintMetrics' => ['void', 'hint_metrics'=>'string'],
'CairoFontOptions::setHintStyle' => ['void', 'hint_style'=>'string'],
'CairoFontOptions::setSubpixelOrder' => ['void', 'subpixel_order'=>'string'],
'CairoFontOptions::status' => ['int', 'context'=>'cairocontext'],
'CairoFormat::strideForWidth' => ['int', 'format'=>'int', 'width'=>'int'],
'CairoGradientPattern::addColorStopRgb' => ['void', 'offset'=>'string', 'red'=>'string', 'green'=>'string', 'blue'=>'string'],
'CairoGradientPattern::addColorStopRgba' => ['void', 'offset'=>'string', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string'],
'CairoGradientPattern::getColorStopCount' => ['int'],
'CairoGradientPattern::getColorStopRgba' => ['array', 'index'=>'string'],
'CairoGradientPattern::getExtend' => ['int'],
'CairoGradientPattern::setExtend' => ['void', 'extend'=>'int'],
'CairoImageSurface::__construct' => ['void', 'format'=>'int', 'width'=>'int', 'height'=>'int'],
'CairoImageSurface::createForData' => ['void', 'data'=>'string', 'format'=>'int', 'width'=>'int', 'height'=>'int', 'stride='=>'int'],
'CairoImageSurface::createFromPng' => ['CairoImageSurface', 'file'=>'string'],
'CairoImageSurface::getData' => ['string'],
'CairoImageSurface::getFormat' => ['int'],
'CairoImageSurface::getHeight' => ['int'],
'CairoImageSurface::getStride' => ['int'],
'CairoImageSurface::getWidth' => ['int'],
'CairoLinearGradient::__construct' => ['void', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float'],
'CairoLinearGradient::getPoints' => ['array'],
'CairoMatrix::__construct' => ['void', 'xx='=>'float', 'yx='=>'float', 'xy='=>'float', 'yy='=>'float', 'x0='=>'float', 'y0='=>'float'],
'CairoMatrix::initIdentity' => ['object'],
'CairoMatrix::initRotate' => ['object', 'radians'=>'float'],
'CairoMatrix::initScale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'CairoMatrix::initTranslate' => ['object', 'tx'=>'float', 'ty'=>'float'],
'CairoMatrix::invert' => ['void'],
'CairoMatrix::multiply' => ['CairoMatrix', 'matrix1'=>'cairomatrix', 'matrix2'=>'cairomatrix'],
'CairoMatrix::rotate' => ['', 'sx'=>'string', 'sy'=>'string', 'context'=>'cairocontext', 'angle'=>'string'],
'CairoMatrix::scale' => ['', 'sx'=>'float', 'sy'=>'float', 'context'=>'cairocontext'],
'CairoMatrix::transformDistance' => ['array', 'dx'=>'string', 'dy'=>'string'],
'CairoMatrix::transformPoint' => ['array', 'dx'=>'string', 'dy'=>'string'],
'CairoMatrix::translate' => ['', 'tx'=>'string', 'ty'=>'string', 'context'=>'cairocontext', 'x'=>'string', 'y'=>'string'],
'CairoPattern::__construct' => ['void'],
'CairoPattern::getMatrix' => ['', 'context'=>'cairocontext'],
'CairoPattern::getType' => ['int'],
'CairoPattern::setMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoPattern::status' => ['int', 'context'=>'cairocontext'],
'CairoPdfSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoPdfSurface::setSize' => ['void', 'width'=>'string', 'height'=>'string'],
'CairoPsSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoPsSurface::dscBeginPageSetup' => ['void'],
'CairoPsSurface::dscBeginSetup' => ['void'],
'CairoPsSurface::dscComment' => ['void', 'comment'=>'string'],
'CairoPsSurface::getEps' => ['bool'],
'CairoPsSurface::getLevels' => ['array'],
'CairoPsSurface::levelToString' => ['string', 'level'=>'int'],
'CairoPsSurface::restrictToLevel' => ['void', 'level'=>'string'],
'CairoPsSurface::setEps' => ['void', 'level'=>'string'],
'CairoPsSurface::setSize' => ['void', 'width'=>'string', 'height'=>'string'],
'CairoRadialGradient::__construct' => ['void', 'x0'=>'float', 'y0'=>'float', 'r0'=>'float', 'x1'=>'float', 'y1'=>'float', 'r1'=>'float'],
'CairoRadialGradient::getCircles' => ['array'],
'CairoScaledFont::__construct' => ['void', 'font_face'=>'CairoFontFace', 'matrix'=>'CairoMatrix', 'ctm'=>'CairoMatrix', 'options'=>'CairoFontOptions'],
'CairoScaledFont::extents' => ['array'],
'CairoScaledFont::getCtm' => ['CairoMatrix'],
'CairoScaledFont::getFontFace' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getFontMatrix' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getScaleMatrix' => ['void'],
'CairoScaledFont::getType' => ['int'],
'CairoScaledFont::glyphExtents' => ['array', 'glyphs'=>'string'],
'CairoScaledFont::status' => ['int', 'context'=>'cairocontext'],
'CairoScaledFont::textExtents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'CairoSolidPattern::__construct' => ['void', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha='=>'float'],
'CairoSolidPattern::getRgba' => ['array'],
'CairoSurface::__construct' => ['void'],
'CairoSurface::copyPage' => ['', 'context'=>'cairocontext'],
'CairoSurface::createSimilar' => ['void', 'other'=>'cairosurface', 'content'=>'int', 'width'=>'string', 'height'=>'string'],
'CairoSurface::finish' => ['void'],
'CairoSurface::flush' => ['void'],
'CairoSurface::getContent' => ['int'],
'CairoSurface::getDeviceOffset' => ['array'],
'CairoSurface::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoSurface::getType' => ['int'],
'CairoSurface::markDirty' => ['void'],
'CairoSurface::markDirtyRectangle' => ['void', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string'],
'CairoSurface::setDeviceOffset' => ['void', 'x'=>'string', 'y'=>'string'],
'CairoSurface::setFallbackResolution' => ['void', 'x'=>'string', 'y'=>'string'],
'CairoSurface::showPage' => ['', 'context'=>'cairocontext'],
'CairoSurface::status' => ['int', 'context'=>'cairocontext'],
'CairoSurface::writeToPng' => ['void', 'file'=>'string'],
'CairoSurfacePattern::__construct' => ['void', 'surface'=>'CairoSurface'],
'CairoSurfacePattern::getExtend' => ['int'],
'CairoSurfacePattern::getFilter' => ['int'],
'CairoSurfacePattern::getSurface' => ['void'],
'CairoSurfacePattern::setExtend' => ['void', 'extend'=>'int'],
'CairoSurfacePattern::setFilter' => ['void', 'filter'=>'string'],
'CairoSvgSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoSvgSurface::getVersions' => ['array'],
'CairoSvgSurface::restrictToVersion' => ['void', 'version'=>'string'],
'CairoSvgSurface::versionToString' => ['string', 'version'=>'int'],
'cal_days_in_month' => ['int', 'calendar'=>'int', 'month'=>'int', 'year'=>'int'],
'cal_from_jd' => ['false|array{date:string,month:int,day:int,year:int,dow:int,abbrevdayname:string,dayname:string,abbrevmonth:string,monthname:string}', 'julian_day'=>'int', 'calendar'=>'int'],
'cal_info' => ['array', 'calendar='=>'int'],
'cal_to_jd' => ['int', 'calendar'=>'int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'calcul_hmac' => ['string', 'clent'=>'string', 'siretcode'=>'string', 'price'=>'string', 'reference'=>'string', 'validity'=>'string', 'taxation'=>'string', 'devise'=>'string', 'language'=>'string'],
'calculhmac' => ['string', 'clent'=>'string', 'data'=>'string'],
'call_user_func' => ['mixed|false', 'callback'=>'callable', '...args='=>'mixed'],
'call_user_func_array' => ['mixed|false', 'callback'=>'callable', 'args'=>'list<mixed>'],
'call_user_method' => ['mixed', 'method_name'=>'string', 'object'=>'object', 'parameter='=>'mixed', '...args='=>'mixed'],
'call_user_method_array' => ['mixed', 'method_name'=>'string', 'object'=>'object', 'params'=>'list<mixed>'],
'CallbackFilterIterator::__construct' => ['void', 'iterator'=>'Iterator', 'func'=>'callable(mixed):bool|callable(mixed,mixed):bool|callable(mixed,mixed,mixed):bool'],
'CallbackFilterIterator::accept' => ['bool'],
'CallbackFilterIterator::current' => ['mixed'],
'CallbackFilterIterator::getInnerIterator' => ['Iterator'],
'CallbackFilterIterator::key' => ['mixed'],
'CallbackFilterIterator::next' => ['void'],
'CallbackFilterIterator::rewind' => ['void'],
'CallbackFilterIterator::valid' => ['bool'],
'ceil' => ['float|int', 'num'=>'float'],
'chdb::__construct' => ['void', 'pathname'=>'string'],
'chdb::get' => ['string', 'key'=>'string'],
'chdb_create' => ['bool', 'pathname'=>'string', 'data'=>'array'],
'chdir' => ['bool', 'directory'=>'string'],
'checkdate' => ['bool', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'checkdnsrr' => ['bool', 'hostname'=>'string', 'type='=>'string'],
'chgrp' => ['bool', 'filename'=>'string', 'group'=>'string|int'],
'chmod' => ['bool', 'filename'=>'string', 'permissions'=>'int'],
'chop' => ['string', 'string'=>'string', 'characters='=>'string'],
'chown' => ['bool', 'filename'=>'string', 'user'=>'string|int'],
'chr' => ['string', 'codepoint'=>'int'],
'chroot' => ['bool', 'directory'=>'string'],
'chunk_split' => ['string', 'string'=>'string', 'length='=>'int', 'separator='=>'string'],
'class_alias' => ['bool', 'class'=>'string', 'alias'=>'string', 'autoload='=>'bool'],
'class_exists' => ['bool', 'class'=>'string', 'autoload='=>'bool'],
'class_implements' => ['array<string,string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'class_parents' => ['array<string, class-string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'class_uses' => ['array<string,string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'classkit_import' => ['array', 'filename'=>'string'],
'classkit_method_add' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int'],
'classkit_method_copy' => ['bool', 'dclass'=>'string', 'dmethod'=>'string', 'sclass'=>'string', 'smethod='=>'string'],
'classkit_method_redefine' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int'],
'classkit_method_remove' => ['bool', 'classname'=>'string', 'methodname'=>'string'],
'classkit_method_rename' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'newname'=>'string'],
'classObj::__construct' => ['void', 'layer'=>'layerObj', 'class'=>'classObj'],
'classObj::addLabel' => ['int', 'label'=>'labelObj'],
'classObj::convertToString' => ['string'],
'classObj::createLegendIcon' => ['imageObj', 'width'=>'int', 'height'=>'int'],
'classObj::deletestyle' => ['int', 'index'=>'int'],
'classObj::drawLegendIcon' => ['int', 'width'=>'int', 'height'=>'int', 'im'=>'imageObj', 'dstX'=>'int', 'dstY'=>'int'],
'classObj::free' => ['void'],
'classObj::getExpressionString' => ['string'],
'classObj::getLabel' => ['labelObj', 'index'=>'int'],
'classObj::getMetaData' => ['int', 'name'=>'string'],
'classObj::getStyle' => ['styleObj', 'index'=>'int'],
'classObj::getTextString' => ['string'],
'classObj::movestyledown' => ['int', 'index'=>'int'],
'classObj::movestyleup' => ['int', 'index'=>'int'],
'classObj::ms_newClassObj' => ['classObj', 'layer'=>'layerObj', 'class'=>'classObj'],
'classObj::removeLabel' => ['labelObj', 'index'=>'int'],
'classObj::removeMetaData' => ['int', 'name'=>'string'],
'classObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'classObj::setExpression' => ['int', 'expression'=>'string'],
'classObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'classObj::settext' => ['int', 'text'=>'string'],
'classObj::updateFromString' => ['int', 'snippet'=>'string'],
'clearstatcache' => ['void', 'clear_realpath_cache='=>'bool', 'filename='=>'string'],
'cli_get_process_title' => ['string'],
'cli_set_process_title' => ['bool', 'title'=>'string'],
'ClosedGeneratorException::__clone' => ['void'],
'ClosedGeneratorException::__toString' => ['string'],
'ClosedGeneratorException::getCode' => ['int'],
'ClosedGeneratorException::getFile' => ['string'],
'ClosedGeneratorException::getLine' => ['int'],
'ClosedGeneratorException::getMessage' => ['string'],
'ClosedGeneratorException::getPrevious' => ['Throwable|ClosedGeneratorException|null'],
'ClosedGeneratorException::getTrace' => ['list<array<string,mixed>>'],
'ClosedGeneratorException::getTraceAsString' => ['string'],
'closedir' => ['void', 'dir_handle='=>'resource'],
'closelog' => ['bool'],
'Closure::__construct' => ['void'],
'Closure::__invoke' => ['', '...args='=>''],
'Closure::bind' => ['Closure|false', 'old'=>'Closure', 'to'=>'?object', 'scope='=>'object|string'],
'Closure::bindTo' => ['Closure|false', 'new'=>'?object', 'newscope='=>'object|string'],
'Closure::call' => ['', 'to'=>'object', '...parameters='=>''],
'Closure::fromCallable' => ['Closure', 'callable'=>'callable'],
'clusterObj::convertToString' => ['string'],
'clusterObj::getFilterString' => ['string'],
'clusterObj::getGroupString' => ['string'],
'clusterObj::setFilter' => ['int', 'expression'=>'string'],
'clusterObj::setGroup' => ['int', 'expression'=>'string'],
'Collator::__construct' => ['void', 'locale'=>'string'],
'Collator::asort' => ['bool', '&rw_arr'=>'array', 'sort_flag='=>'int'],
'Collator::compare' => ['int|false', 'string1'=>'string', 'string2'=>'string'],
'Collator::create' => ['?Collator', 'locale'=>'string'],
'Collator::getAttribute' => ['int|false', 'attr'=>'int'],
'Collator::getErrorCode' => ['int'],
'Collator::getErrorMessage' => ['string'],
'Collator::getLocale' => ['string', 'type'=>'int'],
'Collator::getSortKey' => ['string|false', 'string'=>'string'],
'Collator::getStrength' => ['int|false'],
'Collator::setAttribute' => ['bool', 'attr'=>'int', 'value'=>'int'],
'Collator::setStrength' => ['bool', 'strength'=>'int'],
'Collator::sort' => ['bool', '&rw_arr'=>'array', 'sort_flags='=>'int'],
'Collator::sortWithSortKeys' => ['bool', '&rw_arr'=>'array'],
'collator_asort' => ['bool', 'object'=>'collator', '&rw_array'=>'array', 'flags='=>'int'],
'collator_compare' => ['int', 'object'=>'collator', 'string1'=>'string', 'string2'=>'string'],
'collator_create' => ['Collator', 'locale'=>'string'],
'collator_get_attribute' => ['int|false', 'object'=>'collator', 'attribute'=>'int'],
'collator_get_error_code' => ['int', 'object'=>'collator'],
'collator_get_error_message' => ['string', 'object'=>'collator'],
'collator_get_locale' => ['string', 'object'=>'collator', 'type'=>'int'],
'collator_get_sort_key' => ['string', 'object'=>'collator', 'string'=>'string'],
'collator_get_strength' => ['int|false', 'object'=>'collator'],
'collator_set_attribute' => ['bool', 'object'=>'collator', 'attribute'=>'int', 'value'=>'int'],
'collator_set_strength' => ['bool', 'object'=>'collator', 'strength'=>'int'],
'collator_sort' => ['bool', 'object'=>'collator', '&rw_array'=>'array', 'flags='=>'int'],
'collator_sort_with_sort_keys' => ['bool', 'object'=>'collator', '&rw_array'=>'array'],
'Collectable::isGarbage' => ['bool'],
'Collectable::setGarbage' => ['void'],
'colorObj::setHex' => ['int', 'hex'=>'string'],
'colorObj::toHex' => ['string'],
'COM::__call' => ['', 'name'=>'', 'args'=>''],
'COM::__construct' => ['void', 'module_name'=>'string', 'server_name='=>'mixed', 'codepage='=>'int', 'typelib='=>'string'],
'COM::__get' => ['', 'name'=>''],
'COM::__set' => ['void', 'name'=>'', 'value'=>''],
'com_addref' => [''],
'com_create_guid' => ['string'],
'com_event_sink' => ['bool', 'variant'=>'VARIANT', 'sink_object'=>'object', 'sink_interface='=>'mixed'],
'com_get_active_object' => ['VARIANT', 'prog_id'=>'string', 'codepage='=>'int'],
'com_isenum' => ['bool', 'com_module'=>'variant'],
'com_load_typelib' => ['bool', 'typelib'=>'string', 'case_insensitive='=>'int'],
'com_message_pump' => ['bool', 'timeout_milliseconds='=>'int'],
'com_print_typeinfo' => ['bool', 'variant'=>'object', 'dispatch_interface='=>'string', 'display_sink='=>'bool'],
'commonmark\cql::__invoke' => ['', 'root'=>'CommonMark\Node', 'handler'=>'callable'],
'commonmark\interfaces\ivisitable::accept' => ['void', 'visitor'=>'CommonMark\Interfaces\IVisitor'],
'commonmark\interfaces\ivisitor::enter' => ['?int|IVisitable', 'visitable'=>'IVisitable'],
'commonmark\interfaces\ivisitor::leave' => ['?int|IVisitable', 'visitable'=>'IVisitable'],
'commonmark\node::accept' => ['void', 'visitor'=>'CommonMark\Interfaces\IVisitor'],
'commonmark\node::appendChild' => ['CommonMark\Node', 'child'=>'CommonMark\Node'],
'commonmark\node::insertAfter' => ['CommonMark\Node', 'sibling'=>'CommonMark\Node'],
'commonmark\node::insertBefore' => ['CommonMark\Node', 'sibling'=>'CommonMark\Node'],
'commonmark\node::prependChild' => ['CommonMark\Node', 'child'=>'CommonMark\Node'],
'commonmark\node::replace' => ['CommonMark\Node', 'target'=>'CommonMark\Node'],
'commonmark\node::unlink' => ['void'],
'commonmark\parse' => ['CommonMark\Node', 'content'=>'string', 'options='=>'int'],
'commonmark\parser::finish' => ['CommonMark\Node'],
'commonmark\parser::parse' => ['void', 'buffer'=>'string'],
'commonmark\render' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\html' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int'],
'commonmark\render\latex' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\man' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\xml' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int'],
'compact' => ['array<string, mixed>', 'var_name'=>'string|array', '...var_names='=>'string|array'],
'COMPersistHelper::__construct' => ['void', 'variant'=>'object'],
'COMPersistHelper::GetCurFile' => ['string'],
'COMPersistHelper::GetCurFileName' => ['string'],
'COMPersistHelper::GetMaxStreamSize' => ['int'],
'COMPersistHelper::InitNew' => ['int'],
'COMPersistHelper::LoadFromFile' => ['bool', 'filename'=>'string', 'flags'=>'int'],
'COMPersistHelper::LoadFromStream' => ['', 'stream'=>''],
'COMPersistHelper::SaveToFile' => ['bool', 'filename'=>'string', 'remember'=>'bool'],
'COMPersistHelper::SaveToStream' => ['int', 'stream'=>''],
'componere\abstract\definition::addInterface' => ['Componere\Abstract\Definition', 'interface'=>'string'],
'componere\abstract\definition::addMethod' => ['Componere\Abstract\Definition', 'name'=>'string', 'method'=>'Componere\Method'],
'componere\abstract\definition::addTrait' => ['Componere\Abstract\Definition', 'trait'=>'string'],
'componere\abstract\definition::getReflector' => ['ReflectionClass'],
'componere\cast' => ['object', 'arg1'=>'string', 'object'=>'object'],
'componere\cast_by_ref' => ['object', 'arg1'=>'string', 'object'=>'object'],
'componere\definition::addConstant' => ['Componere\Definition', 'name'=>'string', 'value'=>'Componere\Value'],
'componere\definition::addProperty' => ['Componere\Definition', 'name'=>'string', 'value'=>'Componere\Value'],
'componere\definition::getClosure' => ['Closure', 'name'=>'string'],
'componere\definition::getClosures' => ['Closure[]'],
'componere\definition::isRegistered' => ['bool'],
'componere\definition::register' => ['void'],
'componere\method::getReflector' => ['ReflectionMethod'],
'componere\method::setPrivate' => ['Method'],
'componere\method::setProtected' => ['Method'],
'componere\method::setStatic' => ['Method'],
'componere\patch::apply' => ['void'],
'componere\patch::derive' => ['Componere\Patch', 'instance'=>'object'],
'componere\patch::getClosure' => ['Closure', 'name'=>'string'],
'componere\patch::getClosures' => ['Closure[]'],
'componere\patch::isApplied' => ['bool'],
'componere\patch::revert' => ['void'],
'componere\value::hasDefault' => ['bool'],
'componere\value::isPrivate' => ['bool'],
'componere\value::isProtected' => ['bool'],
'componere\value::isStatic' => ['bool'],
'componere\value::setPrivate' => ['Value'],
'componere\value::setProtected' => ['Value'],
'componere\value::setStatic' => ['Value'],
'Cond::broadcast' => ['bool', 'condition'=>'long'],
'Cond::create' => ['long'],
'Cond::destroy' => ['bool', 'condition'=>'long'],
'Cond::signal' => ['bool', 'condition'=>'long'],
'Cond::wait' => ['bool', 'condition'=>'long', 'mutex'=>'long', 'timeout='=>'long'],
'confirm_pdo_ibm_compiled' => [''],
'connection_aborted' => ['int'],
'connection_status' => ['int'],
'connection_timeout' => ['int'],
'constant' => ['mixed', 'name'=>'string'],
'convert_cyr_string' => ['string', 'string'=>'string', 'from'=>'string', 'to'=>'string'],
'convert_uudecode' => ['string', 'string'=>'string'],
'convert_uuencode' => ['string', 'string'=>'string'],
'copy' => ['bool', 'from'=>'string', 'to'=>'string', 'context='=>'resource'],
'cos' => ['float', 'num'=>'float'],
'cosh' => ['float', 'num'=>'float'],
'Couchbase\AnalyticsQuery::__construct' => ['void'],
'Couchbase\AnalyticsQuery::fromString' => ['Couchbase\AnalyticsQuery', 'statement'=>'string'],
'Couchbase\basicDecoderV1' => ['mixed', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int', 'options'=>'array'],
'Couchbase\basicEncoderV1' => ['array', 'value'=>'mixed', 'options'=>'array'],
'Couchbase\BooleanFieldSearchQuery::__construct' => ['void'],
'Couchbase\BooleanFieldSearchQuery::boost' => ['Couchbase\BooleanFieldSearchQuery', 'boost'=>'float'],
'Couchbase\BooleanFieldSearchQuery::field' => ['Couchbase\BooleanFieldSearchQuery', 'field'=>'string'],
'Couchbase\BooleanFieldSearchQuery::jsonSerialize' => ['array'],
'Couchbase\BooleanSearchQuery::__construct' => ['void'],
'Couchbase\BooleanSearchQuery::boost' => ['Couchbase\BooleanSearchQuery', 'boost'=>'float'],
'Couchbase\BooleanSearchQuery::jsonSerialize' => ['array'],
'Couchbase\BooleanSearchQuery::must' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\BooleanSearchQuery::mustNot' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\BooleanSearchQuery::should' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\Bucket::__construct' => ['void'],
'Couchbase\Bucket::__get' => ['int', 'name'=>'string'],
'Couchbase\Bucket::__set' => ['int', 'name'=>'string', 'value'=>'int'],
'Couchbase\Bucket::append' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::counter' => ['Couchbase\Document|array', 'ids'=>'array|string', 'delta='=>'int', 'options='=>'array'],
'Couchbase\Bucket::decryptFields' => ['array', 'document'=>'array', 'fieldOptions'=>'', 'prefix='=>'string'],
'Couchbase\Bucket::diag' => ['array', 'reportId='=>'string'],
'Couchbase\Bucket::encryptFields' => ['array', 'document'=>'array', 'fieldOptions'=>'', 'prefix='=>'string'],
'Couchbase\Bucket::get' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::getAndLock' => ['Couchbase\Document|array', 'ids'=>'array|string', 'lockTime'=>'int', 'options='=>'array'],
'Couchbase\Bucket::getAndTouch' => ['Couchbase\Document|array', 'ids'=>'array|string', 'expiry'=>'int', 'options='=>'array'],
'Couchbase\Bucket::getFromReplica' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::getName' => ['string'],
'Couchbase\Bucket::insert' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::listExists' => ['bool', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listGet' => ['mixed', 'id'=>'string', 'index'=>'int'],
'Couchbase\Bucket::listPush' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listRemove' => ['', 'id'=>'string', 'index'=>'int'],
'Couchbase\Bucket::listSet' => ['', 'id'=>'string', 'index'=>'int', 'value'=>'mixed'],
'Couchbase\Bucket::listShift' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::lookupIn' => ['Couchbase\LookupInBuilder', 'id'=>'string'],
'Couchbase\Bucket::manager' => ['Couchbase\BucketManager'],
'Couchbase\Bucket::mapAdd' => ['', 'id'=>'string', 'key'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::mapGet' => ['mixed', 'id'=>'string', 'key'=>'string'],
'Couchbase\Bucket::mapRemove' => ['', 'id'=>'string', 'key'=>'string'],
'Couchbase\Bucket::mapSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::mutateIn' => ['Couchbase\MutateInBuilder', 'id'=>'string', 'cas'=>'string'],
'Couchbase\Bucket::ping' => ['array', 'services='=>'int', 'reportId='=>'string'],
'Couchbase\Bucket::prepend' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::query' => ['object', 'query'=>'Couchbase\AnalyticsQuery|Couchbase\N1qlQuery|Couchbase\SearchQuery|Couchbase\SpatialViewQuery|Couchbase\ViewQuery', 'jsonAsArray='=>'bool'],
'Couchbase\Bucket::queueAdd' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::queueExists' => ['bool', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::queueRemove' => ['mixed', 'id'=>'string'],
'Couchbase\Bucket::queueSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::remove' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::replace' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::retrieveIn' => ['Couchbase\DocumentFragment', 'id'=>'string', '...paths='=>'array<int,string>'],
'Couchbase\Bucket::setAdd' => ['', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setExists' => ['bool', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setRemove' => ['', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::setTranscoder' => ['', 'encoder'=>'callable', 'decoder'=>'callable'],
'Couchbase\Bucket::touch' => ['Couchbase\Document|array', 'ids'=>'array|string', 'expiry'=>'int', 'options='=>'array'],
'Couchbase\Bucket::unlock' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::upsert' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\BucketManager::__construct' => ['void'],
'Couchbase\BucketManager::createN1qlIndex' => ['', 'name'=>'string', 'fields'=>'array', 'whereClause='=>'string', 'ignoreIfExist='=>'bool', 'defer='=>'bool'],
'Couchbase\BucketManager::createN1qlPrimaryIndex' => ['', 'customName='=>'string', 'ignoreIfExist='=>'bool', 'defer='=>'bool'],
'Couchbase\BucketManager::dropN1qlIndex' => ['', 'name'=>'string', 'ignoreIfNotExist='=>'bool'],
'Couchbase\BucketManager::dropN1qlPrimaryIndex' => ['', 'customName='=>'string', 'ignoreIfNotExist='=>'bool'],
'Couchbase\BucketManager::flush' => [''],
'Couchbase\BucketManager::getDesignDocument' => ['array', 'name'=>'string'],
'Couchbase\BucketManager::info' => ['array'],
'Couchbase\BucketManager::insertDesignDocument' => ['', 'name'=>'string', 'document'=>'array'],
'Couchbase\BucketManager::listDesignDocuments' => ['array'],
'Couchbase\BucketManager::listN1qlIndexes' => ['array'],
'Couchbase\BucketManager::removeDesignDocument' => ['', 'name'=>'string'],
'Couchbase\BucketManager::upsertDesignDocument' => ['', 'name'=>'string', 'document'=>'array'],
'Couchbase\ClassicAuthenticator::bucket' => ['', 'name'=>'string', 'password'=>'string'],
'Couchbase\ClassicAuthenticator::cluster' => ['', 'username'=>'string', 'password'=>'string'],
'Couchbase\Cluster::__construct' => ['void', 'connstr'=>'string'],
'Couchbase\Cluster::authenticate' => ['null', 'authenticator'=>'Couchbase\Authenticator'],
'Couchbase\Cluster::authenticateAs' => ['null', 'username'=>'string', 'password'=>'string'],
'Couchbase\Cluster::manager' => ['Couchbase\ClusterManager', 'username='=>'string', 'password='=>'string'],
'Couchbase\Cluster::openBucket' => ['Couchbase\Bucket', 'name='=>'string', 'password='=>'string'],
'Couchbase\ClusterManager::__construct' => ['void'],
'Couchbase\ClusterManager::createBucket' => ['', 'name'=>'string', 'options='=>'array'],
'Couchbase\ClusterManager::getUser' => ['array', 'username'=>'string', 'domain='=>'int'],
'Couchbase\ClusterManager::info' => ['array'],
'Couchbase\ClusterManager::listBuckets' => ['array'],
'Couchbase\ClusterManager::listUsers' => ['array', 'domain='=>'int'],
'Couchbase\ClusterManager::removeBucket' => ['', 'name'=>'string'],
'Couchbase\ClusterManager::removeUser' => ['', 'name'=>'string', 'domain='=>'int'],
'Couchbase\ClusterManager::upsertUser' => ['', 'name'=>'string', 'settings'=>'Couchbase\UserSettings', 'domain='=>'int'],
'Couchbase\ConjunctionSearchQuery::__construct' => ['void'],
'Couchbase\ConjunctionSearchQuery::boost' => ['Couchbase\ConjunctionSearchQuery', 'boost'=>'float'],
'Couchbase\ConjunctionSearchQuery::every' => ['Couchbase\ConjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\ConjunctionSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchFacet::__construct' => ['void'],
'Couchbase\DateRangeSearchFacet::addRange' => ['Couchbase\DateRangeSearchFacet', 'name'=>'string', 'start'=>'int|string', 'end'=>'int|string'],
'Couchbase\DateRangeSearchFacet::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchQuery::__construct' => ['void'],
'Couchbase\DateRangeSearchQuery::boost' => ['Couchbase\DateRangeSearchQuery', 'boost'=>'float'],
'Couchbase\DateRangeSearchQuery::dateTimeParser' => ['Couchbase\DateRangeSearchQuery', 'dateTimeParser'=>'string'],
'Couchbase\DateRangeSearchQuery::end' => ['Couchbase\DateRangeSearchQuery', 'end'=>'int|string', 'inclusive='=>'bool'],
'Couchbase\DateRangeSearchQuery::field' => ['Couchbase\DateRangeSearchQuery', 'field'=>'string'],
'Couchbase\DateRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchQuery::start' => ['Couchbase\DateRangeSearchQuery', 'start'=>'int|string', 'inclusive='=>'bool'],
'Couchbase\defaultDecoder' => ['mixed', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int'],
'Couchbase\defaultEncoder' => ['array', 'value'=>'mixed'],
'Couchbase\DisjunctionSearchQuery::__construct' => ['void'],
'Couchbase\DisjunctionSearchQuery::boost' => ['Couchbase\DisjunctionSearchQuery', 'boost'=>'float'],
'Couchbase\DisjunctionSearchQuery::either' => ['Couchbase\DisjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\DisjunctionSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DisjunctionSearchQuery::min' => ['Couchbase\DisjunctionSearchQuery', 'min'=>'int'],
'Couchbase\DocIdSearchQuery::__construct' => ['void'],
'Couchbase\DocIdSearchQuery::boost' => ['Couchbase\DocIdSearchQuery', 'boost'=>'float'],
'Couchbase\DocIdSearchQuery::docIds' => ['Couchbase\DocIdSearchQuery', '...documentIds='=>'array<int,string>'],
'Couchbase\DocIdSearchQuery::field' => ['Couchbase\DocIdSearchQuery', 'field'=>'string'],
'Couchbase\DocIdSearchQuery::jsonSerialize' => ['array'],
'Couchbase\fastlzCompress' => ['string', 'data'=>'string'],
'Couchbase\fastlzDecompress' => ['string', 'data'=>'string'],
'Couchbase\GeoBoundingBoxSearchQuery::__construct' => ['void'],
'Couchbase\GeoBoundingBoxSearchQuery::boost' => ['Couchbase\GeoBoundingBoxSearchQuery', 'boost'=>'float'],
'Couchbase\GeoBoundingBoxSearchQuery::field' => ['Couchbase\GeoBoundingBoxSearchQuery', 'field'=>'string'],
'Couchbase\GeoBoundingBoxSearchQuery::jsonSerialize' => ['array'],
'Couchbase\GeoDistanceSearchQuery::__construct' => ['void'],
'Couchbase\GeoDistanceSearchQuery::boost' => ['Couchbase\GeoDistanceSearchQuery', 'boost'=>'float'],
'Couchbase\GeoDistanceSearchQuery::field' => ['Couchbase\GeoDistanceSearchQuery', 'field'=>'string'],
'Couchbase\GeoDistanceSearchQuery::jsonSerialize' => ['array'],
'Couchbase\LookupInBuilder::__construct' => ['void'],
'Couchbase\LookupInBuilder::execute' => ['Couchbase\DocumentFragment'],
'Couchbase\LookupInBuilder::exists' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\LookupInBuilder::get' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\LookupInBuilder::getCount' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\MatchAllSearchQuery::__construct' => ['void'],
'Couchbase\MatchAllSearchQuery::boost' => ['Couchbase\MatchAllSearchQuery', 'boost'=>'float'],
'Couchbase\MatchAllSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchNoneSearchQuery::__construct' => ['void'],
'Couchbase\MatchNoneSearchQuery::boost' => ['Couchbase\MatchNoneSearchQuery', 'boost'=>'float'],
'Couchbase\MatchNoneSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchPhraseSearchQuery::__construct' => ['void'],
'Couchbase\MatchPhraseSearchQuery::analyzer' => ['Couchbase\MatchPhraseSearchQuery', 'analyzer'=>'string'],
'Couchbase\MatchPhraseSearchQuery::boost' => ['Couchbase\MatchPhraseSearchQuery', 'boost'=>'float'],
'Couchbase\MatchPhraseSearchQuery::field' => ['Couchbase\MatchPhraseSearchQuery', 'field'=>'string'],
'Couchbase\MatchPhraseSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchSearchQuery::__construct' => ['void'],
'Couchbase\MatchSearchQuery::analyzer' => ['Couchbase\MatchSearchQuery', 'analyzer'=>'string'],
'Couchbase\MatchSearchQuery::boost' => ['Couchbase\MatchSearchQuery', 'boost'=>'float'],
'Couchbase\MatchSearchQuery::field' => ['Couchbase\MatchSearchQuery', 'field'=>'string'],
'Couchbase\MatchSearchQuery::fuzziness' => ['Couchbase\MatchSearchQuery', 'fuzziness'=>'int'],
'Couchbase\MatchSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchSearchQuery::prefixLength' => ['Couchbase\MatchSearchQuery', 'prefixLength'=>'int'],
'Couchbase\MutateInBuilder::__construct' => ['void'],
'Couchbase\MutateInBuilder::arrayAddUnique' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayAppend' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayAppendAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayInsert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\MutateInBuilder::arrayInsertAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array'],
'Couchbase\MutateInBuilder::arrayPrepend' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayPrependAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::counter' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'delta'=>'int', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::execute' => ['Couchbase\DocumentFragment'],
'Couchbase\MutateInBuilder::insert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::modeDocument' => ['', 'mode'=>'int'],
'Couchbase\MutateInBuilder::remove' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\MutateInBuilder::replace' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\MutateInBuilder::upsert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::withExpiry' => ['Couchbase\MutateInBuilder', 'expiry'=>'Couchbase\expiry'],
'Couchbase\MutationState::__construct' => ['void'],
'Couchbase\MutationState::add' => ['', 'source'=>'Couchbase\Document|Couchbase\DocumentFragment|array'],
'Couchbase\MutationState::from' => ['Couchbase\MutationState', 'source'=>'Couchbase\Document|Couchbase\DocumentFragment|array'],
'Couchbase\MutationToken::__construct' => ['void'],
'Couchbase\MutationToken::bucketName' => ['string'],
'Couchbase\MutationToken::from' => ['', 'bucketName'=>'string', 'vbucketId'=>'int', 'vbucketUuid'=>'string', 'sequenceNumber'=>'string'],
'Couchbase\MutationToken::sequenceNumber' => ['string'],
'Couchbase\MutationToken::vbucketId' => ['int'],
'Couchbase\MutationToken::vbucketUuid' => ['string'],
'Couchbase\N1qlIndex::__construct' => ['void'],
'Couchbase\N1qlQuery::__construct' => ['void'],
'Couchbase\N1qlQuery::adhoc' => ['Couchbase\N1qlQuery', 'adhoc'=>'bool'],
'Couchbase\N1qlQuery::consistency' => ['Couchbase\N1qlQuery', 'consistency'=>'int'],
'Couchbase\N1qlQuery::consistentWith' => ['Couchbase\N1qlQuery', 'state'=>'Couchbase\MutationState'],
'Couchbase\N1qlQuery::crossBucket' => ['Couchbase\N1qlQuery', 'crossBucket'=>'bool'],
'Couchbase\N1qlQuery::fromString' => ['Couchbase\N1qlQuery', 'statement'=>'string'],
'Couchbase\N1qlQuery::maxParallelism' => ['Couchbase\N1qlQuery', 'maxParallelism'=>'int'],
'Couchbase\N1qlQuery::namedParams' => ['Couchbase\N1qlQuery', 'params'=>'array'],
'Couchbase\N1qlQuery::pipelineBatch' => ['Couchbase\N1qlQuery', 'pipelineBatch'=>'int'],
'Couchbase\N1qlQuery::pipelineCap' => ['Couchbase\N1qlQuery', 'pipelineCap'=>'int'],
'Couchbase\N1qlQuery::positionalParams' => ['Couchbase\N1qlQuery', 'params'=>'array'],
'Couchbase\N1qlQuery::profile' => ['', 'profileType'=>'string'],
'Couchbase\N1qlQuery::readonly' => ['Couchbase\N1qlQuery', 'readonly'=>'bool'],
'Couchbase\N1qlQuery::scanCap' => ['Couchbase\N1qlQuery', 'scanCap'=>'int'],
'Couchbase\NumericRangeSearchFacet::__construct' => ['void'],
'Couchbase\NumericRangeSearchFacet::addRange' => ['Couchbase\NumericRangeSearchFacet', 'name'=>'string', 'min'=>'float', 'max'=>'float'],
'Couchbase\NumericRangeSearchFacet::jsonSerialize' => ['array'],
'Couchbase\NumericRangeSearchQuery::__construct' => ['void'],
'Couchbase\NumericRangeSearchQuery::boost' => ['Couchbase\NumericRangeSearchQuery', 'boost'=>'float'],
'Couchbase\NumericRangeSearchQuery::field' => ['Couchbase\NumericRangeSearchQuery', 'field'=>'string'],
'Couchbase\NumericRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\NumericRangeSearchQuery::max' => ['Couchbase\NumericRangeSearchQuery', 'max'=>'float', 'inclusive='=>'bool'],
'Couchbase\NumericRangeSearchQuery::min' => ['Couchbase\NumericRangeSearchQuery', 'min'=>'float', 'inclusive='=>'bool'],
'Couchbase\passthruDecoder' => ['string', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int'],
'Couchbase\passthruEncoder' => ['array', 'value'=>'string'],
'Couchbase\PasswordAuthenticator::password' => ['Couchbase\PasswordAuthenticator', 'password'=>'string'],
'Couchbase\PasswordAuthenticator::username' => ['Couchbase\PasswordAuthenticator', 'username'=>'string'],
'Couchbase\PhraseSearchQuery::__construct' => ['void'],
'Couchbase\PhraseSearchQuery::boost' => ['Couchbase\PhraseSearchQuery', 'boost'=>'float'],
'Couchbase\PhraseSearchQuery::field' => ['Couchbase\PhraseSearchQuery', 'field'=>'string'],
'Couchbase\PhraseSearchQuery::jsonSerialize' => ['array'],
'Couchbase\PrefixSearchQuery::__construct' => ['void'],
'Couchbase\PrefixSearchQuery::boost' => ['Couchbase\PrefixSearchQuery', 'boost'=>'float'],
'Couchbase\PrefixSearchQuery::field' => ['Couchbase\PrefixSearchQuery', 'field'=>'string'],
'Couchbase\PrefixSearchQuery::jsonSerialize' => ['array'],
'Couchbase\QueryStringSearchQuery::__construct' => ['void'],
'Couchbase\QueryStringSearchQuery::boost' => ['Couchbase\QueryStringSearchQuery', 'boost'=>'float'],
'Couchbase\QueryStringSearchQuery::jsonSerialize' => ['array'],
'Couchbase\RegexpSearchQuery::__construct' => ['void'],
'Couchbase\RegexpSearchQuery::boost' => ['Couchbase\RegexpSearchQuery', 'boost'=>'float'],
'Couchbase\RegexpSearchQuery::field' => ['Couchbase\RegexpSearchQuery', 'field'=>'string'],
'Couchbase\RegexpSearchQuery::jsonSerialize' => ['array'],
'Couchbase\SearchQuery::__construct' => ['void', 'indexName'=>'string', 'queryPart'=>'Couchbase\SearchQueryPart'],
'Couchbase\SearchQuery::addFacet' => ['Couchbase\SearchQuery', 'name'=>'string', 'facet'=>'Couchbase\SearchFacet'],
'Couchbase\SearchQuery::boolean' => ['Couchbase\BooleanSearchQuery'],
'Couchbase\SearchQuery::booleanField' => ['Couchbase\BooleanFieldSearchQuery', 'value'=>'bool'],
'Couchbase\SearchQuery::conjuncts' => ['Couchbase\ConjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\SearchQuery::consistentWith' => ['Couchbase\SearchQuery', 'state'=>'Couchbase\MutationState'],
'Couchbase\SearchQuery::dateRange' => ['Couchbase\DateRangeSearchQuery'],
'Couchbase\SearchQuery::dateRangeFacet' => ['Couchbase\DateRangeSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::disjuncts' => ['Couchbase\DisjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\SearchQuery::docId' => ['Couchbase\DocIdSearchQuery', '...documentIds='=>'array<int,string>'],
'Couchbase\SearchQuery::explain' => ['Couchbase\SearchQuery', 'explain'=>'bool'],
'Couchbase\SearchQuery::fields' => ['Couchbase\SearchQuery', '...fields='=>'array<int,string>'],
'Couchbase\SearchQuery::geoBoundingBox' => ['Couchbase\GeoBoundingBoxSearchQuery', 'topLeftLongitude'=>'float', 'topLeftLatitude'=>'float', 'bottomRightLongitude'=>'float', 'bottomRightLatitude'=>'float'],
'Couchbase\SearchQuery::geoDistance' => ['Couchbase\GeoDistanceSearchQuery', 'longitude'=>'float', 'latitude'=>'float', 'distance'=>'string'],
'Couchbase\SearchQuery::highlight' => ['Couchbase\SearchQuery', 'style'=>'string', '...fields='=>'array<int,string>'],
'Couchbase\SearchQuery::jsonSerialize' => ['array'],
'Couchbase\SearchQuery::limit' => ['Couchbase\SearchQuery', 'limit'=>'int'],
'Couchbase\SearchQuery::match' => ['Couchbase\MatchSearchQuery', 'match'=>'string'],
'Couchbase\SearchQuery::matchAll' => ['Couchbase\MatchAllSearchQuery'],
'Couchbase\SearchQuery::matchNone' => ['Couchbase\MatchNoneSearchQuery'],
'Couchbase\SearchQuery::matchPhrase' => ['Couchbase\MatchPhraseSearchQuery', '...terms='=>'array<int,string>'],
'Couchbase\SearchQuery::numericRange' => ['Couchbase\NumericRangeSearchQuery'],
'Couchbase\SearchQuery::numericRangeFacet' => ['Couchbase\NumericRangeSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::prefix' => ['Couchbase\PrefixSearchQuery', 'prefix'=>'string'],
'Couchbase\SearchQuery::queryString' => ['Couchbase\QueryStringSearchQuery', 'queryString'=>'string'],
'Couchbase\SearchQuery::regexp' => ['Couchbase\RegexpSearchQuery', 'regexp'=>'string'],
'Couchbase\SearchQuery::serverSideTimeout' => ['Couchbase\SearchQuery', 'serverSideTimeout'=>'int'],
'Couchbase\SearchQuery::skip' => ['Couchbase\SearchQuery', 'skip'=>'int'],
'Couchbase\SearchQuery::sort' => ['Couchbase\SearchQuery', '...sort='=>'array<int,Couchbase\sort>'],
'Couchbase\SearchQuery::term' => ['Couchbase\TermSearchQuery', 'term'=>'string'],
'Couchbase\SearchQuery::termFacet' => ['Couchbase\TermSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::termRange' => ['Couchbase\TermRangeSearchQuery'],
'Couchbase\SearchQuery::wildcard' => ['Couchbase\WildcardSearchQuery', 'wildcard'=>'string'],
'Couchbase\SearchSort::__construct' => ['void'],
'Couchbase\SearchSort::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSort::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSort::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSort::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortField::__construct' => ['void'],
'Couchbase\SearchSortField::descending' => ['Couchbase\SearchSortField', 'descending'=>'bool'],
'Couchbase\SearchSortField::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortField::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortField::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortField::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortField::missing' => ['', 'missing'=>'string'],
'Couchbase\SearchSortField::mode' => ['', 'mode'=>'string'],
'Couchbase\SearchSortField::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortField::type' => ['', 'type'=>'string'],
'Couchbase\SearchSortGeoDistance::__construct' => ['void'],
'Couchbase\SearchSortGeoDistance::descending' => ['Couchbase\SearchSortGeoDistance', 'descending'=>'bool'],
'Couchbase\SearchSortGeoDistance::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortGeoDistance::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortGeoDistance::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortGeoDistance::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortGeoDistance::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortGeoDistance::unit' => ['Couchbase\SearchSortGeoDistance', 'unit'=>'string'],
'Couchbase\SearchSortId::__construct' => ['void'],
'Couchbase\SearchSortId::descending' => ['Couchbase\SearchSortId', 'descending'=>'bool'],
'Couchbase\SearchSortId::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortId::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortId::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortId::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortId::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortScore::__construct' => ['void'],
'Couchbase\SearchSortScore::descending' => ['Couchbase\SearchSortScore', 'descending'=>'bool'],
'Couchbase\SearchSortScore::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortScore::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortScore::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortScore::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortScore::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SpatialViewQuery::__construct' => ['void'],
'Couchbase\SpatialViewQuery::bbox' => ['Couchbase\SpatialViewQuery', 'bbox'=>'array'],
'Couchbase\SpatialViewQuery::consistency' => ['Couchbase\SpatialViewQuery', 'consistency'=>'int'],
'Couchbase\SpatialViewQuery::custom' => ['', 'customParameters'=>'array'],
'Couchbase\SpatialViewQuery::encode' => ['array'],
'Couchbase\SpatialViewQuery::endRange' => ['Couchbase\SpatialViewQuery', 'range'=>'array'],
'Couchbase\SpatialViewQuery::limit' => ['Couchbase\SpatialViewQuery', 'limit'=>'int'],
'Couchbase\SpatialViewQuery::order' => ['Couchbase\SpatialViewQuery', 'order'=>'int'],
'Couchbase\SpatialViewQuery::skip' => ['Couchbase\SpatialViewQuery', 'skip'=>'int'],
'Couchbase\SpatialViewQuery::startRange' => ['Couchbase\SpatialViewQuery', 'range'=>'array'],
'Couchbase\TermRangeSearchQuery::__construct' => ['void'],
'Couchbase\TermRangeSearchQuery::boost' => ['Couchbase\TermRangeSearchQuery', 'boost'=>'float'],
'Couchbase\TermRangeSearchQuery::field' => ['Couchbase\TermRangeSearchQuery', 'field'=>'string'],
'Couchbase\TermRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\TermRangeSearchQuery::max' => ['Couchbase\TermRangeSearchQuery', 'max'=>'string', 'inclusive='=>'bool'],
'Couchbase\TermRangeSearchQuery::min' => ['Couchbase\TermRangeSearchQuery', 'min'=>'string', 'inclusive='=>'bool'],
'Couchbase\TermSearchFacet::__construct' => ['void'],
'Couchbase\TermSearchFacet::jsonSerialize' => ['array'],
'Couchbase\TermSearchQuery::__construct' => ['void'],
'Couchbase\TermSearchQuery::boost' => ['Couchbase\TermSearchQuery', 'boost'=>'float'],
'Couchbase\TermSearchQuery::field' => ['Couchbase\TermSearchQuery', 'field'=>'string'],
'Couchbase\TermSearchQuery::fuzziness' => ['Couchbase\TermSearchQuery', 'fuzziness'=>'int'],
'Couchbase\TermSearchQuery::jsonSerialize' => ['array'],
'Couchbase\TermSearchQuery::prefixLength' => ['Couchbase\TermSearchQuery', 'prefixLength'=>'int'],
'Couchbase\UserSettings::fullName' => ['Couchbase\UserSettings', 'fullName'=>'string'],
'Couchbase\UserSettings::password' => ['Couchbase\UserSettings', 'password'=>'string'],
'Couchbase\UserSettings::role' => ['Couchbase\UserSettings', 'role'=>'string', 'bucket='=>'string'],
'Couchbase\ViewQuery::__construct' => ['void'],
'Couchbase\ViewQuery::consistency' => ['Couchbase\ViewQuery', 'consistency'=>'int'],
'Couchbase\ViewQuery::custom' => ['Couchbase\ViewQuery', 'customParameters'=>'array'],
'Couchbase\ViewQuery::encode' => ['array'],
'Couchbase\ViewQuery::from' => ['Couchbase\ViewQuery', 'designDocumentName'=>'string', 'viewName'=>'string'],
'Couchbase\ViewQuery::fromSpatial' => ['Couchbase\SpatialViewQuery', 'designDocumentName'=>'string', 'viewName'=>'string'],
'Couchbase\ViewQuery::group' => ['Couchbase\ViewQuery', 'group'=>'bool'],
'Couchbase\ViewQuery::groupLevel' => ['Couchbase\ViewQuery', 'groupLevel'=>'int'],
'Couchbase\ViewQuery::idRange' => ['Couchbase\ViewQuery', 'startKeyDocumentId'=>'string', 'endKeyDocumentId'=>'string'],
'Couchbase\ViewQuery::key' => ['Couchbase\ViewQuery', 'key'=>'mixed'],
'Couchbase\ViewQuery::keys' => ['Couchbase\ViewQuery', 'keys'=>'array'],
'Couchbase\ViewQuery::limit' => ['Couchbase\ViewQuery', 'limit'=>'int'],
'Couchbase\ViewQuery::order' => ['Couchbase\ViewQuery', 'order'=>'int'],
'Couchbase\ViewQuery::range' => ['Couchbase\ViewQuery', 'startKey'=>'mixed', 'endKey'=>'mixed', 'inclusiveEnd='=>'bool'],
'Couchbase\ViewQuery::reduce' => ['Couchbase\ViewQuery', 'reduce'=>'bool'],
'Couchbase\ViewQuery::skip' => ['Couchbase\ViewQuery', 'skip'=>'int'],
'Couchbase\ViewQueryEncodable::encode' => ['array'],
'Couchbase\WildcardSearchQuery::__construct' => ['void'],
'Couchbase\WildcardSearchQuery::boost' => ['Couchbase\WildcardSearchQuery', 'boost'=>'float'],
'Couchbase\WildcardSearchQuery::field' => ['Couchbase\WildcardSearchQuery', 'field'=>'string'],
'Couchbase\WildcardSearchQuery::jsonSerialize' => ['array'],
'Couchbase\zlibCompress' => ['string', 'data'=>'string'],
'Couchbase\zlibDecompress' => ['string', 'data'=>'string'],
'count' => ['int', 'value'=>'Countable|array|SimpleXMLElement|ResourceBundle', 'mode='=>'int'],
'count_chars' => ['mixed', 'string'=>'string', 'mode='=>'int'],
'Countable::count' => ['int'],
'crack_check' => ['bool', 'dictionary'=>'', 'password'=>'string'],
'crack_closedict' => ['bool', 'dictionary='=>'resource'],
'crack_getlastmessage' => ['string'],
'crack_opendict' => ['resource|false', 'dictionary'=>'string'],
'crash' => [''],
'crc32' => ['int', 'string'=>'string'],
'create_function' => ['string', 'args'=>'string', 'code'=>'string'],
'crypt' => ['string', 'string'=>'string', 'salt='=>'string'],
'ctype_alnum' => ['bool', 'text'=>'string|int'],
'ctype_alpha' => ['bool', 'text'=>'string|int'],
'ctype_cntrl' => ['bool', 'text'=>'string|int'],
'ctype_digit' => ['bool', 'text'=>'string|int'],
'ctype_graph' => ['bool', 'text'=>'string|int'],
'ctype_lower' => ['bool', 'text'=>'string|int'],
'ctype_print' => ['bool', 'text'=>'string|int'],
'ctype_punct' => ['bool', 'text'=>'string|int'],
'ctype_space' => ['bool', 'text'=>'string|int'],
'ctype_upper' => ['bool', 'text'=>'string|int'],
'ctype_xdigit' => ['bool', 'text'=>'string|int'],
'cubrid_affected_rows' => ['int', 'req_identifier='=>''],
'cubrid_bind' => ['bool', 'req_identifier'=>'resource', 'bind_param'=>'int', 'bind_value'=>'mixed', 'bind_value_type='=>'string'],
'cubrid_client_encoding' => ['string', 'conn_identifier='=>''],
'cubrid_close' => ['bool', 'conn_identifier='=>''],
'cubrid_close_prepare' => ['bool', 'req_identifier'=>'resource'],
'cubrid_close_request' => ['bool', 'req_identifier'=>'resource'],
'cubrid_col_get' => ['array', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string'],
'cubrid_col_size' => ['int', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string'],
'cubrid_column_names' => ['array', 'req_identifier'=>'resource'],
'cubrid_column_types' => ['array', 'req_identifier'=>'resource'],
'cubrid_commit' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_connect' => ['resource', 'host'=>'string', 'port'=>'int', 'dbname'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_connect_with_url' => ['resource', 'conn_url'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_current_oid' => ['string', 'req_identifier'=>'resource'],
'cubrid_data_seek' => ['bool', 'req_identifier'=>'', 'row_number'=>'int'],
'cubrid_db_name' => ['string', 'result'=>'array', 'index'=>'int'],
'cubrid_db_parameter' => ['array', 'conn_identifier'=>'resource'],
'cubrid_disconnect' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_errno' => ['int', 'conn_identifier='=>''],
'cubrid_error' => ['string', 'connection='=>''],
'cubrid_error_code' => ['int'],
'cubrid_error_code_facility' => ['int'],
'cubrid_error_msg' => ['string'],
'cubrid_execute' => ['bool', 'conn_identifier'=>'', 'sql'=>'string', 'option='=>'int', 'request_identifier='=>''],
'cubrid_fetch' => ['mixed', 'result'=>'resource', 'type='=>'int'],
'cubrid_fetch_array' => ['array', 'result'=>'resource', 'type='=>'int'],
'cubrid_fetch_assoc' => ['array', 'result'=>'resource'],
'cubrid_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'cubrid_fetch_lengths' => ['array', 'result'=>'resource'],
'cubrid_fetch_object' => ['object', 'result'=>'resource', 'class_name='=>'string', 'params='=>'array'],
'cubrid_fetch_row' => ['array', 'result'=>'resource'],
'cubrid_field_flags' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_len' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_name' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_seek' => ['bool', 'result'=>'resource', 'field_offset='=>'int'],
'cubrid_field_table' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_type' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_free_result' => ['bool', 'req_identifier'=>'resource'],
'cubrid_get' => ['mixed', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr='=>'mixed'],
'cubrid_get_autocommit' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_get_charset' => ['string', 'conn_identifier'=>'resource'],
'cubrid_get_class_name' => ['string', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_get_client_info' => ['string'],
'cubrid_get_db_parameter' => ['array', 'conn_identifier'=>'resource'],
'cubrid_get_query_timeout' => ['int', 'req_identifier'=>'resource'],
'cubrid_get_server_info' => ['string', 'conn_identifier'=>'resource'],
'cubrid_insert_id' => ['string', 'conn_identifier='=>'resource'],
'cubrid_is_instance' => ['int', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_list_dbs' => ['array', 'conn_identifier'=>'resource'],
'cubrid_load_from_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string', 'file_name'=>'string'],
'cubrid_lob2_bind' => ['bool', 'req_identifier'=>'resource', 'bind_index'=>'int', 'bind_value'=>'mixed', 'bind_value_type='=>'string'],
'cubrid_lob2_close' => ['bool', 'lob_identifier'=>'resource'],
'cubrid_lob2_export' => ['bool', 'lob_identifier'=>'resource', 'file_name'=>'string'],
'cubrid_lob2_import' => ['bool', 'lob_identifier'=>'resource', 'file_name'=>'string'],
'cubrid_lob2_new' => ['resource', 'conn_identifier='=>'resource', 'type='=>'string'],
'cubrid_lob2_read' => ['string', 'lob_identifier'=>'resource', 'length'=>'int'],
'cubrid_lob2_seek' => ['bool', 'lob_identifier'=>'resource', 'offset'=>'int', 'origin='=>'int'],
'cubrid_lob2_seek64' => ['bool', 'lob_identifier'=>'resource', 'offset'=>'string', 'origin='=>'int'],
'cubrid_lob2_size' => ['int', 'lob_identifier'=>'resource'],
'cubrid_lob2_size64' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lob2_tell' => ['int', 'lob_identifier'=>'resource'],
'cubrid_lob2_tell64' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lob2_write' => ['bool', 'lob_identifier'=>'resource', 'buf'=>'string'],
'cubrid_lob_close' => ['bool', 'lob_identifier_array'=>'array'],
'cubrid_lob_export' => ['bool', 'conn_identifier'=>'resource', 'lob_identifier'=>'resource', 'path_name'=>'string'],
'cubrid_lob_get' => ['array', 'conn_identifier'=>'resource', 'sql'=>'string'],
'cubrid_lob_send' => ['bool', 'conn_identifier'=>'resource', 'lob_identifier'=>'resource'],
'cubrid_lob_size' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lock_read' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_lock_write' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_move_cursor' => ['int', 'req_identifier'=>'resource', 'offset'=>'int', 'origin='=>'int'],
'cubrid_new_glo' => ['string', 'conn_identifier'=>'', 'class_name'=>'string', 'file_name'=>'string'],
'cubrid_next_result' => ['bool', 'result'=>'resource'],
'cubrid_num_cols' => ['int', 'req_identifier'=>'resource'],
'cubrid_num_fields' => ['int', 'result'=>'resource'],
'cubrid_num_rows' => ['int', 'req_identifier'=>'resource'],
'cubrid_pconnect' => ['resource', 'host'=>'string', 'port'=>'int', 'dbname'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_pconnect_with_url' => ['resource', 'conn_url'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_ping' => ['bool', 'conn_identifier='=>''],
'cubrid_prepare' => ['resource', 'conn_identifier'=>'resource', 'prepare_stmt'=>'string', 'option='=>'int'],
'cubrid_put' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr='=>'string', 'value='=>'mixed'],
'cubrid_query' => ['resource', 'query'=>'string', 'conn_identifier='=>''],
'cubrid_real_escape_string' => ['string', 'unescaped_string'=>'string', 'conn_identifier='=>''],
'cubrid_result' => ['string', 'result'=>'resource', 'row'=>'int', 'field='=>''],
'cubrid_rollback' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_save_to_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string', 'file_name'=>'string'],
'cubrid_schema' => ['array', 'conn_identifier'=>'resource', 'schema_type'=>'int', 'class_name='=>'string', 'attr_name='=>'string'],
'cubrid_send_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string'],
'cubrid_seq_add' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'seq_element'=>'string'],
'cubrid_seq_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int'],
'cubrid_seq_insert' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int', 'seq_element'=>'string'],
'cubrid_seq_put' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int', 'seq_element'=>'string'],
'cubrid_set_add' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'set_element'=>'string'],
'cubrid_set_autocommit' => ['bool', 'conn_identifier'=>'resource', 'mode'=>'bool'],
'cubrid_set_db_parameter' => ['bool', 'conn_identifier'=>'resource', 'param_type'=>'int', 'param_value'=>'int'],
'cubrid_set_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'set_element'=>'string'],
'cubrid_set_query_timeout' => ['bool', 'req_identifier'=>'resource', 'timeout'=>'int'],
'cubrid_unbuffered_query' => ['resource', 'query'=>'string', 'conn_identifier='=>''],
'cubrid_version' => ['string'],
'curl_close' => ['void', 'handle'=>'CurlHandle'],
'curl_copy_handle' => ['CurlHandle', 'handle'=>'CurlHandle'],
'curl_errno' => ['int', 'handle'=>'CurlHandle'],
'curl_error' => ['string', 'handle'=>'CurlHandle'],
'curl_escape' => ['string|false', 'handle'=>'CurlHandle', 'string'=>'string'],
'curl_exec' => ['bool|string', 'handle'=>'CurlHandle'],
'curl_file_create' => ['CURLFile', 'filename'=>'string', 'mime_type='=>'string', 'posted_filename='=>'string'],
'curl_getinfo' => ['mixed', 'handle'=>'CurlHandle', 'option='=>'int'],
'curl_init' => ['CurlHandle|false', 'url='=>'string'],
'curl_multi_add_handle' => ['int', 'multi_handle'=>'CurlMultiHandle', 'handle'=>'CurlHandle'],
'curl_multi_close' => ['void', 'multi_handle'=>'CurlMultiHandle'],
'curl_multi_errno' => ['int', 'multi_handle'=>'CurlMultiHandle'],
'curl_multi_exec' => ['int', 'multi_handle'=>'CurlMultiHandle', '&w_still_running'=>'int'],
'curl_multi_getcontent' => ['string', 'handle'=>'CurlHandle'],
'curl_multi_info_read' => ['array|false', 'multi_handle'=>'CurlMultiHandle', '&w_queued_messages='=>'int'],
'curl_multi_init' => ['CurlMultiHandle|false'],
'curl_multi_remove_handle' => ['int', 'multi_handle'=>'CurlMultiHandle', 'handle'=>'CurlHandle'],
'curl_multi_select' => ['int', 'multi_handle'=>'CurlMultiHandle', 'timeout='=>'float'],
'curl_multi_setopt' => ['bool', 'multi_handle'=>'CurlMultiHandle', 'option'=>'int', 'value'=>'mixed'],
'curl_multi_strerror' => ['?string', 'error_code'=>'int'],
'curl_pause' => ['int', 'handle'=>'CurlHandle', 'flags'=>'int'],
'curl_reset' => ['void', 'handle'=>'CurlHandle'],
'curl_setopt' => ['bool', 'handle'=>'CurlHandle', 'option'=>'int', 'value'=>'callable|mixed'],
'curl_setopt_array' => ['bool', 'handle'=>'CurlHandle', 'options'=>'array'],
'curl_share_close' => ['void', 'share_handle'=>'CurlShareHandle'],
'curl_share_errno' => ['int', 'share_handle'=>'CurlShareHandle'],
'curl_share_init' => ['CurlShareHandle'],
'curl_share_setopt' => ['bool', 'share_handle'=>'CurlShareHandle', 'option'=>'int', 'value'=>'mixed'],
'curl_share_strerror' => ['string', 'error_code'=>'int'],
'curl_strerror' => ['?string', 'error_code'=>'int'],
'curl_unescape' => ['string|false', 'handle'=>'CurlShareHandle', 'string'=>'string'],
'curl_version' => ['array', 'version='=>'int'],
'CURLFile::__construct' => ['void', 'filename'=>'string', 'mimetype='=>'string', 'postfilename='=>'string'],
'CURLFile::__wakeup' => ['void'],
'CURLFile::getFilename' => ['string'],
'CURLFile::getMimeType' => ['string'],
'CURLFile::getPostFilename' => ['string'],
'CURLFile::setMimeType' => ['void', 'mime'=>'string'],
'CURLFile::setPostFilename' => ['void', 'name'=>'string'],
'current' => ['mixed|false', 'array'=>'array|object'],
'cyrus_authenticate' => ['void', 'connection'=>'resource', 'mechlist='=>'string', 'service='=>'string', 'user='=>'string', 'minssf='=>'int', 'maxssf='=>'int', 'authname='=>'string', 'password='=>'string'],
'cyrus_bind' => ['bool', 'connection'=>'resource', 'callbacks'=>'array'],
'cyrus_close' => ['bool', 'connection'=>'resource'],
'cyrus_connect' => ['resource', 'host='=>'string', 'port='=>'string', 'flags='=>'int'],
'cyrus_query' => ['array', 'connection'=>'resource', 'query'=>'string'],
'cyrus_unbind' => ['bool', 'connection'=>'resource', 'trigger_name'=>'string'],
'date' => ['string|false', 'format'=>'string', 'timestamp='=>'int'],
'date_add' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_create' => ['DateTime|false', 'datetime='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_from_format' => ['DateTime|false', 'format'=>'string', 'datetime'=>'string', 'timezone='=>'?\DateTimeZone'],
'date_create_immutable' => ['DateTimeImmutable|false', 'datetime='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_immutable_from_format' => ['DateTimeImmutable|false', 'format'=>'string', 'datetime'=>'string', 'timezone='=>'?DateTimeZone'],
'date_date_set' => ['DateTime|false', 'object'=>'DateTime', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'date_default_timezone_get' => ['string'],
'date_default_timezone_set' => ['bool', 'timezoneId'=>'string'],
'date_diff' => ['DateInterval|false', 'baseObject'=>'DateTimeInterface', 'targetObject'=>'DateTimeInterface', 'absolute='=>'bool'],
'date_format' => ['string|false', 'object'=>'DateTimeInterface', 'format'=>'string'],
'date_get_last_errors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'date_interval_create_from_date_string' => ['DateInterval', 'datetime'=>'string'],
'date_interval_format' => ['string', 'object'=>'DateInterval', 'format'=>'string'],
'date_isodate_set' => ['DateTime|false', 'object'=>'DateTime', 'year'=>'int', 'week'=>'int', 'dayOfWeek='=>'int|mixed'],
'date_modify' => ['DateTime|false', 'object'=>'DateTime', 'modifier'=>'string'],
'date_offset_get' => ['int|false', 'object'=>'DateTimeInterface'],
'date_parse' => ['array|false', 'datetime'=>'string'],
'date_parse_from_format' => ['array', 'format'=>'string', 'datetime'=>'string'],
'date_sub' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_sun_info' => ['array|false', 'timestamp'=>'int', 'latitude'=>'float', 'longitude'=>'float'],
'date_sunrise' => ['mixed', 'timestamp'=>'int', 'returnFormat='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'utcOffset='=>'float'],
'date_sunset' => ['mixed', 'timestamp'=>'int', 'returnFormat='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'utcOffset='=>'float'],
'date_time_set' => ['DateTime|false', 'object'=>'', 'hour'=>'', 'minute'=>'', 'second='=>'', 'microsecond='=>''],
'date_timestamp_get' => ['int', 'object'=>'DateTimeInterface'],
'date_timestamp_set' => ['DateTime|false', 'object'=>'DateTime', 'timestamp'=>'int'],
'date_timezone_get' => ['DateTimeZone|false', 'object'=>'DateTimeInterface'],
'date_timezone_set' => ['DateTime|false', 'object'=>'DateTime', 'timezone'=>'DateTimeZone'],
'datefmt_create' => ['IntlDateFormatter|false', 'locale'=>'?string', 'dateType'=>'?int', 'timeType'=>'?int', 'timezone='=>'string|DateTimeZone|IntlTimeZone|null', 'calendar='=>'int|IntlCalendar|null', 'pattern='=>'string'],
'datefmt_format' => ['string|false', 'formatter'=>'IntlDateFormatter', 'datetime'=>'DateTime|IntlCalendar|array|int'],
'datefmt_format_object' => ['string|false', 'datetime'=>'object', 'format='=>'mixed', 'locale='=>'string'],
'datefmt_get_calendar' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_calendar_object' => ['IntlCalendar', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_datetype' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_error_code' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_error_message' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_locale' => ['string|false', 'formatter'=>'IntlDateFormatter', 'type='=>'int'],
'datefmt_get_pattern' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_timetype' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_timezone' => ['IntlTimeZone|false'],
'datefmt_get_timezone_id' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_is_lenient' => ['bool', 'formatter'=>'IntlDateFormatter'],
'datefmt_localtime' => ['array|false', 'formatter'=>'IntlDateFormatter', 'string='=>'string', '&rw_offset='=>'int'],
'datefmt_parse' => ['int|false', 'formatter'=>'IntlDateFormatter', 'string='=>'string', '&rw_offset='=>'int'],
'datefmt_set_calendar' => ['bool', 'formatter'=>'IntlDateFormatter', 'calendar'=>'int'],
'datefmt_set_lenient' => ['?bool', 'formatter'=>'IntlDateFormatter', 'lenient'=>'bool'],
'datefmt_set_pattern' => ['bool', 'formatter'=>'IntlDateFormatter', 'pattern'=>'string'],
'datefmt_set_timezone' => ['bool', 'formatter'=>'mixed'],
'datefmt_set_timezone_id' => ['bool', 'fmt'=>'IntlDateFormatter', 'zone'=>'string'],
'DateInterval::__construct' => ['void', 'spec'=>'string'],
'DateInterval::__set_state' => ['DateInterval', 'array'=>'array'],
'DateInterval::__wakeup' => ['void'],
'DateInterval::createFromDateString' => ['DateInterval', 'time'=>'string'],
'DateInterval::format' => ['string', 'format'=>'string'],
'DatePeriod::__construct' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'recur'=>'int', 'options='=>'int'],
'DatePeriod::__construct\'1' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'end'=>'DateTimeInterface', 'options='=>'int'],
'DatePeriod::__construct\'2' => ['void', 'iso'=>'string', 'options='=>'int'],
'DatePeriod::__wakeup' => ['void'],
'DatePeriod::getDateInterval' => ['DateInterval'],
'DatePeriod::getEndDate' => ['?DateTimeInterface'],
'DatePeriod::getStartDate' => ['DateTimeInterface'],
'DateTime::__construct' => ['void', 'time='=>'string'],
'DateTime::__construct\'1' => ['void', 'time'=>'?string', 'timezone'=>'?DateTimeZone'],
'DateTime::__set_state' => ['static', 'array'=>'array'],
'DateTime::__wakeup' => ['void'],
'DateTime::add' => ['static', 'interval'=>'DateInterval'],
'DateTime::createFromFormat' => ['static|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'DateTime::createFromImmutable' => ['static', 'datetTimeImmutable'=>'DateTimeImmutable'],
'DateTime::diff' => ['DateInterval|false', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTime::format' => ['string|false', 'format'=>'string'],
'DateTime::getLastErrors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'DateTime::getOffset' => ['int'],
'DateTime::getTimestamp' => ['int|false'],
'DateTime::getTimezone' => ['DateTimeZone|false'],
'DateTime::modify' => ['static|false', 'modify'=>'string'],
'DateTime::setDate' => ['static', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'DateTime::setISODate' => ['static', 'year'=>'int', 'week'=>'int', 'day='=>'int'],
'DateTime::setTime' => ['static|false', 'hour'=>'int', 'minute'=>'int', 'second='=>'int', 'microseconds='=>'int'],
'DateTime::setTimestamp' => ['static', 'unixtimestamp'=>'int'],
'DateTime::setTimezone' => ['static', 'timezone'=>'DateTimeZone'],
'DateTime::sub' => ['static', 'interval'=>'DateInterval'],
'DateTimeImmutable::__construct' => ['void', 'time='=>'string'],
'DateTimeImmutable::__construct\'1' => ['void', 'time'=>'?string', 'timezone'=>'?DateTimeZone'],
'DateTimeImmutable::__set_state' => ['static', 'array'=>'array'],
'DateTimeImmutable::__wakeup' => ['void'],
'DateTimeImmutable::add' => ['static', 'interval'=>'DateInterval'],
'DateTimeImmutable::createFromFormat' => ['static|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'DateTimeImmutable::createFromMutable' => ['static', 'datetime'=>'DateTime'],
'DateTimeImmutable::diff' => ['DateInterval', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTimeImmutable::format' => ['string|false', 'format'=>'string'],
'DateTimeImmutable::getLastErrors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'DateTimeImmutable::getOffset' => ['int'],
'DateTimeImmutable::getTimestamp' => ['int|false'],
'DateTimeImmutable::getTimezone' => ['DateTimeZone|false'],
'DateTimeImmutable::modify' => ['static', 'modify'=>'string'],
'DateTimeImmutable::setDate' => ['static|false', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'DateTimeImmutable::setISODate' => ['static|false', 'year'=>'int', 'week'=>'int', 'day='=>'int'],
'DateTimeImmutable::setTime' => ['static|false', 'hour'=>'int', 'minute'=>'int', 'second='=>'int', 'microseconds='=>'int'],
'DateTimeImmutable::setTimestamp' => ['static|false', 'unixtimestamp'=>'int'],
'DateTimeImmutable::setTimezone' => ['static|false', 'timezone'=>'DateTimeZone'],
'DateTimeImmutable::sub' => ['static|false', 'interval'=>'DateInterval'],
'DateTimeInterface::diff' => ['DateInterval', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTimeInterface::format' => ['string', 'format'=>'string'],
'DateTimeInterface::getOffset' => ['int'],
'DateTimeInterface::getTimestamp' => ['int|false'],
'DateTimeInterface::getTimezone' => ['DateTimeZone|false'],
'DateTimeZone::__construct' => ['void', 'timezone'=>'string'],
'DateTimeZone::__set_state' => ['DateTimeZone', 'array'=>'array'],
'DateTimeZone::__wakeup' => ['void'],
'DateTimeZone::getLocation' => ['array|false'],
'DateTimeZone::getName' => ['string'],
'DateTimeZone::getOffset' => ['int|false', 'datetime'=>'DateTimeInterface'],
'DateTimeZone::getTransitions' => ['list<array{ts: int, time: string, offset: int, isdst: bool, abbr: string}>|false', 'timestamp_begin='=>'int', 'timestamp_end='=>'int'],
'DateTimeZone::listAbbreviations' => ['array<string, list<array{dst: bool, offset: int, timezone_id: string|null}>>|false'],
'DateTimeZone::listIdentifiers' => ['list<string>|false', 'what='=>'int', 'country='=>'string'],
'db2_autocommit' => ['mixed', 'connection'=>'resource', 'value='=>'int'],
'db2_bind_param' => ['bool', 'stmt'=>'resource', 'parameter_number'=>'int', 'variable_name'=>'string', 'parameter_type='=>'int', 'data_type='=>'int', 'precision='=>'int', 'scale='=>'int'],
'db2_client_info' => ['object|false', 'connection'=>'resource'],
'db2_close' => ['bool', 'connection'=>'resource'],
'db2_column_privileges' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'column_name='=>'string'],
'db2_columns' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'column_name='=>'string'],
'db2_commit' => ['bool', 'connection'=>'resource'],
'db2_conn_error' => ['string', 'connection='=>'resource'],
'db2_conn_errormsg' => ['string', 'connection='=>'resource'],
'db2_connect' => ['resource|false', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'options='=>'array'],
'db2_cursor_type' => ['int', 'stmt'=>'resource'],
'db2_escape_string' => ['string', 'string_literal'=>'string'],
'db2_exec' => ['resource|false', 'connection'=>'resource', 'statement'=>'string', 'options='=>'array'],
'db2_execute' => ['bool', 'stmt'=>'resource', 'parameters='=>'array'],
'db2_fetch_array' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_assoc' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_both' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_object' => ['object|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_row' => ['bool', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_field_display_size' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_name' => ['string|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_num' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_precision' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_scale' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_type' => ['string|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_width' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_foreign_keys' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string'],
'db2_free_result' => ['bool', 'stmt'=>'resource'],
'db2_free_stmt' => ['bool', 'stmt'=>'resource'],
'db2_get_option' => ['string|false', 'resource'=>'resource', 'option'=>'string'],
'db2_last_insert_id' => ['string', 'resource'=>'resource'],
'db2_lob_read' => ['string|false', 'stmt'=>'resource', 'colnum'=>'int', 'length'=>'int'],
'db2_next_result' => ['resource|false', 'stmt'=>'resource'],
'db2_num_fields' => ['int|false', 'stmt'=>'resource'],
'db2_num_rows' => ['int', 'stmt'=>'resource'],
'db2_pclose' => ['bool', 'resource'=>'resource'],
'db2_pconnect' => ['resource|false', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'options='=>'array'],
'db2_prepare' => ['resource|false', 'connection'=>'resource', 'statement'=>'string', 'options='=>'array'],
'db2_primary_keys' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string'],
'db2_primarykeys' => [''],
'db2_procedure_columns' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'procedure'=>'string', 'parameter'=>'string'],
'db2_procedurecolumns' => [''],
'db2_procedures' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'procedure'=>'string'],
'db2_result' => ['mixed', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_rollback' => ['bool', 'connection'=>'resource'],
'db2_server_info' => ['object|false', 'connection'=>'resource'],
'db2_set_option' => ['bool', 'resource'=>'resource', 'options'=>'array', 'type'=>'int'],
'db2_setoption' => [''],
'db2_special_columns' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string', 'scope'=>'int'],
'db2_specialcolumns' => [''],
'db2_statistics' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string', 'unique'=>'bool'],
'db2_stmt_error' => ['string', 'stmt='=>'resource'],
'db2_stmt_errormsg' => ['string', 'stmt='=>'resource'],
'db2_table_privileges' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string'],
'db2_tableprivileges' => [''],
'db2_tables' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'table_type='=>'string'],
'dba_close' => ['void', 'dba'=>'resource'],
'dba_delete' => ['bool', 'key'=>'string', 'dba'=>'resource'],
'dba_exists' => ['bool', 'key'=>'string', 'dba'=>'resource'],
'dba_fetch' => ['string|false', 'key'=>'string', 'skip'=>'int', 'dba'=>'resource'],
'dba_fetch\'1' => ['string|false', 'key'=>'string', 'skip'=>'resource'],
'dba_firstkey' => ['string', 'dba'=>'resource'],
'dba_handlers' => ['array', 'full_info='=>'bool'],
'dba_insert' => ['bool', 'key'=>'string', 'value'=>'string', 'dba'=>'resource'],
'dba_key_split' => ['array|false', 'key'=>'string'],
'dba_list' => ['array'],
'dba_nextkey' => ['string', 'dba'=>'resource'],
'dba_open' => ['resource', 'path'=>'string', 'mode'=>'string', 'handler='=>'string', '...handler_params='=>'string'],
'dba_optimize' => ['bool', 'dba'=>'resource'],
'dba_popen' => ['resource', 'path'=>'string', 'mode'=>'string', 'handler='=>'string', '...handler_params='=>'string'],
'dba_replace' => ['bool', 'key'=>'string', 'value'=>'string', 'dba'=>'resource'],
'dba_sync' => ['bool', 'dba'=>'resource'],
'dbase_add_record' => ['bool', 'dbase_identifier'=>'resource', 'record'=>'array'],
'dbase_close' => ['bool', 'dbase_identifier'=>'resource'],
'dbase_create' => ['resource|false', 'filename'=>'string', 'fields'=>'array'],
'dbase_delete_record' => ['bool', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_get_header_info' => ['array', 'dbase_identifier'=>'resource'],
'dbase_get_record' => ['array', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_get_record_with_names' => ['array', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_numfields' => ['int', 'dbase_identifier'=>'resource'],
'dbase_numrecords' => ['int', 'dbase_identifier'=>'resource'],
'dbase_open' => ['resource|false', 'filename'=>'string', 'mode'=>'int'],
'dbase_pack' => ['bool', 'dbase_identifier'=>'resource'],
'dbase_replace_record' => ['bool', 'dbase_identifier'=>'resource', 'record'=>'array', 'record_number'=>'int'],
'dbplus_add' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_aql' => ['resource', 'query'=>'string', 'server='=>'string', 'dbpath='=>'string'],
'dbplus_chdir' => ['string', 'newdir='=>'string'],
'dbplus_close' => ['mixed', 'relation'=>'resource'],
'dbplus_curr' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_errcode' => ['string', 'errno='=>'int'],
'dbplus_errno' => ['int'],
'dbplus_find' => ['int', 'relation'=>'resource', 'constraints'=>'array', 'tuple'=>'mixed'],
'dbplus_first' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_flush' => ['int', 'relation'=>'resource'],
'dbplus_freealllocks' => ['int'],
'dbplus_freelock' => ['int', 'relation'=>'resource', 'tuple'=>'string'],
'dbplus_freerlocks' => ['int', 'relation'=>'resource'],
'dbplus_getlock' => ['int', 'relation'=>'resource', 'tuple'=>'string'],
'dbplus_getunique' => ['int', 'relation'=>'resource', 'uniqueid'=>'int'],
'dbplus_info' => ['int', 'relation'=>'resource', 'key'=>'string', 'result'=>'array'],
'dbplus_last' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_lockrel' => ['int', 'relation'=>'resource'],
'dbplus_next' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_open' => ['resource', 'name'=>'string'],
'dbplus_prev' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_rchperm' => ['int', 'relation'=>'resource', 'mask'=>'int', 'user'=>'string', 'group'=>'string'],
'dbplus_rcreate' => ['resource', 'name'=>'string', 'domlist'=>'mixed', 'overwrite='=>'bool'],
'dbplus_rcrtexact' => ['mixed', 'name'=>'string', 'relation'=>'resource', 'overwrite='=>'bool'],
'dbplus_rcrtlike' => ['mixed', 'name'=>'string', 'relation'=>'resource', 'overwrite='=>'int'],
'dbplus_resolve' => ['array', 'relation_name'=>'string'],
'dbplus_restorepos' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_rkeys' => ['mixed', 'relation'=>'resource', 'domlist'=>'mixed'],
'dbplus_ropen' => ['resource', 'name'=>'string'],
'dbplus_rquery' => ['resource', 'query'=>'string', 'dbpath='=>'string'],
'dbplus_rrename' => ['int', 'relation'=>'resource', 'name'=>'string'],
'dbplus_rsecindex' => ['mixed', 'relation'=>'resource', 'domlist'=>'mixed', 'type'=>'int'],
'dbplus_runlink' => ['int', 'relation'=>'resource'],
'dbplus_rzap' => ['int', 'relation'=>'resource'],
'dbplus_savepos' => ['int', 'relation'=>'resource'],
'dbplus_setindex' => ['int', 'relation'=>'resource', 'idx_name'=>'string'],
'dbplus_setindexbynumber' => ['int', 'relation'=>'resource', 'idx_number'=>'int'],
'dbplus_sql' => ['resource', 'query'=>'string', 'server='=>'string', 'dbpath='=>'string'],
'dbplus_tcl' => ['string', 'sid'=>'int', 'script'=>'string'],
'dbplus_tremove' => ['int', 'relation'=>'resource', 'tuple'=>'array', 'current='=>'array'],
'dbplus_undo' => ['int', 'relation'=>'resource'],
'dbplus_undoprepare' => ['int', 'relation'=>'resource'],
'dbplus_unlockrel' => ['int', 'relation'=>'resource'],
'dbplus_unselect' => ['int', 'relation'=>'resource'],
'dbplus_update' => ['int', 'relation'=>'resource', 'old'=>'array', 'new'=>'array'],
'dbplus_xlockrel' => ['int', 'relation'=>'resource'],
'dbplus_xunlockrel' => ['int', 'relation'=>'resource'],
'dbx_close' => ['int', 'link_identifier'=>'object'],
'dbx_compare' => ['int', 'row_a'=>'array', 'row_b'=>'array', 'column_key'=>'string', 'flags='=>'int'],
'dbx_connect' => ['object', 'module'=>'mixed', 'host'=>'string', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'persistent='=>'int'],
'dbx_error' => ['string', 'link_identifier'=>'object'],
'dbx_escape_string' => ['string', 'link_identifier'=>'object', 'text'=>'string'],
'dbx_fetch_row' => ['mixed', 'result_identifier'=>'object'],
'dbx_query' => ['mixed', 'link_identifier'=>'object', 'sql_statement'=>'string', 'flags='=>'int'],
'dbx_sort' => ['bool', 'result'=>'object', 'user_compare_function'=>'string'],
'dcgettext' => ['string', 'domain'=>'string', 'message'=>'string', 'category'=>'int'],
'dcngettext' => ['string', 'domain'=>'string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int', 'category'=>'int'],
'deaggregate' => ['', 'object'=>'object', 'class_name='=>'string'],
'debug_backtrace' => ['list<array>', 'options='=>'int|bool', 'limit='=>'int'],
'debug_print_backtrace' => ['void', 'options='=>'int|bool', 'limit='=>'int'],
'debug_zval_dump' => ['void', '...value'=>'mixed'],
'debugger_connect' => [''],
'debugger_connector_pid' => [''],
'debugger_get_server_start_time' => [''],
'debugger_print' => [''],
'debugger_start_debug' => [''],
'decbin' => ['string', 'num'=>'int'],
'dechex' => ['string', 'num'=>'int'],
'decoct' => ['string', 'num'=>'int'],
'define' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'case_insensitive='=>'bool'],
'define_syslog_variables' => ['void'],
'defined' => ['bool', 'constant_name'=>'string'],
'deflate_add' => ['string|false', 'context'=>'resource', 'data'=>'string', 'flush_mode='=>'int'],
'deflate_init' => ['resource|false', 'encoding'=>'int', 'options='=>'array'],
'deg2rad' => ['float', 'num'=>'float'],
'dgettext' => ['string', 'domain'=>'string', 'message'=>'string'],
'dio_close' => ['void', 'fd'=>'resource'],
'dio_fcntl' => ['mixed', 'fd'=>'resource', 'cmd'=>'int', 'args='=>'mixed'],
'dio_open' => ['resource|false', 'filename'=>'string', 'flags'=>'int', 'mode='=>'int'],
'dio_read' => ['string', 'fd'=>'resource', 'length='=>'int'],
'dio_seek' => ['int', 'fd'=>'resource', 'pos'=>'int', 'whence='=>'int'],
'dio_stat' => ['?array', 'fd'=>'resource'],
'dio_tcsetattr' => ['bool', 'fd'=>'resource', 'options'=>'array'],
'dio_truncate' => ['bool', 'fd'=>'resource', 'offset'=>'int'],
'dio_write' => ['int', 'fd'=>'resource', 'data'=>'string', 'length='=>'int'],
'dir' => ['Directory|false|null', 'directory'=>'string', 'context='=>'resource'],
'Directory::close' => ['void', 'dir_handle='=>'resource'],
'Directory::read' => ['string|false', 'dir_handle='=>'resource'],
'Directory::rewind' => ['void', 'dir_handle='=>'resource'],
'DirectoryIterator::__construct' => ['void', 'path'=>'string'],
'DirectoryIterator::__toString' => ['string'],
'DirectoryIterator::current' => ['DirectoryIterator'],
'DirectoryIterator::getATime' => ['int'],
'DirectoryIterator::getBasename' => ['string', 'suffix='=>'string'],
'DirectoryIterator::getCTime' => ['int'],
'DirectoryIterator::getExtension' => ['string'],
'DirectoryIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'DirectoryIterator::getFilename' => ['string'],
'DirectoryIterator::getGroup' => ['int'],
'DirectoryIterator::getInode' => ['int'],
'DirectoryIterator::getLinkTarget' => ['string'],
'DirectoryIterator::getMTime' => ['int'],
'DirectoryIterator::getOwner' => ['int'],
'DirectoryIterator::getPath' => ['string'],
'DirectoryIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'DirectoryIterator::getPathname' => ['string'],
'DirectoryIterator::getPerms' => ['int'],
'DirectoryIterator::getRealPath' => ['string'],
'DirectoryIterator::getSize' => ['int'],
'DirectoryIterator::getType' => ['string'],
'DirectoryIterator::isDir' => ['bool'],
'DirectoryIterator::isDot' => ['bool'],
'DirectoryIterator::isExecutable' => ['bool'],
'DirectoryIterator::isFile' => ['bool'],
'DirectoryIterator::isLink' => ['bool'],
'DirectoryIterator::isReadable' => ['bool'],
'DirectoryIterator::isWritable' => ['bool'],
'DirectoryIterator::key' => ['string'],
'DirectoryIterator::next' => ['void'],
'DirectoryIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'DirectoryIterator::rewind' => ['void'],
'DirectoryIterator::seek' => ['void', 'position'=>'int'],
'DirectoryIterator::setFileClass' => ['void', 'class_name='=>'string'],
'DirectoryIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'DirectoryIterator::valid' => ['bool'],
'dirname' => ['string', 'path'=>'string', 'levels='=>'int'],
'disk_free_space' => ['float|false', 'directory'=>'string'],
'disk_total_space' => ['float|false', 'directory'=>'string'],
'diskfreespace' => ['float|false', 'directory'=>'string'],
'display_disabled_function' => [''],
'dl' => ['bool', 'extension_filename'=>'string'],
'dngettext' => ['string', 'domain'=>'string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int'],
'dns_check_record' => ['bool', 'hostname'=>'string', 'type='=>'string'],
'dns_get_mx' => ['bool', 'hostname'=>'string', '&w_hosts'=>'array', '&w_weights'=>'array'],
'dns_get_record' => ['list<array>|false', 'hostname'=>'string', 'type='=>'int', '&w_authoritative_name_servers='=>'array', '&w_additional_records='=>'array', 'raw='=>'bool'],
'dom_document_relaxNG_validate_file' => ['bool', 'filename'=>'string'],
'dom_document_relaxNG_validate_xml' => ['bool', 'source'=>'string'],
'dom_document_schema_validate' => ['bool', 'source'=>'string', 'flags'=>'int'],
'dom_document_schema_validate_file' => ['bool', 'filename'=>'string', 'flags'=>'int'],
'dom_document_xinclude' => ['int', 'options'=>'int'],
'dom_import_simplexml' => ['DOMElement|false', 'node'=>'SimpleXMLElement'],
'dom_xpath_evaluate' => ['', 'expr'=>'string', 'context'=>'DOMNode', 'registernodens'=>'bool'],
'dom_xpath_query' => ['DOMNodeList', 'expr'=>'string', 'context'=>'DOMNode', 'registernodens'=>'bool'],
'dom_xpath_register_ns' => ['bool', 'prefix'=>'string', 'uri'=>'string'],
'dom_xpath_register_php_functions' => [''],
'DomainException::__clone' => ['void'],
'DomainException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?DomainException'],
'DomainException::__toString' => ['string'],
'DomainException::__wakeup' => ['void'],
'DomainException::getCode' => ['int'],
'DomainException::getFile' => ['string'],
'DomainException::getLine' => ['int'],
'DomainException::getMessage' => ['string'],
'DomainException::getPrevious' => ['Throwable|DomainException|null'],
'DomainException::getTrace' => ['list<array<string,mixed>>'],
'DomainException::getTraceAsString' => ['string'],
'DOMAttr::__construct' => ['void', 'name'=>'string', 'value='=>'string'],
'DOMAttr::getLineNo' => ['int'],
'DOMAttr::getNodePath' => ['?string'],
'DOMAttr::hasAttributes' => ['bool'],
'DOMAttr::hasChildNodes' => ['bool'],
'DOMAttr::insertBefore' => ['DOMNode', 'newnode'=>'DOMNode', 'refnode='=>'DOMNode'],
'DOMAttr::isDefaultNamespace' => ['bool', 'namespaceuri'=>'string'],
'DOMAttr::isId' => ['bool'],
'DOMAttr::isSameNode' => ['bool', 'node'=>'DOMNode'],
'DOMAttr::isSupported' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMAttr::lookupNamespaceUri' => ['string', 'prefix'=>'string'],
'DOMAttr::lookupPrefix' => ['string', 'namespaceuri'=>'string'],
'DOMAttr::normalize' => ['void'],
'DOMAttr::removeChild' => ['DOMNode', 'oldnode'=>'DOMNode'],
'DOMAttr::replaceChild' => ['DOMNode', 'newnode'=>'DOMNode', 'oldnode'=>'DOMNode'],
'DomAttribute::name' => ['string'],
'DomAttribute::set_value' => ['bool', 'content'=>'string'],
'DomAttribute::specified' => ['bool'],
'DomAttribute::value' => ['string'],
'DOMCdataSection::__construct' => ['void', 'value'=>'string'],
'DOMCharacterData::appendData' => ['void', 'data'=>'string'],
'DOMCharacterData::deleteData' => ['void', 'offset'=>'int', 'count'=>'int'],
'DOMCharacterData::insertData' => ['void', 'offset'=>'int', 'data'=>'string'],
'DOMCharacterData::replaceData' => ['void', 'offset'=>'int', 'count'=>'int', 'data'=>'string'],
'DOMCharacterData::substringData' => ['string', 'offset'=>'int', 'count'=>'int'],
'DOMComment::__construct' => ['void', 'value='=>'string'],
'DOMDocument::__construct' => ['void', 'version='=>'string', 'encoding='=>'string'],
'DOMDocument::createAttribute' => ['DOMAttr|false', 'name'=>'string'],
'DOMDocument::createAttributeNS' => ['DOMAttr|false', 'namespaceuri'=>'string', 'qualifiedname'=>'string'],
'DOMDocument::createCDATASection' => ['DOMCDATASection|false', 'data'=>'string'],
'DOMDocument::createComment' => ['DOMComment|false', 'data'=>'string'],
'DOMDocument::createDocumentFragment' => ['DOMDocumentFragment|false'],
'DOMDocument::createElement' => ['DOMElement|false', 'name'=>'string', 'value='=>'string'],
'DOMDocument::createElementNS' => ['DOMElement|false', 'namespaceuri'=>'string', 'qualifiedname'=>'string', 'value='=>'string'],
'DOMDocument::createEntityReference' => ['DOMEntityReference|false', 'name'=>'string'],
'DOMDocument::createProcessingInstruction' => ['DOMProcessingInstruction|false', 'target'=>'string', 'data='=>'string'],
'DOMDocument::createTextNode' => ['DOMText|false', 'content'=>'string'],
'DOMDocument::getElementById' => ['?DOMElement', 'elementid'=>'string'],
'DOMDocument::getElementsByTagName' => ['DOMNodeList', 'name'=>'string'],
'DOMDocument::getElementsByTagNameNS' => ['DOMNodeList', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMDocument::importNode' => ['DOMNode|false', 'importednode'=>'DOMNode', 'deep='=>'bool'],
'DOMDocument::load' => ['DOMDocument|bool', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::loadHTML' => ['bool', 'source'=>'string', 'options='=>'int'],
'DOMDocument::loadHTMLFile' => ['bool', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::loadXML' => ['DOMDocument|bool', 'source'=>'string', 'options='=>'int'],
'DOMDocument::normalizeDocument' => ['void'],
'DOMDocument::registerNodeClass' => ['bool', 'baseclass'=>'string', 'extendedclass'=>'string'],
'DOMDocument::relaxNGValidate' => ['bool', 'filename'=>'string'],
'DOMDocument::relaxNGValidateSource' => ['bool', 'source'=>'string'],
'DOMDocument::save' => ['int|false', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::saveHTML' => ['string|false', 'node='=>'?DOMNode'],
'DOMDocument::saveHTMLFile' => ['int|false', 'filename'=>'string'],
'DOMDocument::saveXML' => ['string|false', 'node='=>'?DOMNode', 'options='=>'int'],
'DOMDocument::schemaValidate' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'DOMDocument::schemaValidateSource' => ['bool', 'source'=>'string', 'flags='=>'int'],
'DOMDocument::validate' => ['bool'],
'DOMDocument::xinclude' => ['int', 'options='=>'int'],
'DOMDocumentFragment::__construct' => ['void'],
'DOMDocumentFragment::appendXML' => ['bool', 'data'=>'string'],
'DomDocumentType::entities' => ['array'],
'DomDocumentType::internal_subset' => ['bool'],
'DomDocumentType::name' => ['string'],
'DomDocumentType::notations' => ['array'],
'DomDocumentType::public_id' => ['string'],
'DomDocumentType::system_id' => ['string'],
'DOMElement::__construct' => ['void', 'name'=>'string', 'value='=>'string', 'uri='=>'string'],
'DOMElement::get_attribute' => ['string', 'name'=>'string'],
'DOMElement::get_attribute_node' => ['DomAttribute', 'name'=>'string'],
'DOMElement::get_elements_by_tagname' => ['array', 'name'=>'string'],
'DOMElement::getAttribute' => ['string', 'name'=>'string'],
'DOMElement::getAttributeNode' => ['DOMAttr', 'name'=>'string'],
'DOMElement::getAttributeNodeNS' => ['DOMAttr', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::getAttributeNS' => ['string', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::getElementsByTagName' => ['DOMNodeList', 'name'=>'string'],
'DOMElement::getElementsByTagNameNS' => ['DOMNodeList', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::has_attribute' => ['bool', 'name'=>'string'],
'DOMElement::hasAttribute' => ['bool', 'name'=>'string'],
'DOMElement::hasAttributeNS' => ['bool', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::remove_attribute' => ['bool', 'name'=>'string'],
'DOMElement::removeAttribute' => ['bool', 'name'=>'string'],
'DOMElement::removeAttributeNode' => ['bool', 'oldnode'=>'DOMAttr'],
'DOMElement::removeAttributeNS' => ['bool', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::set_attribute' => ['DomAttribute', 'name'=>'string', 'value'=>'string'],
'DOMElement::set_attribute_node' => ['DomNode', 'attr'=>'DOMNode'],
'DOMElement::setAttribute' => ['DOMAttr|false', 'name'=>'string', 'value'=>'string'],
'DOMElement::setAttributeNode' => ['?DOMAttr', 'attr'=>'DOMAttr'],
'DOMElement::setAttributeNodeNS' => ['DOMAttr', 'attr'=>'DOMAttr'],
'DOMElement::setAttributeNS' => ['void', 'namespaceuri'=>'string', 'qualifiedname'=>'string', 'value'=>'string'],
'DOMElement::setIdAttribute' => ['void', 'name'=>'string', 'isid'=>'bool'],
'DOMElement::setIdAttributeNode' => ['void', 'attr'=>'DOMAttr', 'isid'=>'bool'],
'DOMElement::setIdAttributeNS' => ['void', 'namespaceuri'=>'string', 'localname'=>'string', 'isid'=>'bool'],
'DOMElement::tagname' => ['string'],
'DOMEntityReference::__construct' => ['void', 'name'=>'string'],
'DOMImplementation::__construct' => ['void'],
'DOMImplementation::createDocument' => ['DOMDocument', 'namespaceuri='=>'string', 'qualifiedname='=>'string', 'doctype='=>'DOMDocumentType'],
'DOMImplementation::createDocumentType' => ['DOMDocumentType', 'qualifiedname='=>'string', 'publicid='=>'string', 'systemid='=>'string'],
'DOMImplementation::hasFeature' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMNamedNodeMap::count' => ['int'],
'DOMNamedNodeMap::getNamedItem' => ['?DOMNode', 'name'=>'string'],
'DOMNamedNodeMap::getNamedItemNS' => ['?DOMNode', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMNamedNodeMap::item' => ['?DOMNode', 'index'=>'int'],
'DomNode::add_namespace' => ['bool', 'uri'=>'string', 'prefix'=>'string'],
'DomNode::append_child' => ['DOMNode', 'newnode'=>'DOMNode'],
'DOMNode::appendChild' => ['DOMNode', 'newnode'=>'DOMNode'],
'DOMNode::C14N' => ['string', 'exclusive='=>'bool', 'with_comments='=>'bool', 'xpath='=>'array', 'ns_prefixes='=>'array'],
'DOMNode::C14NFile' => ['int|false', 'uri='=>'string', 'exclusive='=>'bool', 'with_comments='=>'bool', 'xpath='=>'array', 'ns_prefixes='=>'array'],
'DOMNode::cloneNode' => ['DOMNode', 'deep='=>'bool'],
'DOMNode::getLineNo' => ['int'],
'DOMNode::getNodePath' => ['?string'],
'DOMNode::hasAttributes' => ['bool'],
'DOMNode::hasChildNodes' => ['bool'],
'DOMNode::insertBefore' => ['DOMNode', 'newnode'=>'DOMNode', 'refnode='=>'DOMNode|null'],
'DOMNode::isDefaultNamespace' => ['bool', 'namespaceuri'=>'string'],
'DOMNode::isSameNode' => ['bool', 'node'=>'DOMNode'],
'DOMNode::isSupported' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMNode::lookupNamespaceURI' => ['string', 'prefix'=>'string'],
'DOMNode::lookupPrefix' => ['string', 'namespaceuri'=>'string'],
'DOMNode::normalize' => ['void'],
'DOMNode::removeChild' => ['DOMNode', 'oldnode'=>'DOMNode'],
'DOMNode::replaceChild' => ['DOMNode|false', 'newnode'=>'DOMNode', 'oldnode'=>'DOMNode'],
'DOMNodeList::count' => ['int'],
'DOMNodeList::item' => ['?DOMNode', 'index'=>'int'],
'DOMProcessingInstruction::__construct' => ['void', 'name'=>'string', 'value'=>'string'],
'DomProcessingInstruction::data' => ['string'],
'DomProcessingInstruction::target' => ['string'],
'DOMText::__construct' => ['void', 'value='=>'string'],
'DOMText::isElementContentWhitespace' => ['bool'],
'DOMText::isWhitespaceInElementContent' => ['bool'],
'DOMText::splitText' => ['DOMText', 'offset'=>'int'],
'domxml_new_doc' => ['DomDocument', 'version'=>'string'],
'domxml_open_file' => ['DomDocument', 'filename'=>'string', 'mode='=>'int', 'error='=>'array'],
'domxml_open_mem' => ['DomDocument', 'string'=>'string', 'mode='=>'int', 'error='=>'array'],
'domxml_version' => ['string'],
'domxml_xmltree' => ['DomDocument', 'string'=>'string'],
'domxml_xslt_stylesheet' => ['DomXsltStylesheet', 'xsl_buf'=>'string'],
'domxml_xslt_stylesheet_doc' => ['DomXsltStylesheet', 'xsl_doc'=>'DOMDocument'],
'domxml_xslt_stylesheet_file' => ['DomXsltStylesheet', 'xsl_file'=>'string'],
'domxml_xslt_version' => ['int'],
'DOMXPath::__construct' => ['void', 'doc'=>'DOMDocument'],
'DOMXPath::evaluate' => ['mixed', 'expression'=>'string', 'contextnode='=>'?DOMNode', 'registernodens='=>'bool'],
'DOMXPath::query' => ['DOMNodeList|false', 'expression'=>'string', 'contextnode='=>'DOMNode|null', 'registernodens='=>'bool'],
'DOMXPath::registerNamespace' => ['bool', 'prefix'=>'string', 'namespaceuri'=>'string'],
'DOMXPath::registerPhpFunctions' => ['void', 'restrict='=>'mixed'],
'DomXsltStylesheet::process' => ['DomDocument', 'xml_doc'=>'DOMDocument', 'xslt_params='=>'array', 'is_xpath_param='=>'bool', 'profile_filename='=>'string'],
'DomXsltStylesheet::result_dump_file' => ['string', 'xmldoc'=>'DOMDocument', 'filename'=>'string'],
'DomXsltStylesheet::result_dump_mem' => ['string', 'xmldoc'=>'DOMDocument'],
'DOTNET::__call' => ['mixed', 'name'=>'string', 'args'=>''],
'DOTNET::__construct' => ['void', 'assembly_name'=>'string', 'datatype_name'=>'string', 'codepage='=>'int'],
'DOTNET::__get' => ['mixed', 'name'=>'string'],
'DOTNET::__set' => ['void', 'name'=>'string', 'value'=>''],
'dotnet_load' => ['int', 'assembly_name'=>'string', 'datatype_name='=>'string', 'codepage='=>'int'],
'doubleval' => ['float', 'value'=>'mixed'],
'Ds\Collection::clear' => ['void'],
'Ds\Collection::copy' => ['Ds\Collection'],
'Ds\Collection::isEmpty' => ['bool'],
'Ds\Collection::toArray' => ['array'],
'Ds\Deque::__construct' => ['void', 'values='=>'mixed'],
'Ds\Deque::allocate' => ['void', 'capacity'=>'int'],
'Ds\Deque::apply' => ['void', 'callback'=>'callable'],
'Ds\Deque::capacity' => ['int'],
'Ds\Deque::clear' => ['void'],
'Ds\Deque::contains' => ['bool', '...values='=>'mixed'],
'Ds\Deque::copy' => ['Ds\Deque'],
'Ds\Deque::count' => ['int'],
'Ds\Deque::filter' => ['Ds\Deque', 'callback='=>'callable'],
'Ds\Deque::find' => ['mixed', 'value'=>'mixed'],
'Ds\Deque::first' => ['mixed'],
'Ds\Deque::get' => ['void', 'index'=>'int'],
'Ds\Deque::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Deque::isEmpty' => ['bool'],
'Ds\Deque::join' => ['string', 'glue='=>'string'],
'Ds\Deque::jsonSerialize' => ['array'],
'Ds\Deque::last' => ['mixed'],
'Ds\Deque::map' => ['Ds\Deque', 'callback'=>'callable'],
'Ds\Deque::merge' => ['Ds\Deque', 'values'=>'mixed'],
'Ds\Deque::pop' => ['mixed'],
'Ds\Deque::push' => ['void', '...values='=>'mixed'],
'Ds\Deque::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Deque::remove' => ['mixed', 'index'=>'int'],
'Ds\Deque::reverse' => ['void'],
'Ds\Deque::reversed' => ['Ds\Deque'],
'Ds\Deque::rotate' => ['void', 'rotations'=>'int'],
'Ds\Deque::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Deque::shift' => ['mixed'],
'Ds\Deque::slice' => ['Ds\Deque', 'index'=>'int', 'length='=>'?int'],
'Ds\Deque::sort' => ['void', 'comparator='=>'callable'],
'Ds\Deque::sorted' => ['Ds\Deque', 'comparator='=>'callable'],
'Ds\Deque::sum' => ['int|float'],
'Ds\Deque::toArray' => ['array'],
'Ds\Deque::unshift' => ['void', '...values='=>'mixed'],
'Ds\Hashable::equals' => ['bool', 'object'=>'mixed'],
'Ds\Hashable::hash' => ['mixed'],
'Ds\Map::__construct' => ['void', 'values='=>'mixed'],
'Ds\Map::allocate' => ['void', 'capacity'=>'int'],
'Ds\Map::apply' => ['void', 'callback'=>'callable'],
'Ds\Map::capacity' => ['int'],
'Ds\Map::clear' => ['void'],
'Ds\Map::copy' => ['Ds\Map'],
'Ds\Map::count' => ['int'],
'Ds\Map::diff' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::filter' => ['Ds\Map', 'callback='=>'callable'],
'Ds\Map::first' => ['Ds\Pair'],
'Ds\Map::get' => ['mixed', 'key'=>'mixed', 'default='=>'mixed'],
'Ds\Map::hasKey' => ['bool', 'key'=>'mixed'],
'Ds\Map::hasValue' => ['bool', 'value'=>'mixed'],
'Ds\Map::intersect' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::isEmpty' => ['bool'],
'Ds\Map::jsonSerialize' => ['array'],
'Ds\Map::keys' => ['Ds\Set'],
'Ds\Map::ksort' => ['void', 'comparator='=>'callable'],
'Ds\Map::ksorted' => ['Ds\Map', 'comparator='=>'callable'],
'Ds\Map::last' => ['Ds\Pair'],
'Ds\Map::map' => ['Ds\Map', 'callback'=>'callable'],
'Ds\Map::merge' => ['Ds\Map', 'values'=>'mixed'],
'Ds\Map::pairs' => ['Ds\Sequence'],
'Ds\Map::put' => ['void', 'key'=>'mixed', 'value'=>'mixed'],
'Ds\Map::putAll' => ['void', 'values'=>'mixed'],
'Ds\Map::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Map::remove' => ['mixed', 'key'=>'mixed', 'default='=>'mixed'],
'Ds\Map::reverse' => ['void'],
'Ds\Map::reversed' => ['Ds\Map'],
'Ds\Map::skip' => ['Ds\Pair', 'position'=>'int'],
'Ds\Map::slice' => ['Ds\Map', 'index'=>'int', 'length='=>'?int'],
'Ds\Map::sort' => ['void', 'comparator='=>'callable'],
'Ds\Map::sorted' => ['Ds\Map', 'comparator='=>'callable'],
'Ds\Map::sum' => ['int|float'],
'Ds\Map::toArray' => ['array'],
'Ds\Map::union' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::values' => ['Ds\Sequence'],
'Ds\Map::xor' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Pair::__construct' => ['void', 'key='=>'mixed', 'value='=>'mixed'],
'Ds\Pair::clear' => ['void'],
'Ds\Pair::copy' => ['Ds\Pair'],
'Ds\Pair::isEmpty' => ['bool'],
'Ds\Pair::jsonSerialize' => ['array'],
'Ds\Pair::toArray' => ['array'],
'Ds\PriorityQueue::__construct' => ['void'],
'Ds\PriorityQueue::allocate' => ['void', 'capacity'=>'int'],
'Ds\PriorityQueue::capacity' => ['int'],
'Ds\PriorityQueue::clear' => ['void'],
'Ds\PriorityQueue::copy' => ['Ds\PriorityQueue'],
'Ds\PriorityQueue::count' => ['int'],
'Ds\PriorityQueue::isEmpty' => ['bool'],
'Ds\PriorityQueue::jsonSerialize' => ['array'],
'Ds\PriorityQueue::peek' => ['mixed'],
'Ds\PriorityQueue::pop' => ['mixed'],
'Ds\PriorityQueue::push' => ['void', 'value'=>'mixed', 'priority'=>'int'],
'Ds\PriorityQueue::toArray' => ['array'],
'Ds\Queue::__construct' => ['void', 'values='=>'mixed'],
'Ds\Queue::allocate' => ['void', 'capacity'=>'int'],
'Ds\Queue::capacity' => ['int'],
'Ds\Queue::clear' => ['void'],
'Ds\Queue::copy' => ['Ds\Queue'],
'Ds\Queue::count' => ['int'],
'Ds\Queue::isEmpty' => ['bool'],
'Ds\Queue::jsonSerialize' => ['array'],
'Ds\Queue::peek' => ['mixed'],
'Ds\Queue::pop' => ['mixed'],
'Ds\Queue::push' => ['void', '...values='=>'mixed'],
'Ds\Queue::toArray' => ['array'],
'Ds\Sequence::allocate' => ['void', 'capacity'=>'int'],
'Ds\Sequence::apply' => ['void', 'callback'=>'callable'],
'Ds\Sequence::capacity' => ['int'],
'Ds\Sequence::contains' => ['bool', '...values='=>'mixed'],
'Ds\Sequence::filter' => ['Ds\Sequence', 'callback='=>'callable'],
'Ds\Sequence::find' => ['mixed', 'value'=>'mixed'],
'Ds\Sequence::first' => ['mixed'],
'Ds\Sequence::get' => ['mixed', 'index'=>'int'],
'Ds\Sequence::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Sequence::join' => ['string', 'glue='=>'string'],
'Ds\Sequence::last' => ['void'],
'Ds\Sequence::map' => ['Ds\Sequence', 'callback'=>'callable'],
'Ds\Sequence::merge' => ['Ds\Sequence', 'values'=>'mixed'],
'Ds\Sequence::pop' => ['mixed'],
'Ds\Sequence::push' => ['void', '...values='=>'mixed'],
'Ds\Sequence::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Sequence::remove' => ['mixed', 'index'=>'int'],
'Ds\Sequence::reverse' => ['void'],
'Ds\Sequence::reversed' => ['Ds\Sequence'],
'Ds\Sequence::rotate' => ['void', 'rotations'=>'int'],
'Ds\Sequence::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Sequence::shift' => ['mixed'],
'Ds\Sequence::slice' => ['Ds\Sequence', 'index'=>'int', 'length='=>'?int'],
'Ds\Sequence::sort' => ['void', 'comparator='=>'callable'],
'Ds\Sequence::sorted' => ['Ds\Sequence', 'comparator='=>'callable'],
'Ds\Sequence::sum' => ['int|float'],
'Ds\Sequence::unshift' => ['void', '...values='=>'mixed'],
'Ds\Set::__construct' => ['void', 'values='=>'mixed'],
'Ds\Set::add' => ['void', '...values='=>'mixed'],
'Ds\Set::allocate' => ['void', 'capacity'=>'int'],
'Ds\Set::capacity' => ['int'],
'Ds\Set::clear' => ['void'],
'Ds\Set::contains' => ['bool', '...values='=>'mixed'],
'Ds\Set::copy' => ['Ds\Set'],
'Ds\Set::count' => ['int'],
'Ds\Set::diff' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::filter' => ['Ds\Set', 'callback='=>'callable'],
'Ds\Set::first' => ['mixed'],
'Ds\Set::get' => ['mixed', 'index'=>'int'],
'Ds\Set::intersect' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::isEmpty' => ['bool'],
'Ds\Set::join' => ['string', 'glue='=>'string'],
'Ds\Set::jsonSerialize' => ['array'],
'Ds\Set::last' => ['mixed'],
'Ds\Set::merge' => ['Ds\Set', 'values'=>'mixed'],
'Ds\Set::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Set::remove' => ['void', '...values='=>'mixed'],
'Ds\Set::reverse' => ['void'],
'Ds\Set::reversed' => ['Ds\Set'],
'Ds\Set::slice' => ['Ds\Set', 'index'=>'int', 'length='=>'?int'],
'Ds\Set::sort' => ['void', 'comparator='=>'callable'],
'Ds\Set::sorted' => ['Ds\Set', 'comparator='=>'callable'],
'Ds\Set::sum' => ['int|float'],
'Ds\Set::toArray' => ['array'],
'Ds\Set::union' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::xor' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Stack::__construct' => ['void', 'values='=>'mixed'],
'Ds\Stack::allocate' => ['void', 'capacity'=>'int'],
'Ds\Stack::capacity' => ['int'],
'Ds\Stack::clear' => ['void'],
'Ds\Stack::copy' => ['Ds\Stack'],
'Ds\Stack::count' => ['int'],
'Ds\Stack::isEmpty' => ['bool'],
'Ds\Stack::jsonSerialize' => ['array'],
'Ds\Stack::peek' => ['mixed'],
'Ds\Stack::pop' => ['mixed'],
'Ds\Stack::push' => ['void', '...values='=>'mixed'],
'Ds\Stack::toArray' => ['array'],
'Ds\Vector::__construct' => ['void', 'values='=>'mixed'],
'Ds\Vector::allocate' => ['void', 'capacity'=>'int'],
'Ds\Vector::apply' => ['void', 'callback'=>'callable'],
'Ds\Vector::capacity' => ['int'],
'Ds\Vector::clear' => ['void'],
'Ds\Vector::contains' => ['bool', '...values='=>'mixed'],
'Ds\Vector::copy' => ['Ds\Vector'],
'Ds\Vector::count' => ['int'],
'Ds\Vector::filter' => ['Ds\Vector', 'callback='=>'callable'],
'Ds\Vector::find' => ['mixed', 'value'=>'mixed'],
'Ds\Vector::first' => ['mixed'],
'Ds\Vector::get' => ['mixed', 'index'=>'int'],
'Ds\Vector::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Vector::isEmpty' => ['bool'],
'Ds\Vector::join' => ['string', 'glue='=>'string'],
'Ds\Vector::jsonSerialize' => ['array'],
'Ds\Vector::last' => ['mixed'],
'Ds\Vector::map' => ['Ds\Vector', 'callback'=>'callable'],
'Ds\Vector::merge' => ['Ds\Vector', 'values'=>'mixed'],
'Ds\Vector::pop' => ['mixed'],
'Ds\Vector::push' => ['void', '...values='=>'mixed'],
'Ds\Vector::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Vector::remove' => ['mixed', 'index'=>'int'],
'Ds\Vector::reverse' => ['void'],
'Ds\Vector::reversed' => ['Ds\Vector'],
'Ds\Vector::rotate' => ['void', 'rotations'=>'int'],
'Ds\Vector::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Vector::shift' => ['mixed'],
'Ds\Vector::slice' => ['Ds\Vector', 'index'=>'int', 'length='=>'?int'],
'Ds\Vector::sort' => ['void', 'comparator='=>'callable'],
'Ds\Vector::sorted' => ['Ds\Vector', 'comparator='=>'callable'],
'Ds\Vector::sum' => ['int|float'],
'Ds\Vector::toArray' => ['array'],
'Ds\Vector::unshift' => ['void', '...values='=>'mixed'],
'each' => ['array{0:int|string,key:int|string,1:mixed,value:mixed}', '&r_arr'=>'array'],
'easter_date' => ['int', 'year='=>'int'],
'easter_days' => ['int', 'year='=>'int', 'mode='=>'int'],
'echo' => ['void', 'arg1'=>'string', '...args='=>'string'],
'eio_busy' => ['resource', 'delay'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_cancel' => ['void', 'req'=>'resource'],
'eio_chmod' => ['resource', 'path'=>'string', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_chown' => ['resource', 'path'=>'string', 'uid'=>'int', 'gid='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_close' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_custom' => ['resource', 'execute'=>'callable', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_dup2' => ['resource', 'fd'=>'mixed', 'fd2'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_event_loop' => ['bool'],
'eio_fallocate' => ['resource', 'fd'=>'mixed', 'mode'=>'int', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fchmod' => ['resource', 'fd'=>'mixed', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fchown' => ['resource', 'fd'=>'mixed', 'uid'=>'int', 'gid='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fdatasync' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fstat' => ['resource', 'fd'=>'mixed', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_fstatvfs' => ['resource', 'fd'=>'mixed', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_fsync' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_ftruncate' => ['resource', 'fd'=>'mixed', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_futime' => ['resource', 'fd'=>'mixed', 'atime'=>'float', 'mtime'=>'float', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_get_event_stream' => ['mixed'],
'eio_get_last_error' => ['string', 'req'=>'resource'],
'eio_grp' => ['resource', 'callback'=>'callable', 'data='=>'string'],
'eio_grp_add' => ['void', 'grp'=>'resource', 'req'=>'resource'],
'eio_grp_cancel' => ['void', 'grp'=>'resource'],
'eio_grp_limit' => ['void', 'grp'=>'resource', 'limit'=>'int'],
'eio_init' => ['void'],
'eio_link' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_lstat' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_mkdir' => ['resource', 'path'=>'string', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_mknod' => ['resource', 'path'=>'string', 'mode'=>'int', 'dev'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_nop' => ['resource', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_npending' => ['int'],
'eio_nready' => ['int'],
'eio_nreqs' => ['int'],
'eio_nthreads' => ['int'],
'eio_open' => ['resource', 'path'=>'string', 'flags'=>'int', 'mode'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_poll' => ['int'],
'eio_read' => ['resource', 'fd'=>'mixed', 'length'=>'int', 'offset'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_readahead' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_readdir' => ['resource', 'path'=>'string', 'flags'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_readlink' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_realpath' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_rename' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_rmdir' => ['resource', 'path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_seek' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'whence'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sendfile' => ['resource', 'out_fd'=>'mixed', 'in_fd'=>'mixed', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'string'],
'eio_set_max_idle' => ['void', 'nthreads'=>'int'],
'eio_set_max_parallel' => ['void', 'nthreads'=>'int'],
'eio_set_max_poll_reqs' => ['void', 'nreqs'=>'int'],
'eio_set_max_poll_time' => ['void', 'nseconds'=>'float'],
'eio_set_min_parallel' => ['void', 'nthreads'=>'string'],
'eio_stat' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_statvfs' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_symlink' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sync' => ['resource', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sync_file_range' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'nbytes'=>'int', 'flags'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_syncfs' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_truncate' => ['resource', 'path'=>'string', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_unlink' => ['resource', 'path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_utime' => ['resource', 'path'=>'string', 'atime'=>'float', 'mtime'=>'float', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_write' => ['resource', 'fd'=>'mixed', 'string'=>'string', 'length='=>'int', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'empty' => ['bool', 'value'=>'mixed'],
'EmptyIterator::current' => ['mixed'],
'EmptyIterator::key' => ['mixed'],
'EmptyIterator::next' => ['void'],
'EmptyIterator::rewind' => ['void'],
'EmptyIterator::valid' => ['bool'],
'enchant_broker_describe' => ['array', 'broker'=>'resource'],
'enchant_broker_dict_exists' => ['bool', 'broker'=>'resource', 'tag'=>'string'],
'enchant_broker_free' => ['bool', 'broker'=>'resource'],
'enchant_broker_free_dict' => ['bool', 'dictionary'=>'resource'],
'enchant_broker_get_dict_path' => ['string', 'broker'=>'resource', 'type'=>'int'],
'enchant_broker_get_error' => ['string|false', 'broker'=>'resource'],
'enchant_broker_init' => ['resource|false'],
'enchant_broker_list_dicts' => ['array<int,array{lang_tag:string,provider_name:string,provider_desc:string,provider_file:string}>|false', 'broker'=>'resource'],
'enchant_broker_request_dict' => ['resource|false', 'broker'=>'resource', 'tag'=>'string'],
'enchant_broker_request_pwl_dict' => ['resource|false', 'broker'=>'resource', 'filename'=>'string'],
'enchant_broker_set_dict_path' => ['bool', 'broker'=>'resource', 'type'=>'int', 'path'=>'string'],
'enchant_broker_set_ordering' => ['bool', 'broker'=>'resource', 'tag'=>'string', 'ordering'=>'string'],
'enchant_dict_add_to_personal' => ['void', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_add_to_session' => ['void', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_check' => ['bool', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_describe' => ['array', 'dictionary'=>'resource'],
'enchant_dict_get_error' => ['string', 'dictionary'=>'resource'],
'enchant_dict_is_in_session' => ['bool', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_quick_check' => ['bool', 'dictionary'=>'resource', 'word'=>'string', '&w_suggestions='=>'array<int,string>'],
'enchant_dict_store_replacement' => ['void', 'dictionary'=>'resource', 'misspelled'=>'string', 'correct'=>'string'],
'enchant_dict_suggest' => ['array', 'dictionary'=>'resource', 'word'=>'string'],
'end' => ['mixed|false', '&r_array'=>'array|object'],
'Error::__clone' => ['void'],
'Error::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'Error::__toString' => ['string'],
'Error::getCode' => ['int'],
'Error::getFile' => ['string'],
'Error::getLine' => ['int'],
'Error::getMessage' => ['string'],
'Error::getPrevious' => ['Throwable|Error|null'],
'Error::getTrace' => ['list<array<string,mixed>>'],
'Error::getTraceAsString' => ['string'],
'error_clear_last' => ['void'],
'error_get_last' => ['?array{type:int,message:string,file:string,line:int}'],
'error_log' => ['bool', 'message'=>'string', 'message_type='=>'int', 'destination='=>'string', 'additional_headers='=>'string'],
'error_reporting' => ['int', 'error_level='=>'int'],
'ErrorException::__clone' => ['void'],
'ErrorException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'severity='=>'int', 'filename='=>'string', 'lineno='=>'int', 'previous='=>'?Throwable|?ErrorException'],
'ErrorException::__toString' => ['string'],
'ErrorException::getCode' => ['int'],
'ErrorException::getFile' => ['string'],
'ErrorException::getLine' => ['int'],
'ErrorException::getMessage' => ['string'],
'ErrorException::getPrevious' => ['Throwable|ErrorException|null'],
'ErrorException::getSeverity' => ['int'],
'ErrorException::getTrace' => ['list<array<string,mixed>>'],
'ErrorException::getTraceAsString' => ['string'],
'escapeshellarg' => ['string', 'arg'=>'string'],
'escapeshellcmd' => ['string', 'command'=>'string'],
'Ev::backend' => ['int'],
'Ev::depth' => ['int'],
'Ev::embeddableBackends' => ['int'],
'Ev::feedSignal' => ['void', 'signum'=>'int'],
'Ev::feedSignalEvent' => ['void', 'signum'=>'int'],
'Ev::iteration' => ['int'],
'Ev::now' => ['float'],
'Ev::nowUpdate' => ['void'],
'Ev::recommendedBackends' => ['int'],
'Ev::resume' => ['void'],
'Ev::run' => ['void', 'flags='=>'int'],
'Ev::sleep' => ['void', 'seconds'=>'float'],
'Ev::stop' => ['void', 'how='=>'int'],
'Ev::supportedBackends' => ['int'],
'Ev::suspend' => ['void'],
'Ev::time' => ['float'],
'Ev::verify' => ['void'],
'eval' => ['mixed', 'code_str'=>'string'],
'EvCheck::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvCheck::clear' => ['int'],
'EvCheck::createStopped' => ['EvCheck', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvCheck::feed' => ['void', 'events'=>'int'],
'EvCheck::getLoop' => ['EvLoop'],
'EvCheck::invoke' => ['void', 'events'=>'int'],
'EvCheck::keepAlive' => ['void', 'value'=>'bool'],
'EvCheck::setCallback' => ['void', 'callback'=>'callable'],
'EvCheck::start' => ['void'],
'EvCheck::stop' => ['void'],
'EvChild::__construct' => ['void', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvChild::clear' => ['int'],
'EvChild::createStopped' => ['EvChild', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvChild::feed' => ['void', 'events'=>'int'],
'EvChild::getLoop' => ['EvLoop'],
'EvChild::invoke' => ['void', 'events'=>'int'],
'EvChild::keepAlive' => ['void', 'value'=>'bool'],
'EvChild::set' => ['void', 'pid'=>'int', 'trace'=>'bool'],
'EvChild::setCallback' => ['void', 'callback'=>'callable'],
'EvChild::start' => ['void'],
'EvChild::stop' => ['void'],
'EvEmbed::__construct' => ['void', 'other'=>'object', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvEmbed::clear' => ['int'],
'EvEmbed::createStopped' => ['EvEmbed', 'other'=>'object', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvEmbed::feed' => ['void', 'events'=>'int'],
'EvEmbed::getLoop' => ['EvLoop'],
'EvEmbed::invoke' => ['void', 'events'=>'int'],
'EvEmbed::keepAlive' => ['void', 'value'=>'bool'],
'EvEmbed::set' => ['void', 'other'=>'object'],
'EvEmbed::setCallback' => ['void', 'callback'=>'callable'],
'EvEmbed::start' => ['void'],
'EvEmbed::stop' => ['void'],
'EvEmbed::sweep' => ['void'],
'Event::__construct' => ['void', 'base'=>'EventBase', 'fd'=>'mixed', 'what'=>'int', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::add' => ['bool', 'timeout='=>'float'],
'Event::addSignal' => ['bool', 'timeout='=>'float'],
'Event::addTimer' => ['bool', 'timeout='=>'float'],
'Event::del' => ['bool'],
'Event::delSignal' => ['bool'],
'Event::delTimer' => ['bool'],
'Event::free' => ['void'],
'Event::getSupportedMethods' => ['array'],
'Event::pending' => ['bool', 'flags'=>'int'],
'Event::set' => ['bool', 'base'=>'EventBase', 'fd'=>'mixed', 'what='=>'int', 'cb='=>'callable', 'arg='=>'mixed'],
'Event::setPriority' => ['bool', 'priority'=>'int'],
'Event::setTimer' => ['bool', 'base'=>'EventBase', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::signal' => ['Event', 'base'=>'EventBase', 'signum'=>'int', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::timer' => ['Event', 'base'=>'EventBase', 'cb'=>'callable', 'arg='=>'mixed'],
'event_add' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_base_free' => ['void', 'event_base'=>'resource'],
'event_base_loop' => ['int', 'event_base'=>'resource', 'flags='=>'int'],
'event_base_loopbreak' => ['bool', 'event_base'=>'resource'],
'event_base_loopexit' => ['bool', 'event_base'=>'resource', 'timeout='=>'int'],
'event_base_new' => ['resource|false'],
'event_base_priority_init' => ['bool', 'event_base'=>'resource', 'npriorities'=>'int'],
'event_base_reinit' => ['bool', 'event_base'=>'resource'],
'event_base_set' => ['bool', 'event'=>'resource', 'event_base'=>'resource'],
'event_buffer_base_set' => ['bool', 'bevent'=>'resource', 'event_base'=>'resource'],
'event_buffer_disable' => ['bool', 'bevent'=>'resource', 'events'=>'int'],
'event_buffer_enable' => ['bool', 'bevent'=>'resource', 'events'=>'int'],
'event_buffer_fd_set' => ['void', 'bevent'=>'resource', 'fd'=>'resource'],
'event_buffer_free' => ['void', 'bevent'=>'resource'],
'event_buffer_new' => ['resource|false', 'stream'=>'resource', 'readcb'=>'callable|null', 'writecb'=>'callable|null', 'errorcb'=>'callable', 'arg='=>'mixed'],
'event_buffer_priority_set' => ['bool', 'bevent'=>'resource', 'priority'=>'int'],
'event_buffer_read' => ['string', 'bevent'=>'resource', 'data_size'=>'int'],
'event_buffer_set_callback' => ['bool', 'event'=>'resource', 'readcb'=>'mixed', 'writecb'=>'mixed', 'errorcb'=>'mixed', 'arg='=>'mixed'],
'event_buffer_timeout_set' => ['void', 'bevent'=>'resource', 'read_timeout'=>'int', 'write_timeout'=>'int'],
'event_buffer_watermark_set' => ['void', 'bevent'=>'resource', 'events'=>'int', 'lowmark'=>'int', 'highmark'=>'int'],
'event_buffer_write' => ['bool', 'bevent'=>'resource', 'data'=>'string', 'data_size='=>'int'],
'event_del' => ['bool', 'event'=>'resource'],
'event_free' => ['void', 'event'=>'resource'],
'event_new' => ['resource|false'],
'event_priority_set' => ['bool', 'event'=>'resource', 'priority'=>'int'],
'event_set' => ['bool', 'event'=>'resource', 'fd'=>'int|resource', 'events'=>'int', 'callback'=>'callable', 'arg='=>'mixed'],
'event_timer_add' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_timer_del' => ['bool', 'event'=>'resource'],
'event_timer_new' => ['resource|false'],
'event_timer_pending' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_timer_set' => ['bool', 'event'=>'resource', 'callback'=>'callable', 'arg='=>'mixed'],
'EventBase::__construct' => ['void', 'cfg='=>'EventConfig'],
'EventBase::dispatch' => ['void'],
'EventBase::exit' => ['bool', 'timeout='=>'float'],
'EventBase::free' => ['void'],
'EventBase::getFeatures' => ['int'],
'EventBase::getMethod' => ['string', 'cfg='=>'EventConfig'],
'EventBase::getTimeOfDayCached' => ['float'],
'EventBase::gotExit' => ['bool'],
'EventBase::gotStop' => ['bool'],
'EventBase::loop' => ['bool', 'flags='=>'int'],
'EventBase::priorityInit' => ['bool', 'n_priorities'=>'int'],
'EventBase::reInit' => ['bool'],
'EventBase::stop' => ['bool'],
'EventBuffer::__construct' => ['void'],
'EventBuffer::add' => ['bool', 'data'=>'string'],
'EventBuffer::addBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBuffer::appendFrom' => ['int', 'buf'=>'EventBuffer', 'length'=>'int'],
'EventBuffer::copyout' => ['int', '&w_data'=>'string', 'max_bytes'=>'int'],
'EventBuffer::drain' => ['bool', 'length'=>'int'],
'EventBuffer::enableLocking' => ['void'],
'EventBuffer::expand' => ['bool', 'length'=>'int'],
'EventBuffer::freeze' => ['bool', 'at_front'=>'bool'],
'EventBuffer::lock' => ['void'],
'EventBuffer::prepend' => ['bool', 'data'=>'string'],
'EventBuffer::prependBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBuffer::pullup' => ['string', 'size'=>'int'],
'EventBuffer::read' => ['string', 'max_bytes'=>'int'],
'EventBuffer::readFrom' => ['int', 'fd'=>'mixed', 'howmuch'=>'int'],
'EventBuffer::readLine' => ['string', 'eol_style'=>'int'],
'EventBuffer::search' => ['mixed', 'what'=>'string', 'start='=>'int', 'end='=>'int'],
'EventBuffer::searchEol' => ['mixed', 'start='=>'int', 'eol_style='=>'int'],
'EventBuffer::substr' => ['string', 'start'=>'int', 'length='=>'int'],
'EventBuffer::unfreeze' => ['bool', 'at_front'=>'bool'],
'EventBuffer::unlock' => ['bool'],
'EventBuffer::write' => ['int', 'fd'=>'mixed', 'howmuch='=>'int'],
'EventBufferEvent::__construct' => ['void', 'base'=>'EventBase', 'socket='=>'mixed', 'options='=>'int', 'readcb='=>'callable', 'writecb='=>'callable', 'eventcb='=>'callable'],
'EventBufferEvent::close' => ['void'],
'EventBufferEvent::connect' => ['bool', 'addr'=>'string'],
'EventBufferEvent::connectHost' => ['bool', 'dns_base'=>'EventDnsBase', 'hostname'=>'string', 'port'=>'int', 'family='=>'int'],
'EventBufferEvent::createPair' => ['array', 'base'=>'EventBase', 'options='=>'int'],
'EventBufferEvent::disable' => ['bool', 'events'=>'int'],
'EventBufferEvent::enable' => ['bool', 'events'=>'int'],
'EventBufferEvent::free' => ['void'],
'EventBufferEvent::getDnsErrorString' => ['string'],
'EventBufferEvent::getEnabled' => ['int'],
'EventBufferEvent::getInput' => ['EventBuffer'],
'EventBufferEvent::getOutput' => ['EventBuffer'],
'EventBufferEvent::read' => ['string', 'size'=>'int'],
'EventBufferEvent::readBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBufferEvent::setCallbacks' => ['void', 'readcb'=>'callable', 'writecb'=>'callable', 'eventcb'=>'callable', 'arg='=>'string'],
'EventBufferEvent::setPriority' => ['bool', 'priority'=>'int'],
'EventBufferEvent::setTimeouts' => ['bool', 'timeout_read'=>'float', 'timeout_write'=>'float'],
'EventBufferEvent::setWatermark' => ['void', 'events'=>'int', 'lowmark'=>'int', 'highmark'=>'int'],
'EventBufferEvent::sslError' => ['string'],
'EventBufferEvent::sslFilter' => ['EventBufferEvent', 'base'=>'EventBase', 'underlying'=>'EventBufferEvent', 'ctx'=>'EventSslContext', 'state'=>'int', 'options='=>'int'],
'EventBufferEvent::sslGetCipherInfo' => ['string'],
'EventBufferEvent::sslGetCipherName' => ['string'],
'EventBufferEvent::sslGetCipherVersion' => ['string'],
'EventBufferEvent::sslGetProtocol' => ['string'],
'EventBufferEvent::sslRenegotiate' => ['void'],
'EventBufferEvent::sslSocket' => ['EventBufferEvent', 'base'=>'EventBase', 'socket'=>'mixed', 'ctx'=>'EventSslContext', 'state'=>'int', 'options='=>'int'],
'EventBufferEvent::write' => ['bool', 'data'=>'string'],
'EventBufferEvent::writeBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventConfig::__construct' => ['void'],
'EventConfig::avoidMethod' => ['bool', 'method'=>'string'],
'EventConfig::requireFeatures' => ['bool', 'feature'=>'int'],
'EventConfig::setMaxDispatchInterval' => ['void', 'max_interval'=>'int', 'max_callbacks'=>'int', 'min_priority'=>'int'],
'EventDnsBase::__construct' => ['void', 'base'=>'EventBase', 'initialize'=>'bool'],
'EventDnsBase::addNameserverIp' => ['bool', 'ip'=>'string'],
'EventDnsBase::addSearch' => ['void', 'domain'=>'string'],
'EventDnsBase::clearSearch' => ['void'],
'EventDnsBase::countNameservers' => ['int'],
'EventDnsBase::loadHosts' => ['bool', 'hosts'=>'string'],
'EventDnsBase::parseResolvConf' => ['bool', 'flags'=>'int', 'filename'=>'string'],
'EventDnsBase::setOption' => ['bool', 'option'=>'string', 'value'=>'string'],
'EventDnsBase::setSearchNdots' => ['bool', 'ndots'=>'int'],
'EventHttp::__construct' => ['void', 'base'=>'EventBase', 'ctx='=>'EventSslContext'],
'EventHttp::accept' => ['bool', 'socket'=>'mixed'],
'EventHttp::addServerAlias' => ['bool', 'alias'=>'string'],
'EventHttp::bind' => ['void', 'address'=>'string', 'port'=>'int'],
'EventHttp::removeServerAlias' => ['bool', 'alias'=>'string'],
'EventHttp::setAllowedMethods' => ['void', 'methods'=>'int'],
'EventHttp::setCallback' => ['void', 'path'=>'string', 'cb'=>'string', 'arg='=>'string'],
'EventHttp::setDefaultCallback' => ['void', 'cb'=>'string', 'arg='=>'string'],
'EventHttp::setMaxBodySize' => ['void', 'value'=>'int'],
'EventHttp::setMaxHeadersSize' => ['void', 'value'=>'int'],
'EventHttp::setTimeout' => ['void', 'value'=>'int'],
'EventHttpConnection::__construct' => ['void', 'base'=>'EventBase', 'dns_base'=>'EventDnsBase', 'address'=>'string', 'port'=>'int', 'ctx='=>'EventSslContext'],
'EventHttpConnection::getBase' => ['EventBase'],
'EventHttpConnection::getPeer' => ['void', '&w_address'=>'string', '&w_port'=>'int'],
'EventHttpConnection::makeRequest' => ['bool', 'req'=>'EventHttpRequest', 'type'=>'int', 'uri'=>'string'],
'EventHttpConnection::setCloseCallback' => ['void', 'callback'=>'callable', 'data='=>'mixed'],
'EventHttpConnection::setLocalAddress' => ['void', 'address'=>'string'],
'EventHttpConnection::setLocalPort' => ['void', 'port'=>'int'],
'EventHttpConnection::setMaxBodySize' => ['void', 'max_size'=>'string'],
'EventHttpConnection::setMaxHeadersSize' => ['void', 'max_size'=>'string'],
'EventHttpConnection::setRetries' => ['void', 'retries'=>'int'],
'EventHttpConnection::setTimeout' => ['void', 'timeout'=>'int'],
'EventHttpRequest::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed'],
'EventHttpRequest::addHeader' => ['bool', 'key'=>'string', 'value'=>'string', 'type'=>'int'],
'EventHttpRequest::cancel' => ['void'],
'EventHttpRequest::clearHeaders' => ['void'],
'EventHttpRequest::closeConnection' => ['void'],
'EventHttpRequest::findHeader' => ['void', 'key'=>'string', 'type'=>'string'],
'EventHttpRequest::free' => ['void'],
'EventHttpRequest::getBufferEvent' => ['EventBufferEvent'],
'EventHttpRequest::getCommand' => ['void'],
'EventHttpRequest::getConnection' => ['EventHttpConnection'],
'EventHttpRequest::getHost' => ['string'],
'EventHttpRequest::getInputBuffer' => ['EventBuffer'],
'EventHttpRequest::getInputHeaders' => ['array'],
'EventHttpRequest::getOutputBuffer' => ['EventBuffer'],
'EventHttpRequest::getOutputHeaders' => ['void'],
'EventHttpRequest::getResponseCode' => ['int'],
'EventHttpRequest::getUri' => ['string'],
'EventHttpRequest::removeHeader' => ['void', 'key'=>'string', 'type'=>'string'],
'EventHttpRequest::sendError' => ['void', 'error'=>'int', 'reason='=>'string'],
'EventHttpRequest::sendReply' => ['void', 'code'=>'int', 'reason'=>'string', 'buf='=>'EventBuffer'],
'EventHttpRequest::sendReplyChunk' => ['void', 'buf'=>'EventBuffer'],
'EventHttpRequest::sendReplyEnd' => ['void'],
'EventHttpRequest::sendReplyStart' => ['void', 'code'=>'int', 'reason'=>'string'],
'EventListener::__construct' => ['void', 'base'=>'EventBase', 'cb'=>'callable', 'data'=>'mixed', 'flags'=>'int', 'backlog'=>'int', 'target'=>'mixed'],
'EventListener::disable' => ['bool'],
'EventListener::enable' => ['bool'],
'EventListener::getBase' => ['void'],
'EventListener::getSocketName' => ['bool', '&w_address'=>'string', '&w_port='=>'mixed'],
'EventListener::setCallback' => ['void', 'cb'=>'callable', 'arg='=>'mixed'],
'EventListener::setErrorCallback' => ['void', 'cb'=>'string'],
'EventSslContext::__construct' => ['void', 'method'=>'string', 'options'=>'string'],
'EventUtil::__construct' => ['void'],
'EventUtil::getLastSocketErrno' => ['int', 'socket='=>'mixed'],
'EventUtil::getLastSocketError' => ['string', 'socket='=>'mixed'],
'EventUtil::getSocketFd' => ['int', 'socket'=>'mixed'],
'EventUtil::getSocketName' => ['bool', 'socket'=>'mixed', '&w_address'=>'string', '&w_port='=>'mixed'],
'EventUtil::setSocketOption' => ['bool', 'socket'=>'mixed', 'level'=>'int', 'optname'=>'int', 'optval'=>'mixed'],
'EventUtil::sslRandPoll' => ['void'],
'EvFork::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvFork::clear' => ['int'],
'EvFork::createStopped' => ['EvFork', 'callback'=>'callable', 'data='=>'string', 'priority='=>'string'],
'EvFork::feed' => ['void', 'events'=>'int'],
'EvFork::getLoop' => ['EvLoop'],
'EvFork::invoke' => ['void', 'events'=>'int'],
'EvFork::keepAlive' => ['void', 'value'=>'bool'],
'EvFork::setCallback' => ['void', 'callback'=>'callable'],
'EvFork::start' => ['void'],
'EvFork::stop' => ['void'],
'EvIdle::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIdle::clear' => ['int'],
'EvIdle::createStopped' => ['EvIdle', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIdle::feed' => ['void', 'events'=>'int'],
'EvIdle::getLoop' => ['EvLoop'],
'EvIdle::invoke' => ['void', 'events'=>'int'],
'EvIdle::keepAlive' => ['void', 'value'=>'bool'],
'EvIdle::setCallback' => ['void', 'callback'=>'callable'],
'EvIdle::start' => ['void'],
'EvIdle::stop' => ['void'],
'EvIo::__construct' => ['void', 'fd'=>'mixed', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIo::clear' => ['int'],
'EvIo::createStopped' => ['EvIo', 'fd'=>'resource', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIo::feed' => ['void', 'events'=>'int'],
'EvIo::getLoop' => ['EvLoop'],
'EvIo::invoke' => ['void', 'events'=>'int'],
'EvIo::keepAlive' => ['void', 'value'=>'bool'],
'EvIo::set' => ['void', 'fd'=>'resource', 'events'=>'int'],
'EvIo::setCallback' => ['void', 'callback'=>'callable'],
'EvIo::start' => ['void'],
'EvIo::stop' => ['void'],
'EvLoop::__construct' => ['void', 'flags='=>'int', 'data='=>'mixed', 'io_interval='=>'float', 'timeout_interval='=>'float'],
'EvLoop::backend' => ['int'],
'EvLoop::check' => ['EvCheck', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::child' => ['EvChild', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::defaultLoop' => ['EvLoop', 'flags='=>'int', 'data='=>'mixed', 'io_interval='=>'float', 'timeout_interval='=>'float'],
'EvLoop::embed' => ['EvEmbed', 'other'=>'EvLoop', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::fork' => ['EvFork', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::idle' => ['EvIdle', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::invokePending' => ['void'],
'EvLoop::io' => ['EvIo', 'fd'=>'resource', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::loopFork' => ['void'],
'EvLoop::now' => ['float'],
'EvLoop::nowUpdate' => ['void'],
'EvLoop::periodic' => ['EvPeriodic', 'offset'=>'float', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::prepare' => ['EvPrepare', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::resume' => ['void'],
'EvLoop::run' => ['void', 'flags='=>'int'],
'EvLoop::signal' => ['EvSignal', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::stat' => ['EvStat', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::stop' => ['void', 'how='=>'int'],
'EvLoop::suspend' => ['void'],
'EvLoop::timer' => ['EvTimer', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::verify' => ['void'],
'EvPeriodic::__construct' => ['void', 'offset'=>'float', 'interval'=>'string', 'reschedule_cb'=>'callable', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPeriodic::again' => ['void'],
'EvPeriodic::at' => ['float'],
'EvPeriodic::clear' => ['int'],
'EvPeriodic::createStopped' => ['EvPeriodic', 'offset'=>'float', 'interval'=>'float', 'reschedule_cb'=>'callable', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPeriodic::feed' => ['void', 'events'=>'int'],
'EvPeriodic::getLoop' => ['EvLoop'],
'EvPeriodic::invoke' => ['void', 'events'=>'int'],
'EvPeriodic::keepAlive' => ['void', 'value'=>'bool'],
'EvPeriodic::set' => ['void', 'offset'=>'float', 'interval'=>'float'],
'EvPeriodic::setCallback' => ['void', 'callback'=>'callable'],
'EvPeriodic::start' => ['void'],
'EvPeriodic::stop' => ['void'],
'EvPrepare::__construct' => ['void', 'callback'=>'string', 'data='=>'string', 'priority='=>'string'],
'EvPrepare::clear' => ['int'],
'EvPrepare::createStopped' => ['EvPrepare', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPrepare::feed' => ['void', 'events'=>'int'],
'EvPrepare::getLoop' => ['EvLoop'],
'EvPrepare::invoke' => ['void', 'events'=>'int'],
'EvPrepare::keepAlive' => ['void', 'value'=>'bool'],
'EvPrepare::setCallback' => ['void', 'callback'=>'callable'],
'EvPrepare::start' => ['void'],
'EvPrepare::stop' => ['void'],
'EvSignal::__construct' => ['void', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvSignal::clear' => ['int'],
'EvSignal::createStopped' => ['EvSignal', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvSignal::feed' => ['void', 'events'=>'int'],
'EvSignal::getLoop' => ['EvLoop'],
'EvSignal::invoke' => ['void', 'events'=>'int'],
'EvSignal::keepAlive' => ['void', 'value'=>'bool'],
'EvSignal::set' => ['void', 'signum'=>'int'],
'EvSignal::setCallback' => ['void', 'callback'=>'callable'],
'EvSignal::start' => ['void'],
'EvSignal::stop' => ['void'],
'EvStat::__construct' => ['void', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvStat::attr' => ['array'],
'EvStat::clear' => ['int'],
'EvStat::createStopped' => ['EvStat', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvStat::feed' => ['void', 'events'=>'int'],
'EvStat::getLoop' => ['EvLoop'],
'EvStat::invoke' => ['void', 'events'=>'int'],
'EvStat::keepAlive' => ['void', 'value'=>'bool'],
'EvStat::prev' => ['array'],
'EvStat::set' => ['void', 'path'=>'string', 'interval'=>'float'],
'EvStat::setCallback' => ['void', 'callback'=>'callable'],
'EvStat::start' => ['void'],
'EvStat::stat' => ['bool'],
'EvStat::stop' => ['void'],
'EvTimer::__construct' => ['void', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvTimer::again' => ['void'],
'EvTimer::clear' => ['int'],
'EvTimer::createStopped' => ['EvTimer', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvTimer::feed' => ['void', 'events'=>'int'],
'EvTimer::getLoop' => ['EvLoop'],
'EvTimer::invoke' => ['void', 'events'=>'int'],
'EvTimer::keepAlive' => ['void', 'value'=>'bool'],
'EvTimer::set' => ['void', 'after'=>'float', 'repeat'=>'float'],
'EvTimer::setCallback' => ['void', 'callback'=>'callable'],
'EvTimer::start' => ['void'],
'EvTimer::stop' => ['void'],
'EvWatcher::__construct' => ['void'],
'EvWatcher::clear' => ['int'],
'EvWatcher::feed' => ['void', 'revents'=>'int'],
'EvWatcher::getLoop' => ['EvLoop'],
'EvWatcher::invoke' => ['void', 'revents'=>'int'],
'EvWatcher::keepalive' => ['bool', 'value='=>'bool'],
'EvWatcher::setCallback' => ['void', 'callback'=>'callable'],
'EvWatcher::start' => ['void'],
'EvWatcher::stop' => ['void'],
'Exception::__clone' => ['void'],
'Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Exception'],
'Exception::__toString' => ['string'],
'Exception::getCode' => ['int|string'],
'Exception::getFile' => ['string'],
'Exception::getLine' => ['int'],
'Exception::getMessage' => ['string'],
'Exception::getPrevious' => ['?Throwable|?Exception'],
'Exception::getTrace' => ['list<array<string,mixed>>'],
'Exception::getTraceAsString' => ['string'],
'exec' => ['string', 'command'=>'string', '&w_output='=>'array', '&w_result_code='=>'int'],
'exif_imagetype' => ['int|false', 'filename'=>'string'],
'exif_read_data' => ['array|false', 'file'=>'string|resource', 'required_sections='=>'string', 'as_arrays='=>'bool', 'read_thumbnail='=>'bool'],
'exif_tagname' => ['string|false', 'index'=>'int'],
'exif_thumbnail' => ['string|false', 'file'=>'string', '&w_width='=>'int', '&w_height='=>'int', '&w_image_type='=>'int'],
'exit' => ['', 'status'=>'string|int'],
'exp' => ['float', 'num'=>'float'],
'expect_expectl' => ['int', 'expect'=>'resource', 'cases'=>'array', 'match='=>'array'],
'expect_popen' => ['resource|false', 'command'=>'string'],
'explode' => ['list<string>|false', 'separator'=>'string', 'string'=>'string', 'limit='=>'int'],
'expm1' => ['float', 'num'=>'float'],
'extension_loaded' => ['bool', 'extension'=>'string'],
'extract' => ['int', '&rw_array'=>'array', 'flags='=>'int', 'prefix='=>'?string'],
'ezmlm_hash' => ['int', 'addr'=>'string'],
'fam_cancel_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fam_close' => ['void', 'fam'=>'resource'],
'fam_monitor_collection' => ['resource', 'fam'=>'resource', 'dirname'=>'string', 'depth'=>'int', 'mask'=>'string'],
'fam_monitor_directory' => ['resource', 'fam'=>'resource', 'dirname'=>'string'],
'fam_monitor_file' => ['resource', 'fam'=>'resource', 'filename'=>'string'],
'fam_next_event' => ['array', 'fam'=>'resource'],
'fam_open' => ['resource|false', 'appname='=>'string'],
'fam_pending' => ['int', 'fam'=>'resource'],
'fam_resume_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fam_suspend_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fann_cascadetrain_on_data' => ['bool', 'ann'=>'resource', 'data'=>'resource', 'max_neurons'=>'int', 'neurons_between_reports'=>'int', 'desired_error'=>'float'],
'fann_cascadetrain_on_file' => ['bool', 'ann'=>'resource', 'filename'=>'string', 'max_neurons'=>'int', 'neurons_between_reports'=>'int', 'desired_error'=>'float'],
'fann_clear_scaling_params' => ['bool', 'ann'=>'resource'],
'fann_copy' => ['resource|false', 'ann'=>'resource'],
'fann_create_from_file' => ['resource', 'configuration_file'=>'string'],
'fann_create_shortcut' => ['resource|false', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_shortcut_array' => ['resource|false', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_sparse' => ['resource|false', 'connection_rate'=>'float', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_sparse_array' => ['resource|false', 'connection_rate'=>'float', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_standard' => ['resource|false', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_standard_array' => ['resource|false', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_train' => ['resource', 'num_data'=>'int', 'num_input'=>'int', 'num_output'=>'int'],
'fann_create_train_from_callback' => ['resource', 'num_data'=>'int', 'num_input'=>'int', 'num_output'=>'int', 'user_function'=>'callable'],
'fann_descale_input' => ['bool', 'ann'=>'resource', 'input_vector'=>'array'],
'fann_descale_output' => ['bool', 'ann'=>'resource', 'output_vector'=>'array'],
'fann_descale_train' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_destroy' => ['bool', 'ann'=>'resource'],
'fann_destroy_train' => ['bool', 'train_data'=>'resource'],
'fann_duplicate_train_data' => ['resource', 'data'=>'resource'],
'fann_get_activation_function' => ['int|false', 'ann'=>'resource', 'layer'=>'int', 'neuron'=>'int'],
'fann_get_activation_steepness' => ['float|false', 'ann'=>'resource', 'layer'=>'int', 'neuron'=>'int'],
'fann_get_bias_array' => ['array', 'ann'=>'resource'],
'fann_get_bit_fail' => ['int|false', 'ann'=>'resource'],
'fann_get_bit_fail_limit' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_activation_functions' => ['array|false', 'ann'=>'resource'],
'fann_get_cascade_activation_functions_count' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_activation_steepnesses' => ['array|false', 'ann'=>'resource'],
'fann_get_cascade_activation_steepnesses_count' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_change_fraction' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_limit' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_stagnation_epochs' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_max_cand_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_max_out_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_min_cand_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_min_out_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_num_candidate_groups' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_num_candidates' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_output_change_fraction' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_output_stagnation_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_weight_multiplier' => ['float|false', 'ann'=>'resource'],
'fann_get_connection_array' => ['array', 'ann'=>'resource'],
'fann_get_connection_rate' => ['float|false', 'ann'=>'resource'],
'fann_get_errno' => ['int|false', 'errdat'=>'resource'],
'fann_get_errstr' => ['string|false', 'errdat'=>'resource'],
'fann_get_layer_array' => ['array', 'ann'=>'resource'],
'fann_get_learning_momentum' => ['float|false', 'ann'=>'resource'],
'fann_get_learning_rate' => ['float|false', 'ann'=>'resource'],
'fann_get_MSE' => ['float|false', 'ann'=>'resource'],
'fann_get_network_type' => ['int|false', 'ann'=>'resource'],
'fann_get_num_input' => ['int|false', 'ann'=>'resource'],
'fann_get_num_layers' => ['int|false', 'ann'=>'resource'],
'fann_get_num_output' => ['int|false', 'ann'=>'resource'],
'fann_get_quickprop_decay' => ['float|false', 'ann'=>'resource'],
'fann_get_quickprop_mu' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_decrease_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_max' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_min' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_zero' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_increase_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_step_error_shift' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_step_error_threshold_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_temperature' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_weight_decay_shift' => ['float|false', 'ann'=>'resource'],
'fann_get_total_connections' => ['int|false', 'ann'=>'resource'],
'fann_get_total_neurons' => ['int|false', 'ann'=>'resource'],
'fann_get_train_error_function' => ['int|false', 'ann'=>'resource'],
'fann_get_train_stop_function' => ['int|false', 'ann'=>'resource'],
'fann_get_training_algorithm' => ['int|false', 'ann'=>'resource'],
'fann_init_weights' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_length_train_data' => ['int|false', 'data'=>'resource'],
'fann_merge_train_data' => ['resource|false', 'data1'=>'resource', 'data2'=>'resource'],
'fann_num_input_train_data' => ['int|false', 'data'=>'resource'],
'fann_num_output_train_data' => ['int|false', 'data'=>'resource'],
'fann_print_error' => ['void', 'errdat'=>'string'],
'fann_randomize_weights' => ['bool', 'ann'=>'resource', 'min_weight'=>'float', 'max_weight'=>'float'],
'fann_read_train_from_file' => ['resource', 'filename'=>'string'],
'fann_reset_errno' => ['void', 'errdat'=>'resource'],
'fann_reset_errstr' => ['void', 'errdat'=>'resource'],
'fann_reset_MSE' => ['bool', 'ann'=>'string'],
'fann_run' => ['array|false', 'ann'=>'resource', 'input'=>'array'],
'fann_save' => ['bool', 'ann'=>'resource', 'configuration_file'=>'string'],
'fann_save_train' => ['bool', 'data'=>'resource', 'file_name'=>'string'],
'fann_scale_input' => ['bool', 'ann'=>'resource', 'input_vector'=>'array'],
'fann_scale_input_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_scale_output' => ['bool', 'ann'=>'resource', 'output_vector'=>'array'],
'fann_scale_output_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_scale_train' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_scale_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_set_activation_function' => ['bool', 'ann'=>'resource', 'activation_function'=>'int', 'layer'=>'int', 'neuron'=>'int'],
'fann_set_activation_function_hidden' => ['bool', 'ann'=>'resource', 'activation_function'=>'int'],
'fann_set_activation_function_layer' => ['bool', 'ann'=>'resource', 'activation_function'=>'int', 'layer'=>'int'],
'fann_set_activation_function_output' => ['bool', 'ann'=>'resource', 'activation_function'=>'int'],
'fann_set_activation_steepness' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float', 'layer'=>'int', 'neuron'=>'int'],
'fann_set_activation_steepness_hidden' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float'],
'fann_set_activation_steepness_layer' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float', 'layer'=>'int'],
'fann_set_activation_steepness_output' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float'],
'fann_set_bit_fail_limit' => ['bool', 'ann'=>'resource', 'bit_fail_limit'=>'float'],
'fann_set_callback' => ['bool', 'ann'=>'resource', 'callback'=>'callable'],
'fann_set_cascade_activation_functions' => ['bool', 'ann'=>'resource', 'cascade_activation_functions'=>'array'],
'fann_set_cascade_activation_steepnesses' => ['bool', 'ann'=>'resource', 'cascade_activation_steepnesses_count'=>'array'],
'fann_set_cascade_candidate_change_fraction' => ['bool', 'ann'=>'resource', 'cascade_candidate_change_fraction'=>'float'],
'fann_set_cascade_candidate_limit' => ['bool', 'ann'=>'resource', 'cascade_candidate_limit'=>'float'],
'fann_set_cascade_candidate_stagnation_epochs' => ['bool', 'ann'=>'resource', 'cascade_candidate_stagnation_epochs'=>'int'],
'fann_set_cascade_max_cand_epochs' => ['bool', 'ann'=>'resource', 'cascade_max_cand_epochs'=>'int'],
'fann_set_cascade_max_out_epochs' => ['bool', 'ann'=>'resource', 'cascade_max_out_epochs'=>'int'],
'fann_set_cascade_min_cand_epochs' => ['bool', 'ann'=>'resource', 'cascade_min_cand_epochs'=>'int'],
'fann_set_cascade_min_out_epochs' => ['bool', 'ann'=>'resource', 'cascade_min_out_epochs'=>'int'],
'fann_set_cascade_num_candidate_groups' => ['bool', 'ann'=>'resource', 'cascade_num_candidate_groups'=>'int'],
'fann_set_cascade_output_change_fraction' => ['bool', 'ann'=>'resource', 'cascade_output_change_fraction'=>'float'],
'fann_set_cascade_output_stagnation_epochs' => ['bool', 'ann'=>'resource', 'cascade_output_stagnation_epochs'=>'int'],
'fann_set_cascade_weight_multiplier' => ['bool', 'ann'=>'resource', 'cascade_weight_multiplier'=>'float'],
'fann_set_error_log' => ['void', 'errdat'=>'resource', 'log_file'=>'string'],
'fann_set_input_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_input_min'=>'float', 'new_input_max'=>'float'],
'fann_set_learning_momentum' => ['bool', 'ann'=>'resource', 'learning_momentum'=>'float'],
'fann_set_learning_rate' => ['bool', 'ann'=>'resource', 'learning_rate'=>'float'],
'fann_set_output_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_output_min'=>'float', 'new_output_max'=>'float'],
'fann_set_quickprop_decay' => ['bool', 'ann'=>'resource', 'quickprop_decay'=>'float'],
'fann_set_quickprop_mu' => ['bool', 'ann'=>'resource', 'quickprop_mu'=>'float'],
'fann_set_rprop_decrease_factor' => ['bool', 'ann'=>'resource', 'rprop_decrease_factor'=>'float'],
'fann_set_rprop_delta_max' => ['bool', 'ann'=>'resource', 'rprop_delta_max'=>'float'],
'fann_set_rprop_delta_min' => ['bool', 'ann'=>'resource', 'rprop_delta_min'=>'float'],
'fann_set_rprop_delta_zero' => ['bool', 'ann'=>'resource', 'rprop_delta_zero'=>'float'],
'fann_set_rprop_increase_factor' => ['bool', 'ann'=>'resource', 'rprop_increase_factor'=>'float'],
'fann_set_sarprop_step_error_shift' => ['bool', 'ann'=>'resource', 'sarprop_step_error_shift'=>'float'],
'fann_set_sarprop_step_error_threshold_factor' => ['bool', 'ann'=>'resource', 'sarprop_step_error_threshold_factor'=>'float'],
'fann_set_sarprop_temperature' => ['bool', 'ann'=>'resource', 'sarprop_temperature'=>'float'],
'fann_set_sarprop_weight_decay_shift' => ['bool', 'ann'=>'resource', 'sarprop_weight_decay_shift'=>'float'],
'fann_set_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_input_min'=>'float', 'new_input_max'=>'float', 'new_output_min'=>'float', 'new_output_max'=>'float'],
'fann_set_train_error_function' => ['bool', 'ann'=>'resource', 'error_function'=>'int'],
'fann_set_train_stop_function' => ['bool', 'ann'=>'resource', 'stop_function'=>'int'],
'fann_set_training_algorithm' => ['bool', 'ann'=>'resource', 'training_algorithm'=>'int'],
'fann_set_weight' => ['bool', 'ann'=>'resource', 'from_neuron'=>'int', 'to_neuron'=>'int', 'weight'=>'float'],
'fann_set_weight_array' => ['bool', 'ann'=>'resource', 'connections'=>'array'],
'fann_shuffle_train_data' => ['bool', 'train_data'=>'resource'],
'fann_subset_train_data' => ['resource', 'data'=>'resource', 'pos'=>'int', 'length'=>'int'],
'fann_test' => ['bool', 'ann'=>'resource', 'input'=>'array', 'desired_output'=>'array'],
'fann_test_data' => ['float|false', 'ann'=>'resource', 'data'=>'resource'],
'fann_train' => ['bool', 'ann'=>'resource', 'input'=>'array', 'desired_output'=>'array'],
'fann_train_epoch' => ['float|false', 'ann'=>'resource', 'data'=>'resource'],
'fann_train_on_data' => ['bool', 'ann'=>'resource', 'data'=>'resource', 'max_epochs'=>'int', 'epochs_between_reports'=>'int', 'desired_error'=>'float'],
'fann_train_on_file' => ['bool', 'ann'=>'resource', 'filename'=>'string', 'max_epochs'=>'int', 'epochs_between_reports'=>'int', 'desired_error'=>'float'],
'FANNConnection::__construct' => ['void', 'from_neuron'=>'int', 'to_neuron'=>'int', 'weight'=>'float'],
'FANNConnection::getFromNeuron' => ['int'],
'FANNConnection::getToNeuron' => ['int'],
'FANNConnection::getWeight' => ['void'],
'FANNConnection::setWeight' => ['bool', 'weight'=>'float'],
'fastcgi_finish_request' => ['bool'],
'fbsql_affected_rows' => ['int', 'link_identifier='=>'?resource'],
'fbsql_autocommit' => ['bool', 'link_identifier'=>'resource', 'onoff='=>'bool'],
'fbsql_blob_size' => ['int', 'blob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_change_user' => ['bool', 'user'=>'string', 'password'=>'string', 'database='=>'string', 'link_identifier='=>'?resource'],
'fbsql_clob_size' => ['int', 'clob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_close' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_commit' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_connect' => ['resource', 'hostname='=>'string', 'username='=>'string', 'password='=>'string'],
'fbsql_create_blob' => ['string', 'blob_data'=>'string', 'link_identifier='=>'?resource'],
'fbsql_create_clob' => ['string', 'clob_data'=>'string', 'link_identifier='=>'?resource'],
'fbsql_create_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource', 'database_options='=>'string'],
'fbsql_data_seek' => ['bool', 'result'=>'resource', 'row_number'=>'int'],
'fbsql_database' => ['string', 'link_identifier'=>'resource', 'database='=>'string'],
'fbsql_database_password' => ['string', 'link_identifier'=>'resource', 'database_password='=>'string'],
'fbsql_db_query' => ['resource', 'database'=>'string', 'query'=>'string', 'link_identifier='=>'?resource'],
'fbsql_db_status' => ['int', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_drop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_errno' => ['int', 'link_identifier='=>'?resource'],
'fbsql_error' => ['string', 'link_identifier='=>'?resource'],
'fbsql_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'fbsql_fetch_assoc' => ['array', 'result'=>'resource'],
'fbsql_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_fetch_lengths' => ['array', 'result'=>'resource'],
'fbsql_fetch_object' => ['object', 'result'=>'resource'],
'fbsql_fetch_row' => ['array', 'result'=>'resource'],
'fbsql_field_flags' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_len' => ['int', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_name' => ['string', 'result'=>'resource', 'field_index='=>'int'],
'fbsql_field_seek' => ['bool', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_table' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_type' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_free_result' => ['bool', 'result'=>'resource'],
'fbsql_get_autostart_info' => ['array', 'link_identifier='=>'?resource'],
'fbsql_hostname' => ['string', 'link_identifier'=>'resource', 'host_name='=>'string'],
'fbsql_insert_id' => ['int', 'link_identifier='=>'?resource'],
'fbsql_list_dbs' => ['resource', 'link_identifier='=>'?resource'],
'fbsql_list_fields' => ['resource', 'database_name'=>'string', 'table_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_list_tables' => ['resource', 'database'=>'string', 'link_identifier='=>'?resource'],
'fbsql_next_result' => ['bool', 'result'=>'resource'],
'fbsql_num_fields' => ['int', 'result'=>'resource'],
'fbsql_num_rows' => ['int', 'result'=>'resource'],
'fbsql_password' => ['string', 'link_identifier'=>'resource', 'password='=>'string'],
'fbsql_pconnect' => ['resource', 'hostname='=>'string', 'username='=>'string', 'password='=>'string'],
'fbsql_query' => ['resource', 'query'=>'string', 'link_identifier='=>'?resource', 'batch_size='=>'int'],
'fbsql_read_blob' => ['string', 'blob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_read_clob' => ['string', 'clob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_result' => ['mixed', 'result'=>'resource', 'row='=>'int', 'field='=>'mixed'],
'fbsql_rollback' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_rows_fetched' => ['int', 'result'=>'resource'],
'fbsql_select_db' => ['bool', 'database_name='=>'string', 'link_identifier='=>'?resource'],
'fbsql_set_characterset' => ['void', 'link_identifier'=>'resource', 'characterset'=>'int', 'in_out_both='=>'int'],
'fbsql_set_lob_mode' => ['bool', 'result'=>'resource', 'lob_mode'=>'int'],
'fbsql_set_password' => ['bool', 'link_identifier'=>'resource', 'user'=>'string', 'password'=>'string', 'old_password'=>'string'],
'fbsql_set_transaction' => ['void', 'link_identifier'=>'resource', 'locking'=>'int', 'isolation'=>'int'],
'fbsql_start_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource', 'database_options='=>'string'],
'fbsql_stop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_table_name' => ['string', 'result'=>'resource', 'index'=>'int'],
'fbsql_username' => ['string', 'link_identifier'=>'resource', 'username='=>'string'],
'fbsql_warnings' => ['bool', 'onoff='=>'bool'],
'fclose' => ['bool', 'stream'=>'resource'],
'fdf_add_doc_javascript' => ['bool', 'fdf_document'=>'resource', 'script_name'=>'string', 'script_code'=>'string'],
'fdf_add_template' => ['bool', 'fdf_document'=>'resource', 'newpage'=>'int', 'filename'=>'string', 'template'=>'string', 'rename'=>'int'],
'fdf_close' => ['void', 'fdf_document'=>'resource'],
'fdf_create' => ['resource'],
'fdf_enum_values' => ['bool', 'fdf_document'=>'resource', 'function'=>'callable', 'userdata='=>'mixed'],
'fdf_errno' => ['int'],
'fdf_error' => ['string', 'error_code='=>'int'],
'fdf_get_ap' => ['bool', 'fdf_document'=>'resource', 'field'=>'string', 'face'=>'int', 'filename'=>'string'],
'fdf_get_attachment' => ['array', 'fdf_document'=>'resource', 'fieldname'=>'string', 'savepath'=>'string'],
'fdf_get_encoding' => ['string', 'fdf_document'=>'resource'],
'fdf_get_file' => ['string', 'fdf_document'=>'resource'],
'fdf_get_flags' => ['int', 'fdf_document'=>'resource', 'fieldname'=>'string', 'whichflags'=>'int'],
'fdf_get_opt' => ['mixed', 'fdf_document'=>'resource', 'fieldname'=>'string', 'element='=>'int'],
'fdf_get_status' => ['string', 'fdf_document'=>'resource'],
'fdf_get_value' => ['mixed', 'fdf_document'=>'resource', 'fieldname'=>'string', 'which='=>'int'],
'fdf_get_version' => ['string', 'fdf_document='=>'resource'],
'fdf_header' => ['void'],
'fdf_next_field_name' => ['string', 'fdf_document'=>'resource', 'fieldname='=>'string'],
'fdf_open' => ['resource|false', 'filename'=>'string'],
'fdf_open_string' => ['resource', 'fdf_data'=>'string'],
'fdf_remove_item' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'item'=>'int'],
'fdf_save' => ['bool', 'fdf_document'=>'resource', 'filename='=>'string'],
'fdf_save_string' => ['string', 'fdf_document'=>'resource'],
'fdf_set_ap' => ['bool', 'fdf_document'=>'resource', 'field_name'=>'string', 'face'=>'int', 'filename'=>'string', 'page_number'=>'int'],
'fdf_set_encoding' => ['bool', 'fdf_document'=>'resource', 'encoding'=>'string'],
'fdf_set_file' => ['bool', 'fdf_document'=>'resource', 'url'=>'string', 'target_frame='=>'string'],
'fdf_set_flags' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'whichflags'=>'int', 'newflags'=>'int'],
'fdf_set_javascript_action' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'trigger'=>'int', 'script'=>'string'],
'fdf_set_on_import_javascript' => ['bool', 'fdf_document'=>'resource', 'script'=>'string', 'before_data_import'=>'bool'],
'fdf_set_opt' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'element'=>'int', 'string1'=>'string', 'string2'=>'string'],
'fdf_set_status' => ['bool', 'fdf_document'=>'resource', 'status'=>'string'],
'fdf_set_submit_form_action' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'trigger'=>'int', 'script'=>'string', 'flags'=>'int'],
'fdf_set_target_frame' => ['bool', 'fdf_document'=>'resource', 'frame_name'=>'string'],
'fdf_set_value' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'value'=>'mixed', 'isname='=>'int'],
'fdf_set_version' => ['bool', 'fdf_document'=>'resource', 'version'=>'string'],
'feof' => ['bool', 'stream'=>'resource'],
'fflush' => ['bool', 'stream'=>'resource'],
'ffmpeg_animated_gif::__construct' => ['void', 'output_file_path'=>'string', 'width'=>'int', 'height'=>'int', 'frame_rate'=>'int', 'loop_count='=>'int'],
'ffmpeg_animated_gif::addFrame' => ['', 'frame_to_add'=>'ffmpeg_frame'],
'ffmpeg_frame::__construct' => ['void', 'gd_image'=>'resource'],
'ffmpeg_frame::crop' => ['', 'crop_top'=>'int', 'crop_bottom='=>'int', 'crop_left='=>'int', 'crop_right='=>'int'],
'ffmpeg_frame::getHeight' => ['int'],
'ffmpeg_frame::getPresentationTimestamp' => ['int'],
'ffmpeg_frame::getPTS' => ['int'],
'ffmpeg_frame::getWidth' => ['int'],
'ffmpeg_frame::resize' => ['', 'width'=>'int', 'height'=>'int', 'crop_top='=>'int', 'crop_bottom='=>'int', 'crop_left='=>'int', 'crop_right='=>'int'],
'ffmpeg_frame::toGDImage' => ['resource'],
'ffmpeg_movie::__construct' => ['void', 'path_to_media'=>'string', 'persistent'=>'bool'],
'ffmpeg_movie::getArtist' => ['string'],
'ffmpeg_movie::getAudioBitRate' => ['int'],
'ffmpeg_movie::getAudioChannels' => ['int'],
'ffmpeg_movie::getAudioCodec' => ['string'],
'ffmpeg_movie::getAudioSampleRate' => ['int'],
'ffmpeg_movie::getAuthor' => ['string'],
'ffmpeg_movie::getBitRate' => ['int'],
'ffmpeg_movie::getComment' => ['string'],
'ffmpeg_movie::getCopyright' => ['string'],
'ffmpeg_movie::getDuration' => ['int'],
'ffmpeg_movie::getFilename' => ['string'],
'ffmpeg_movie::getFrame' => ['ffmpeg_frame|false', 'framenumber'=>'int'],
'ffmpeg_movie::getFrameCount' => ['int'],
'ffmpeg_movie::getFrameHeight' => ['int'],
'ffmpeg_movie::getFrameNumber' => ['int'],
'ffmpeg_movie::getFrameRate' => ['int'],
'ffmpeg_movie::getFrameWidth' => ['int'],
'ffmpeg_movie::getGenre' => ['string'],
'ffmpeg_movie::getNextKeyFrame' => ['ffmpeg_frame|false'],
'ffmpeg_movie::getPixelFormat' => [''],
'ffmpeg_movie::getTitle' => ['string'],
'ffmpeg_movie::getTrackNumber' => ['int|string'],
'ffmpeg_movie::getVideoBitRate' => ['int'],
'ffmpeg_movie::getVideoCodec' => ['string'],
'ffmpeg_movie::getYear' => ['int|string'],
'ffmpeg_movie::hasAudio' => ['bool'],
'ffmpeg_movie::hasVideo' => ['bool'],
'fgetc' => ['string|false', 'stream'=>'resource'],
'fgetcsv' => ['list<string>|array{0: null}|false|null', 'stream'=>'resource', 'length='=>'int', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'fgets' => ['string|false', 'stream'=>'resource', 'length='=>'int'],
'fgetss' => ['string|false', 'fp'=>'resource', 'length='=>'int', 'allowable_tags='=>'string'],
'file' => ['list<string>|false', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'file_exists' => ['bool', 'filename'=>'string'],
'file_get_contents' => ['string|false', 'filename'=>'string', 'use_include_path='=>'bool', 'context='=>'?resource', 'offset='=>'int', 'length='=>'int'],
'file_put_contents' => ['int|false', 'filename'=>'string', 'data'=>'mixed', 'flags='=>'int', 'context='=>'resource'],
'fileatime' => ['int|false', 'filename'=>'string'],
'filectime' => ['int|false', 'filename'=>'string'],
'filegroup' => ['int|false', 'filename'=>'string'],
'fileinode' => ['int|false', 'filename'=>'string'],
'filemtime' => ['int|false', 'filename'=>'string'],
'fileowner' => ['int|false', 'filename'=>'string'],
'fileperms' => ['int|false', 'filename'=>'string'],
'filepro' => ['bool', 'directory'=>'string'],
'filepro_fieldcount' => ['int'],
'filepro_fieldname' => ['string', 'field_number'=>'int'],
'filepro_fieldtype' => ['string', 'field_number'=>'int'],
'filepro_fieldwidth' => ['int', 'field_number'=>'int'],
'filepro_retrieve' => ['string', 'row_number'=>'int', 'field_number'=>'int'],
'filepro_rowcount' => ['int'],
'filesize' => ['int|false', 'filename'=>'string'],
'FilesystemIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'FilesystemIterator::__toString' => ['string'],
'FilesystemIterator::_bad_state_ex' => [''],
'FilesystemIterator::current' => ['mixed'],
'FilesystemIterator::getATime' => ['int'],
'FilesystemIterator::getBasename' => ['string', 'suffix='=>'string'],
'FilesystemIterator::getCTime' => ['int'],
'FilesystemIterator::getExtension' => ['string'],
'FilesystemIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'FilesystemIterator::getFilename' => ['string'],
'FilesystemIterator::getFlags' => ['int'],
'FilesystemIterator::getGroup' => ['int'],
'FilesystemIterator::getInode' => ['int'],
'FilesystemIterator::getLinkTarget' => ['string'],
'FilesystemIterator::getMTime' => ['int'],
'FilesystemIterator::getOwner' => ['int'],
'FilesystemIterator::getPath' => ['string'],
'FilesystemIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'FilesystemIterator::getPathname' => ['string'],
'FilesystemIterator::getPerms' => ['int'],
'FilesystemIterator::getRealPath' => ['string'],
'FilesystemIterator::getSize' => ['int'],
'FilesystemIterator::getType' => ['string'],
'FilesystemIterator::isDir' => ['bool'],
'FilesystemIterator::isDot' => ['bool'],
'FilesystemIterator::isExecutable' => ['bool'],
'FilesystemIterator::isFile' => ['bool'],
'FilesystemIterator::isLink' => ['bool'],
'FilesystemIterator::isReadable' => ['bool'],
'FilesystemIterator::isWritable' => ['bool'],
'FilesystemIterator::key' => ['string'],
'FilesystemIterator::next' => ['void'],
'FilesystemIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'FilesystemIterator::rewind' => ['void'],
'FilesystemIterator::seek' => ['void', 'position'=>'int'],
'FilesystemIterator::setFileClass' => ['void', 'class_name='=>'string'],
'FilesystemIterator::setFlags' => ['void', 'flags='=>'int'],
'FilesystemIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'FilesystemIterator::valid' => ['bool'],
'filetype' => ['string|false', 'filename'=>'string'],
'filter_has_var' => ['bool', 'input_type'=>'int', 'var_name'=>'string'],
'filter_id' => ['int|false', 'name'=>'string'],
'filter_input' => ['mixed|false', 'type'=>'int', 'var_name'=>'string', 'filter='=>'int', 'options='=>'array|int'],
'filter_input_array' => ['mixed|false', 'type'=>'int', 'options='=>'int|array', 'add_empty='=>'bool'],
'filter_list' => ['array'],
'filter_var' => ['mixed|false', 'value'=>'mixed', 'filter='=>'int', 'options='=>'mixed'],
'filter_var_array' => ['mixed|false', 'array'=>'array', 'options='=>'mixed', 'add_empty='=>'bool'],
'FilterIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'FilterIterator::accept' => ['bool'],
'FilterIterator::current' => ['mixed'],
'FilterIterator::getInnerIterator' => ['Iterator'],
'FilterIterator::key' => ['mixed'],
'FilterIterator::next' => ['void'],
'FilterIterator::rewind' => ['void'],
'FilterIterator::valid' => ['bool'],
'finfo::__construct' => ['void', 'options='=>'int', 'magic_file='=>'string'],
'finfo::buffer' => ['string|false', 'string'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo::file' => ['string|false', 'file_name'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo::finfo' => ['void', 'options='=>'int', 'magic_file='=>'string'],
'finfo::set_flags' => ['bool', 'options'=>'int'],
'finfo_buffer' => ['string|false', 'finfo'=>'resource', 'string'=>'string', 'flags='=>'int', 'context='=>'resource'],
'finfo_close' => ['bool', 'finfo'=>'resource'],
'finfo_file' => ['string|false', 'finfo'=>'resource', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'finfo_open' => ['resource|false', 'flags='=>'int', 'magic_database='=>'string'],
'finfo_set_flags' => ['bool', 'finfo'=>'resource', 'flags'=>'int'],
'floatval' => ['float', 'value'=>'mixed'],
'flock' => ['bool', 'stream'=>'resource', 'operation'=>'int', '&w_would_block='=>'int'],
'floor' => ['float', 'num'=>'float'],
'flush' => ['void'],
'fmod' => ['float', 'num1'=>'float', 'num2'=>'float'],
'fnmatch' => ['bool', 'pattern'=>'string', 'filename'=>'string', 'flags='=>'int'],
'fopen' => ['resource|false', 'filename'=>'string', 'mode'=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'forward_static_call' => ['mixed|false', 'callback'=>'callable', '...args='=>'mixed'],
'forward_static_call_array' => ['mixed|false', 'callback'=>'callable', 'args'=>'list<mixed>'],
'fpassthru' => ['int|false', 'stream'=>'resource'],
'fpm_get_status' => ['array|false'],
'fprintf' => ['int', 'stream'=>'resource', 'format'=>'string', '...values='=>'string|int|float'],
'fputcsv' => ['int|false', 'stream'=>'resource', 'fields'=>'array', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'fputs' => ['int|false', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'fread' => ['string|false', 'stream'=>'resource', 'length'=>'int'],
'frenchtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'fribidi_log2vis' => ['string', 'string'=>'string', 'direction'=>'string', 'charset'=>'int'],
'fscanf' => ['list<mixed>', 'stream'=>'resource', 'format'=>'string'],
'fscanf\'1' => ['int', 'stream'=>'resource', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'fseek' => ['int', 'stream'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'fsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float'],
'fstat' => ['array|false', 'stream'=>'resource'],
'ftell' => ['int|false', 'stream'=>'resource'],
'ftok' => ['int', 'filename'=>'string', 'project_id'=>'string'],
'ftp_alloc' => ['bool', 'ftp'=>'resource', 'size'=>'int', '&w_response='=>'string'],
'ftp_append' => ['bool', 'ftp'=>'resource', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int'],
'ftp_cdup' => ['bool', 'ftp'=>'resource'],
'ftp_chdir' => ['bool', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_chmod' => ['int|false', 'ftp'=>'resource', 'permissions'=>'int', 'filename'=>'string'],
'ftp_close' => ['bool', 'ftp'=>'resource'],
'ftp_connect' => ['resource|false', 'hostname'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_delete' => ['bool', 'ftp'=>'resource', 'filename'=>'string'],
'ftp_exec' => ['bool', 'ftp'=>'resource', 'command'=>'string'],
'ftp_fget' => ['bool', 'ftp'=>'resource', 'stream'=>'resource', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_fput' => ['bool', 'ftp'=>'resource', 'remote_filename'=>'string', 'stream'=>'resource', 'mode='=>'int', 'offset='=>'int'],
'ftp_get' => ['bool', 'ftp'=>'resource', 'local_filename'=>'string', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_get_option' => ['mixed|false', 'ftp'=>'resource', 'option'=>'int'],
'ftp_login' => ['bool', 'ftp'=>'resource', 'username'=>'string', 'password'=>'string'],
'ftp_mdtm' => ['int', 'ftp'=>'resource', 'filename'=>'string'],
'ftp_mkdir' => ['string|false', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_mlsd' => ['array|false', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_nb_continue' => ['int', 'ftp'=>'resource'],
'ftp_nb_fget' => ['int', 'ftp'=>'resource', 'stream'=>'resource', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_fput' => ['int', 'ftp'=>'resource', 'remote_filename'=>'string', 'stream'=>'resource', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_get' => ['int', 'ftp'=>'resource', 'local_filename'=>'string', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_put' => ['int', 'ftp'=>'resource', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nlist' => ['array|false', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_pasv' => ['bool', 'ftp'=>'resource', 'enable'=>'bool'],
'ftp_put' => ['bool', 'ftp'=>'resource', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_pwd' => ['string|false', 'ftp'=>'resource'],
'ftp_quit' => ['bool', 'ftp'=>'resource'],
'ftp_raw' => ['array', 'ftp'=>'resource', 'command'=>'string'],
'ftp_rawlist' => ['array|false', 'ftp'=>'resource', 'directory'=>'string', 'recursive='=>'bool'],
'ftp_rename' => ['bool', 'ftp'=>'resource', 'from'=>'string', 'to'=>'string'],
'ftp_rmdir' => ['bool', 'ftp'=>'resource', 'directory'=>'string'],
'ftp_set_option' => ['bool', 'ftp'=>'resource', 'option'=>'int', 'value'=>'mixed'],
'ftp_site' => ['bool', 'ftp'=>'resource', 'command'=>'string'],
'ftp_size' => ['int', 'ftp'=>'resource', 'filename'=>'string'],
'ftp_ssl_connect' => ['resource|false', 'hostname'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_systype' => ['string|false', 'ftp'=>'resource'],
'ftruncate' => ['bool', 'stream'=>'resource', 'size'=>'int'],
'func_get_arg' => ['mixed|false', 'position'=>'int'],
'func_get_args' => ['list<mixed>'],
'func_num_args' => ['int'],
'function_exists' => ['bool', 'function'=>'string'],
'fwrite' => ['int|false', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'gc_collect_cycles' => ['int'],
'gc_disable' => ['void'],
'gc_enable' => ['void'],
'gc_enabled' => ['bool'],
'gc_mem_caches' => ['int'],
'gc_status' => ['array{runs:int,collected:int,threshold:int,roots:int}'],
'gd_info' => ['array'],
'gearman_bugreport' => [''],
'gearman_client_add_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_add_server' => ['', 'client_object'=>'', 'host'=>'', 'port'=>''],
'gearman_client_add_servers' => ['', 'client_object'=>'', 'servers'=>''],
'gearman_client_add_task' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_high' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_high_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_low' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_low_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_status' => ['', 'client_object'=>'', 'job_handle'=>'', 'context'=>''],
'gearman_client_clear_fn' => ['', 'client_object'=>''],
'gearman_client_clone' => ['', 'client_object'=>''],
'gearman_client_context' => ['', 'client_object'=>''],
'gearman_client_create' => ['', 'client_object'=>''],
'gearman_client_do' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_high' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_high_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_job_handle' => ['', 'client_object'=>''],
'gearman_client_do_low' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_low_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_normal' => ['', 'client_object'=>'', 'function_name'=>'string', 'workload'=>'string', 'unique'=>'string'],
'gearman_client_do_status' => ['', 'client_object'=>''],
'gearman_client_echo' => ['', 'client_object'=>'', 'workload'=>''],
'gearman_client_errno' => ['', 'client_object'=>''],
'gearman_client_error' => ['', 'client_object'=>''],
'gearman_client_job_status' => ['', 'client_object'=>'', 'job_handle'=>''],
'gearman_client_options' => ['', 'client_object'=>''],
'gearman_client_remove_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_return_code' => ['', 'client_object'=>''],
'gearman_client_run_tasks' => ['', 'data'=>''],
'gearman_client_set_complete_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_context' => ['', 'client_object'=>'', 'context'=>''],
'gearman_client_set_created_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_data_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_exception_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_fail_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_set_status_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_timeout' => ['', 'client_object'=>'', 'timeout'=>''],
'gearman_client_set_warning_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_workload_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_timeout' => ['', 'client_object'=>''],
'gearman_client_wait' => ['', 'client_object'=>''],
'gearman_job_function_name' => ['', 'job_object'=>''],
'gearman_job_handle' => ['string'],
'gearman_job_return_code' => ['', 'job_object'=>''],
'gearman_job_send_complete' => ['', 'job_object'=>'', 'result'=>''],
'gearman_job_send_data' => ['', 'job_object'=>'', 'data'=>''],
'gearman_job_send_exception' => ['', 'job_object'=>'', 'exception'=>''],
'gearman_job_send_fail' => ['', 'job_object'=>''],
'gearman_job_send_status' => ['', 'job_object'=>'', 'numerator'=>'', 'denominator'=>''],
'gearman_job_send_warning' => ['', 'job_object'=>'', 'warning'=>''],
'gearman_job_status' => ['array', 'job_handle'=>'string'],
'gearman_job_unique' => ['', 'job_object'=>''],
'gearman_job_workload' => ['', 'job_object'=>''],
'gearman_job_workload_size' => ['', 'job_object'=>''],
'gearman_task_data' => ['', 'task_object'=>''],
'gearman_task_data_size' => ['', 'task_object'=>''],
'gearman_task_denominator' => ['', 'task_object'=>''],
'gearman_task_function_name' => ['', 'task_object'=>''],
'gearman_task_is_known' => ['', 'task_object'=>''],
'gearman_task_is_running' => ['', 'task_object'=>''],
'gearman_task_job_handle' => ['', 'task_object'=>''],
'gearman_task_numerator' => ['', 'task_object'=>''],
'gearman_task_recv_data' => ['', 'task_object'=>'', 'data_len'=>''],
'gearman_task_return_code' => ['', 'task_object'=>''],
'gearman_task_send_workload' => ['', 'task_object'=>'', 'data'=>''],
'gearman_task_unique' => ['', 'task_object'=>''],
'gearman_verbose_name' => ['', 'verbose'=>''],
'gearman_version' => [''],
'gearman_worker_add_function' => ['', 'worker_object'=>'', 'function_name'=>'', 'function'=>'', 'data'=>'', 'timeout'=>''],
'gearman_worker_add_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_add_server' => ['', 'worker_object'=>'', 'host'=>'', 'port'=>''],
'gearman_worker_add_servers' => ['', 'worker_object'=>'', 'servers'=>''],
'gearman_worker_clone' => ['', 'worker_object'=>''],
'gearman_worker_create' => [''],
'gearman_worker_echo' => ['', 'worker_object'=>'', 'workload'=>''],
'gearman_worker_errno' => ['', 'worker_object'=>''],
'gearman_worker_error' => ['', 'worker_object'=>''],
'gearman_worker_grab_job' => ['', 'worker_object'=>''],
'gearman_worker_options' => ['', 'worker_object'=>''],
'gearman_worker_register' => ['', 'worker_object'=>'', 'function_name'=>'', 'timeout'=>''],
'gearman_worker_remove_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_return_code' => ['', 'worker_object'=>''],
'gearman_worker_set_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_set_timeout' => ['', 'worker_object'=>'', 'timeout'=>''],
'gearman_worker_timeout' => ['', 'worker_object'=>''],
'gearman_worker_unregister' => ['', 'worker_object'=>'', 'function_name'=>''],
'gearman_worker_unregister_all' => ['', 'worker_object'=>''],
'gearman_worker_wait' => ['', 'worker_object'=>''],
'gearman_worker_work' => ['', 'worker_object'=>''],
'GearmanClient::__construct' => ['void'],
'GearmanClient::addOptions' => ['bool', 'options'=>'int'],
'GearmanClient::addServer' => ['bool', 'host='=>'string', 'port='=>'int'],
'GearmanClient::addServers' => ['bool', 'servers='=>'string'],
'GearmanClient::addTask' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskHigh' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskHighBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskLow' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskLowBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskStatus' => ['GearmanTask', 'job_handle'=>'string', 'context='=>'string'],
'GearmanClient::clearCallbacks' => ['bool'],
'GearmanClient::clone' => ['GearmanClient'],
'GearmanClient::context' => ['string'],
'GearmanClient::data' => ['string'],
'GearmanClient::do' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doHigh' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doHighBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doJobHandle' => ['string'],
'GearmanClient::doLow' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doLowBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doNormal' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doStatus' => ['array'],
'GearmanClient::echo' => ['bool', 'workload'=>'string'],
'GearmanClient::error' => ['string'],
'GearmanClient::getErrno' => ['int'],
'GearmanClient::jobStatus' => ['array', 'job_handle'=>'string'],
'GearmanClient::options' => [''],
'GearmanClient::ping' => ['bool', 'workload'=>'string'],
'GearmanClient::removeOptions' => ['bool', 'options'=>'int'],
'GearmanClient::returnCode' => ['int'],
'GearmanClient::runTasks' => ['bool'],
'GearmanClient::setClientCallback' => ['void', 'callback'=>'callable'],
'GearmanClient::setCompleteCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setContext' => ['bool', 'context'=>'string'],
'GearmanClient::setCreatedCallback' => ['bool', 'callback'=>'string'],
'GearmanClient::setData' => ['bool', 'data'=>'string'],
'GearmanClient::setDataCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setExceptionCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setFailCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setOptions' => ['bool', 'options'=>'int'],
'GearmanClient::setStatusCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setTimeout' => ['bool', 'timeout'=>'int'],
'GearmanClient::setWarningCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setWorkloadCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::timeout' => ['int'],
'GearmanClient::wait' => [''],
'GearmanJob::__construct' => ['void'],
'GearmanJob::complete' => ['bool', 'result'=>'string'],
'GearmanJob::data' => ['bool', 'data'=>'string'],
'GearmanJob::exception' => ['bool', 'exception'=>'string'],
'GearmanJob::fail' => ['bool'],
'GearmanJob::functionName' => ['string'],
'GearmanJob::handle' => ['string'],
'GearmanJob::returnCode' => ['int'],
'GearmanJob::sendComplete' => ['bool', 'result'=>'string'],
'GearmanJob::sendData' => ['bool', 'data'=>'string'],
'GearmanJob::sendException' => ['bool', 'exception'=>'string'],
'GearmanJob::sendFail' => ['bool'],
'GearmanJob::sendStatus' => ['bool', 'numerator'=>'int', 'denominator'=>'int'],
'GearmanJob::sendWarning' => ['bool', 'warning'=>'string'],
'GearmanJob::setReturn' => ['bool', 'gearman_return_t'=>'string'],
'GearmanJob::status' => ['bool', 'numerator'=>'int', 'denominator'=>'int'],
'GearmanJob::unique' => ['string'],
'GearmanJob::warning' => ['bool', 'warning'=>'string'],
'GearmanJob::workload' => ['string'],
'GearmanJob::workloadSize' => ['int'],
'GearmanTask::__construct' => ['void'],
'GearmanTask::create' => ['GearmanTask'],
'GearmanTask::data' => ['string|false'],
'GearmanTask::dataSize' => ['int|false'],
'GearmanTask::function' => ['string'],
'GearmanTask::functionName' => ['string'],
'GearmanTask::isKnown' => ['bool'],
'GearmanTask::isRunning' => ['bool'],
'GearmanTask::jobHandle' => ['string'],
'GearmanTask::recvData' => ['array|false', 'data_len'=>'int'],
'GearmanTask::returnCode' => ['int'],
'GearmanTask::sendData' => ['int', 'data'=>'string'],
'GearmanTask::sendWorkload' => ['int|false', 'data'=>'string'],
'GearmanTask::taskDenominator' => ['int|false'],
'GearmanTask::taskNumerator' => ['int|false'],
'GearmanTask::unique' => ['string|false'],
'GearmanTask::uuid' => ['string'],
'GearmanWorker::__construct' => ['void'],
'GearmanWorker::addFunction' => ['bool', 'function_name'=>'string', 'function'=>'callable', 'context='=>'mixed', 'timeout='=>'int'],
'GearmanWorker::addOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::addServer' => ['bool', 'host='=>'string', 'port='=>'int'],
'GearmanWorker::addServers' => ['bool', 'servers'=>'string'],
'GearmanWorker::clone' => ['void'],
'GearmanWorker::echo' => ['bool', 'workload'=>'string'],
'GearmanWorker::error' => ['string'],
'GearmanWorker::getErrno' => ['int'],
'GearmanWorker::grabJob' => [''],
'GearmanWorker::options' => ['int'],
'GearmanWorker::register' => ['bool', 'function_name'=>'string', 'timeout='=>'int'],
'GearmanWorker::removeOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::returnCode' => ['int'],
'GearmanWorker::setId' => ['bool', 'id'=>'string'],
'GearmanWorker::setOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::setTimeout' => ['bool', 'timeout'=>'int'],
'GearmanWorker::timeout' => ['int'],
'GearmanWorker::unregister' => ['bool', 'function_name'=>'string'],
'GearmanWorker::unregisterAll' => ['bool'],
'GearmanWorker::wait' => ['bool'],
'GearmanWorker::work' => ['bool'],
'Gender\Gender::__construct' => ['void', 'dsn='=>'string'],
'Gender\Gender::connect' => ['bool', 'dsn'=>'string'],
'Gender\Gender::country' => ['array', 'country'=>'int'],
'Gender\Gender::get' => ['int', 'name'=>'string', 'country='=>'int'],
'Gender\Gender::isNick' => ['array', 'name0'=>'string', 'name1'=>'string', 'country='=>'int'],
'Gender\Gender::similarNames' => ['array', 'name'=>'string', 'country='=>'int'],
'Generator::__wakeup' => ['void'],
'Generator::current' => ['mixed'],
'Generator::getReturn' => ['mixed'],
'Generator::key' => ['mixed'],
'Generator::next' => ['void'],
'Generator::rewind' => ['void'],
'Generator::send' => ['mixed', 'value'=>'mixed'],
'Generator::throw' => ['mixed', 'exception'=>'Exception|Throwable'],
'Generator::valid' => ['bool'],
'geoip_asnum_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_continent_code_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_code3_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_code_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_name_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_database_info' => ['string', 'database='=>'int'],
'geoip_db_avail' => ['bool', 'database'=>'int'],
'geoip_db_filename' => ['string', 'database'=>'int'],
'geoip_db_get_all_info' => ['array'],
'geoip_domain_by_name' => ['string', 'hostname'=>'string'],
'geoip_id_by_name' => ['int', 'hostname'=>'string'],
'geoip_isp_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_netspeedcell_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_org_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_record_by_name' => ['array|false', 'hostname'=>'string'],
'geoip_region_by_name' => ['array|false', 'hostname'=>'string'],
'geoip_region_name_by_code' => ['string|false', 'country_code'=>'string', 'region_code'=>'string'],
'geoip_setup_custom_directory' => ['void', 'path'=>'string'],
'geoip_time_zone_by_country_and_region' => ['string|false', 'country_code'=>'string', 'region_code='=>'string'],
'GEOSGeometry::__toString' => ['string'],
'GEOSGeometry::project' => ['float', 'other'=>'GEOSGeometry', 'normalized'=>'bool'],
'GEOSGeometry::interpolate' => ['GEOSGeometry', 'dist'=>'float', 'normalized'=>'bool'],
'GEOSGeometry::buffer' => ['GEOSGeometry', 'dist'=>'float', 'styleArray'=>'array'],
'GEOSGeometry::offsetCurve' => ['GEOSGeometry', 'dist'=>'float', 'styleArray'=>'array'],
'GEOSGeometry::envelope' => ['GEOSGeometry'],
'GEOSGeometry::intersection' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::convexHull' => ['GEOSGeometry'],
'GEOSGeometry::difference' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::symDifference' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::boundary' => ['GEOSGeometry'],
'GEOSGeometry::union' => ['GEOSGeometry', 'otherGeom='=>'GEOSGeometry'],
'GEOSGeometry::pointOnSurface' => ['GEOSGeometry'],
'GEOSGeometry::centroid' => ['GEOSGeometry'],
'GEOSGeometry::relate' => ['string|bool', 'otherGeom'=>'GEOSGeometry', 'pattern'=>'string'],
'GEOSGeometry::relateBoundaryNodeRule' => ['string', 'otherGeom'=>'GEOSGeometry', 'rule'=>'int'],
'GEOSGeometry::simplify' => ['GEOSGeometry', 'tolerance'=>'float', 'preserveTopology'=>'bool'],
'GEOSGeometry::normalize' => ['GEOSGeometry'],
'GEOSGeometry::extractUniquePoints' => ['GEOSGeometry'],
'GEOSGeometry::disjoint' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::touches' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::intersects' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::crosses' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::within' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::contains' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::overlaps' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::covers' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::coveredBy' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::equals' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::equalsExact' => ['bool', 'geom'=>'GEOSGeometry', 'tolerance'=>'float'],
'GEOSGeometry::isEmpty' => ['bool'],
'GEOSGeometry::checkValidity' => ['array{valid: bool, reason?: string, location?: GEOSGeometry}'],
'GEOSGeometry::isSimple' => ['bool'],
'GEOSGeometry::isRing' => ['bool'],
'GEOSGeometry::hasZ' => ['bool'],
'GEOSGeometry::isClosed' => ['bool'],
'GEOSGeometry::typeName' => ['string'],
'GEOSGeometry::typeId' => ['int'],
'GEOSGeometry::getSRID' => ['int'],
'GEOSGeometry::setSRID' => ['void', 'srid'=>'int'],
'GEOSGeometry::numGeometries' => ['int'],
'GEOSGeometry::geometryN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::numInteriorRings' => ['int'],
'GEOSGeometry::numPoints' => ['int'],
'GEOSGeometry::getX' => ['float'],
'GEOSGeometry::getY' => ['float'],
'GEOSGeometry::interiorRingN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::exteriorRing' => ['GEOSGeometry'],
'GEOSGeometry::numCoordinates' => ['int'],
'GEOSGeometry::dimension' => ['int'],
'GEOSGeometry::coordinateDimension' => ['int'],
'GEOSGeometry::pointN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::startPoint' => ['GEOSGeometry'],
'GEOSGeometry::endPoint' => ['GEOSGeometry'],
'GEOSGeometry::area' => ['float'],
'GEOSGeometry::length' => ['float'],
'GEOSGeometry::distance' => ['float', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::hausdorffDistance' => ['float', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::snapTo' => ['GEOSGeometry', 'geom'=>'GEOSGeometry', 'tolerance'=>'float'],
'GEOSGeometry::node' => ['GEOSGeometry'],
'GEOSGeometry::delaunayTriangulation' => ['GEOSGeometry', 'tolerance'=>'float', 'onlyEdges'=>'bool'],
'GEOSGeometry::voronoiDiagram' => ['GEOSGeometry', 'tolerance'=>'float', 'onlyEdges'=>'bool', 'extent'=>'GEOSGeometry|null'],
'GEOSLineMerge' => ['array', 'geom'=>'GEOSGeometry'],
'GEOSPolygonize' => ['array{rings: GEOSGeometry[], cut_edges?: GEOSGeometry[], dangles: GEOSGeometry[], invalid_rings: GEOSGeometry[]}', 'geom'=>'GEOSGeometry'],
'GEOSRelateMatch' => ['bool', 'matrix'=>'string', 'pattern'=>'string'],
'GEOSSharedPaths' => ['GEOSGeometry', 'geom1'=>'GEOSGeometry', 'geom2'=>'GEOSGeometry'],
'GEOSVersion' => ['string'],
'GEOSWKBReader::__construct' => ['void'],
'GEOSWKBReader::read' => ['GEOSGeometry', 'wkb'=>'string'],
'GEOSWKBReader::readHEX' => ['GEOSGeometry', 'wkb'=>'string'],
'GEOSWKBWriter::__construct' => ['void'],
'GEOSWKBWriter::getOutputDimension' => ['int'],
'GEOSWKBWriter::setOutputDimension' => ['void', 'dim'=>'int'],
'GEOSWKBWriter::getByteOrder' => ['int'],
'GEOSWKBWriter::setByteOrder' => ['void', 'byteOrder'=>'int'],
'GEOSWKBWriter::getIncludeSRID' => ['bool'],
'GEOSWKBWriter::setIncludeSRID' => ['void', 'inc'=>'bool'],
'GEOSWKBWriter::write' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKBWriter::writeHEX' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKTReader::__construct' => ['void'],
'GEOSWKTReader::read' => ['GEOSGeometry', 'wkt'=>'string'],
'GEOSWKTWriter::__construct' => ['void'],
'GEOSWKTWriter::write' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKTWriter::setTrim' => ['void', 'trim'=>'bool'],
'GEOSWKTWriter::setRoundingPrecision' => ['void', 'prec'=>'int'],
'GEOSWKTWriter::setOutputDimension' => ['void', 'dim'=>'int'],
'GEOSWKTWriter::getOutputDimension' => ['int'],
'GEOSWKTWriter::setOld3D' => ['void', 'val'=>'bool'],
'get_browser' => ['array|object|false', 'user_agent='=>'string', 'return_array='=>'bool'],
'get_call_stack' => [''],
'get_called_class' => ['class-string'],
'get_cfg_var' => ['string|false', 'option'=>'string'],
'get_class' => ['class-string|false', 'object='=>'object'],
'get_class_methods' => ['list<string>|null', 'object_or_class'=>'mixed'],
'get_class_vars' => ['array<string,mixed>', 'class'=>'string'],
'get_current_user' => ['string'],
'get_debug_type' => ['string', 'value'=>'mixed'],
'get_declared_classes' => ['list<class-string>'],
'get_declared_interfaces' => ['list<class-string>'],
'get_declared_traits' => ['list<class-string>|null'],
'get_defined_constants' => ['array<string,int|string|float|bool|null|array|resource>', 'categorize='=>'bool'],
'get_defined_functions' => ['array<string,list<callable-string>>', 'exclude_disabled='=>'bool'],
'get_defined_vars' => ['array'],
'get_extension_funcs' => ['list<callable-string>|false', 'extension'=>'string'],
'get_headers' => ['array|false', 'url'=>'string', 'associative='=>'int', 'context='=>'resource'],
'get_html_translation_table' => ['array', 'table='=>'int', 'flags='=>'int', 'encoding='=>'string'],
'get_include_path' => ['string'],
'get_included_files' => ['list<string>'],
'get_loaded_extensions' => ['list<string>', 'zend_extensions='=>'bool'],
'get_magic_quotes_gpc' => ['int|false'],
'get_magic_quotes_runtime' => ['int|false'],
'get_meta_tags' => ['array', 'filename'=>'string', 'use_include_path='=>'bool'],
'get_object_vars' => ['array<string,mixed>', 'object'=>'object'],
'get_parent_class' => ['class-string|false', 'object_or_class='=>'mixed'],
'get_required_files' => ['list<string>'],
'get_resource_id' => ['int', 'resource'=>'resource'],
'get_resource_type' => ['string', 'resource'=>'resource'],
'get_resources' => ['array<int,resource>', 'type='=>'string'],
'getallheaders' => ['array|false'],
'getcwd' => ['string|false'],
'getdate' => ['array', 'timestamp='=>'int'],
'getenv' => ['string|false', 'name'=>'string', 'local_only='=>'bool'],
'getenv\'1' => ['array<string,string>'],
'gethostbyaddr' => ['string|false', 'ip'=>'string'],
'gethostbyname' => ['string', 'hostname'=>'string'],
'gethostbynamel' => ['list<string>|false', 'hostname'=>'string'],
'gethostname' => ['string|false'],
'getimagesize' => ['array|false', 'filename'=>'string', '&w_image_info='=>'array'],
'getimagesizefromstring' => ['array|false', 'string'=>'string', '&w_image_info='=>'array'],
'getlastmod' => ['int|false'],
'getmxrr' => ['bool', 'hostname'=>'string', '&w_hosts'=>'array', '&w_weights='=>'array'],
'getmygid' => ['int|false'],
'getmyinode' => ['int|false'],
'getmypid' => ['int|false'],
'getmyuid' => ['int|false'],
'getopt' => ['array<string,string>|array<string,false>|array<string,list<mixed>>|false', 'short_options'=>'string', 'long_options='=>'array', '&w_rest_index='=>'int'],
'getprotobyname' => ['int|false', 'protocol'=>'string'],
'getprotobynumber' => ['string', 'protocol'=>'int'],
'getrandmax' => ['int'],
'getrusage' => ['array', 'mode='=>'int'],
'getservbyname' => ['int|false', 'service'=>'string', 'protocol'=>'string'],
'getservbyport' => ['string|false', 'port'=>'int', 'protocol'=>'string'],
'gettext' => ['string', 'message'=>'string'],
'gettimeofday' => ['array<string, int>'],
'gettimeofday\'1' => ['float', 'as_float='=>'true'],
'gettype' => ['string', 'value'=>'mixed'],
'glob' => ['list<string>|false', 'pattern'=>'string', 'flags='=>'int'],
'GlobIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'GlobIterator::count' => ['int'],
'GlobIterator::current' => ['FilesystemIterator|SplFileInfo|string'],
'GlobIterator::getATime' => [''],
'GlobIterator::getBasename' => ['', 'suffix='=>'string'],
'GlobIterator::getCTime' => [''],
'GlobIterator::getExtension' => [''],
'GlobIterator::getFileInfo' => [''],
'GlobIterator::getFilename' => [''],
'GlobIterator::getFlags' => ['int'],
'GlobIterator::getGroup' => [''],
'GlobIterator::getInode' => [''],
'GlobIterator::getLinkTarget' => [''],
'GlobIterator::getMTime' => [''],
'GlobIterator::getOwner' => [''],
'GlobIterator::getPath' => [''],
'GlobIterator::getPathInfo' => [''],
'GlobIterator::getPathname' => [''],
'GlobIterator::getPerms' => [''],
'GlobIterator::getRealPath' => [''],
'GlobIterator::getSize' => [''],
'GlobIterator::getType' => [''],
'GlobIterator::isDir' => [''],
'GlobIterator::isDot' => [''],
'GlobIterator::isExecutable' => [''],
'GlobIterator::isFile' => [''],
'GlobIterator::isLink' => [''],
'GlobIterator::isReadable' => [''],
'GlobIterator::isWritable' => [''],
'GlobIterator::key' => ['string'],
'GlobIterator::next' => ['void'],
'GlobIterator::openFile' => [''],
'GlobIterator::rewind' => ['void'],
'GlobIterator::seek' => ['void', 'position'=>'int'],
'GlobIterator::setFileClass' => [''],
'GlobIterator::setFlags' => ['void', 'flags='=>'int'],
'GlobIterator::setInfoClass' => [''],
'GlobIterator::valid' => [''],
'Gmagick::__construct' => ['void', 'filename='=>'string'],
'Gmagick::addimage' => ['Gmagick', 'gmagick'=>'gmagick'],
'Gmagick::addnoiseimage' => ['Gmagick', 'noise'=>'int'],
'Gmagick::annotateimage' => ['Gmagick', 'gmagickdraw'=>'gmagickdraw', 'x'=>'float', 'y'=>'float', 'angle'=>'float', 'text'=>'string'],
'Gmagick::blurimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Gmagick::borderimage' => ['Gmagick', 'color'=>'gmagickpixel', 'width'=>'int', 'height'=>'int'],
'Gmagick::charcoalimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float'],
'Gmagick::chopimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::clear' => ['Gmagick'],
'Gmagick::commentimage' => ['Gmagick', 'comment'=>'string'],
'Gmagick::compositeimage' => ['Gmagick', 'source'=>'gmagick', 'compose'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::cropimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::cropthumbnailimage' => ['Gmagick', 'width'=>'int', 'height'=>'int'],
'Gmagick::current' => ['Gmagick'],
'Gmagick::cyclecolormapimage' => ['Gmagick', 'displace'=>'int'],
'Gmagick::deconstructimages' => ['Gmagick'],
'Gmagick::despeckleimage' => ['Gmagick'],
'Gmagick::destroy' => ['bool'],
'Gmagick::drawimage' => ['Gmagick', 'gmagickdraw'=>'gmagickdraw'],
'Gmagick::edgeimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::embossimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float'],
'Gmagick::enhanceimage' => ['Gmagick'],
'Gmagick::equalizeimage' => ['Gmagick'],
'Gmagick::flipimage' => ['Gmagick'],
'Gmagick::flopimage' => ['Gmagick'],
'Gmagick::frameimage' => ['Gmagick', 'color'=>'gmagickpixel', 'width'=>'int', 'height'=>'int', 'inner_bevel'=>'int', 'outer_bevel'=>'int'],
'Gmagick::gammaimage' => ['Gmagick', 'gamma'=>'float'],
'Gmagick::getcopyright' => ['string'],
'Gmagick::getfilename' => ['string'],
'Gmagick::getimagebackgroundcolor' => ['GmagickPixel'],
'Gmagick::getimageblueprimary' => ['array'],
'Gmagick::getimagebordercolor' => ['GmagickPixel'],
'Gmagick::getimagechanneldepth' => ['int', 'channel_type'=>'int'],
'Gmagick::getimagecolors' => ['int'],
'Gmagick::getimagecolorspace' => ['int'],
'Gmagick::getimagecompose' => ['int'],
'Gmagick::getimagedelay' => ['int'],
'Gmagick::getimagedepth' => ['int'],
'Gmagick::getimagedispose' => ['int'],
'Gmagick::getimageextrema' => ['array'],
'Gmagick::getimagefilename' => ['string'],
'Gmagick::getimageformat' => ['string'],
'Gmagick::getimagegamma' => ['float'],
'Gmagick::getimagegreenprimary' => ['array'],
'Gmagick::getimageheight' => ['int'],
'Gmagick::getimagehistogram' => ['array'],
'Gmagick::getimageindex' => ['int'],
'Gmagick::getimageinterlacescheme' => ['int'],
'Gmagick::getimageiterations' => ['int'],
'Gmagick::getimagematte' => ['int'],
'Gmagick::getimagemattecolor' => ['GmagickPixel'],
'Gmagick::getimageprofile' => ['string', 'name'=>'string'],
'Gmagick::getimageredprimary' => ['array'],
'Gmagick::getimagerenderingintent' => ['int'],
'Gmagick::getimageresolution' => ['array'],
'Gmagick::getimagescene' => ['int'],
'Gmagick::getimagesignature' => ['string'],
'Gmagick::getimagetype' => ['int'],
'Gmagick::getimageunits' => ['int'],
'Gmagick::getimagewhitepoint' => ['array'],
'Gmagick::getimagewidth' => ['int'],
'Gmagick::getpackagename' => ['string'],
'Gmagick::getquantumdepth' => ['array'],
'Gmagick::getreleasedate' => ['string'],
'Gmagick::getsamplingfactors' => ['array'],
'Gmagick::getsize' => ['array'],
'Gmagick::getversion' => ['array'],
'Gmagick::hasnextimage' => ['bool'],
'Gmagick::haspreviousimage' => ['bool'],
'Gmagick::implodeimage' => ['mixed', 'radius'=>'float'],
'Gmagick::labelimage' => ['mixed', 'label'=>'string'],
'Gmagick::levelimage' => ['mixed', 'blackpoint'=>'float', 'gamma'=>'float', 'whitepoint'=>'float', 'channel='=>'int'],
'Gmagick::magnifyimage' => ['mixed'],
'Gmagick::mapimage' => ['Gmagick', 'gmagick'=>'gmagick', 'dither'=>'bool'],
'Gmagick::medianfilterimage' => ['void', 'radius'=>'float'],
'Gmagick::minifyimage' => ['Gmagick'],
'Gmagick::modulateimage' => ['Gmagick', 'brightness'=>'float', 'saturation'=>'float', 'hue'=>'float'],
'Gmagick::motionblurimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float'],
'Gmagick::newimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'background'=>'string', 'format='=>'string'],
'Gmagick::nextimage' => ['bool'],
'Gmagick::normalizeimage' => ['Gmagick', 'channel='=>'int'],
'Gmagick::oilpaintimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::previousimage' => ['bool'],
'Gmagick::profileimage' => ['Gmagick', 'name'=>'string', 'profile'=>'string'],
'Gmagick::quantizeimage' => ['Gmagick', 'numcolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Gmagick::quantizeimages' => ['Gmagick', 'numcolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Gmagick::queryfontmetrics' => ['array', 'draw'=>'gmagickdraw', 'text'=>'string'],
'Gmagick::queryfonts' => ['array', 'pattern='=>'string'],
'Gmagick::queryformats' => ['array', 'pattern='=>'string'],
'Gmagick::radialblurimage' => ['Gmagick', 'angle'=>'float', 'channel='=>'int'],
'Gmagick::raiseimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int', 'raise'=>'bool'],
'Gmagick::read' => ['Gmagick', 'filename'=>'string'],
'Gmagick::readimage' => ['Gmagick', 'filename'=>'string'],
'Gmagick::readimageblob' => ['Gmagick', 'imagecontents'=>'string', 'filename='=>'string'],
'Gmagick::readimagefile' => ['Gmagick', 'fp'=>'resource', 'filename='=>'string'],
'Gmagick::reducenoiseimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::removeimage' => ['Gmagick'],
'Gmagick::removeimageprofile' => ['string', 'name'=>'string'],
'Gmagick::resampleimage' => ['Gmagick', 'xresolution'=>'float', 'yresolution'=>'float', 'filter'=>'int', 'blur'=>'float'],
'Gmagick::resizeimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'filter'=>'int', 'blur'=>'float', 'fit='=>'bool'],
'Gmagick::rollimage' => ['Gmagick', 'x'=>'int', 'y'=>'int'],
'Gmagick::rotateimage' => ['Gmagick', 'color'=>'mixed', 'degrees'=>'float'],
'Gmagick::scaleimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'fit='=>'bool'],
'Gmagick::separateimagechannel' => ['Gmagick', 'channel'=>'int'],
'Gmagick::setCompressionQuality' => ['Gmagick', 'quality'=>'int'],
'Gmagick::setfilename' => ['Gmagick', 'filename'=>'string'],
'Gmagick::setimagebackgroundcolor' => ['Gmagick', 'color'=>'gmagickpixel'],
'Gmagick::setimageblueprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimagebordercolor' => ['Gmagick', 'color'=>'gmagickpixel'],
'Gmagick::setimagechanneldepth' => ['Gmagick', 'channel'=>'int', 'depth'=>'int'],
'Gmagick::setimagecolorspace' => ['Gmagick', 'colorspace'=>'int'],
'Gmagick::setimagecompose' => ['Gmagick', 'composite'=>'int'],
'Gmagick::setimagedelay' => ['Gmagick', 'delay'=>'int'],
'Gmagick::setimagedepth' => ['Gmagick', 'depth'=>'int'],
'Gmagick::setimagedispose' => ['Gmagick', 'disposetype'=>'int'],
'Gmagick::setimagefilename' => ['Gmagick', 'filename'=>'string'],
'Gmagick::setimageformat' => ['Gmagick', 'imageformat'=>'string'],
'Gmagick::setimagegamma' => ['Gmagick', 'gamma'=>'float'],
'Gmagick::setimagegreenprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimageindex' => ['Gmagick', 'index'=>'int'],
'Gmagick::setimageinterlacescheme' => ['Gmagick', 'interlace'=>'int'],
'Gmagick::setimageiterations' => ['Gmagick', 'iterations'=>'int'],
'Gmagick::setimageprofile' => ['Gmagick', 'name'=>'string', 'profile'=>'string'],
'Gmagick::setimageredprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimagerenderingintent' => ['Gmagick', 'rendering_intent'=>'int'],
'Gmagick::setimageresolution' => ['Gmagick', 'xresolution'=>'float', 'yresolution'=>'float'],
'Gmagick::setimagescene' => ['Gmagick', 'scene'=>'int'],
'Gmagick::setimagetype' => ['Gmagick', 'imgtype'=>'int'],
'Gmagick::setimageunits' => ['Gmagick', 'resolution'=>'int'],
'Gmagick::setimagewhitepoint' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setsamplingfactors' => ['Gmagick', 'factors'=>'array'],
'Gmagick::setsize' => ['Gmagick', 'columns'=>'int', 'rows'=>'int'],
'Gmagick::shearimage' => ['Gmagick', 'color'=>'mixed', 'xshear'=>'float', 'yshear'=>'float'],
'Gmagick::solarizeimage' => ['Gmagick', 'threshold'=>'int'],
'Gmagick::spreadimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::stripimage' => ['Gmagick'],
'Gmagick::swirlimage' => ['Gmagick', 'degrees'=>'float'],
'Gmagick::thumbnailimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'fit='=>'bool'],
'Gmagick::trimimage' => ['Gmagick', 'fuzz'=>'float'],
'Gmagick::write' => ['Gmagick', 'filename'=>'string'],
'Gmagick::writeimage' => ['Gmagick', 'filename'=>'string', 'all_frames='=>'bool'],
'GmagickDraw::annotate' => ['GmagickDraw', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'GmagickDraw::arc' => ['GmagickDraw', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float', 'sd'=>'float', 'ed'=>'float'],
'GmagickDraw::bezier' => ['GmagickDraw', 'coordinate_array'=>'array'],
'GmagickDraw::ellipse' => ['GmagickDraw', 'ox'=>'float', 'oy'=>'float', 'rx'=>'float', 'ry'=>'float', 'start'=>'float', 'end'=>'float'],
'GmagickDraw::getfillcolor' => ['GmagickPixel'],
'GmagickDraw::getfillopacity' => ['float'],
'GmagickDraw::getfont' => ['string|false'],
'GmagickDraw::getfontsize' => ['float'],
'GmagickDraw::getfontstyle' => ['int'],
'GmagickDraw::getfontweight' => ['int'],
'GmagickDraw::getstrokecolor' => ['GmagickPixel'],
'GmagickDraw::getstrokeopacity' => ['float'],
'GmagickDraw::getstrokewidth' => ['float'],
'GmagickDraw::gettextdecoration' => ['int'],
'GmagickDraw::gettextencoding' => ['string|false'],
'GmagickDraw::line' => ['GmagickDraw', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float'],
'GmagickDraw::point' => ['GmagickDraw', 'x'=>'float', 'y'=>'float'],
'GmagickDraw::polygon' => ['GmagickDraw', 'coordinates'=>'array'],
'GmagickDraw::polyline' => ['GmagickDraw', 'coordinate_array'=>'array'],
'GmagickDraw::rectangle' => ['GmagickDraw', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'GmagickDraw::rotate' => ['GmagickDraw', 'degrees'=>'float'],
'GmagickDraw::roundrectangle' => ['GmagickDraw', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'rx'=>'float', 'ry'=>'float'],
'GmagickDraw::scale' => ['GmagickDraw', 'x'=>'float', 'y'=>'float'],
'GmagickDraw::setfillcolor' => ['GmagickDraw', 'color'=>'string'],
'GmagickDraw::setfillopacity' => ['GmagickDraw', 'fill_opacity'=>'float'],
'GmagickDraw::setfont' => ['GmagickDraw', 'font'=>'string'],
'GmagickDraw::setfontsize' => ['GmagickDraw', 'pointsize'=>'float'],
'GmagickDraw::setfontstyle' => ['GmagickDraw', 'style'=>'int'],
'GmagickDraw::setfontweight' => ['GmagickDraw', 'weight'=>'int'],
'GmagickDraw::setstrokecolor' => ['GmagickDraw', 'color'=>'gmagickpixel'],
'GmagickDraw::setstrokeopacity' => ['GmagickDraw', 'stroke_opacity'=>'float'],
'GmagickDraw::setstrokewidth' => ['GmagickDraw', 'width'=>'float'],
'GmagickDraw::settextdecoration' => ['GmagickDraw', 'decoration'=>'int'],
'GmagickDraw::settextencoding' => ['GmagickDraw', 'encoding'=>'string'],
'GmagickPixel::__construct' => ['void', 'color='=>'string'],
'GmagickPixel::getcolor' => ['mixed', 'as_array='=>'bool', 'normalize_array='=>'bool'],
'GmagickPixel::getcolorcount' => ['int'],
'GmagickPixel::getcolorvalue' => ['float', 'color'=>'int'],
'GmagickPixel::setcolor' => ['GmagickPixel', 'color'=>'string'],
'GmagickPixel::setcolorvalue' => ['GmagickPixel', 'color'=>'int', 'value'=>'float'],
'gmdate' => ['string|false', 'format'=>'string', 'timestamp='=>'int'],
'gmmktime' => ['int|false', 'hour='=>'int', 'minute='=>'int', 'second='=>'int', 'month='=>'int', 'day='=>'int', 'year='=>'int'],
'GMP::__construct' => ['void'],
'GMP::__toString' => ['numeric-string'],
'GMP::serialize' => ['string'],
'GMP::unserialize' => ['void', 'serialized'=>'string'],
'gmp_abs' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_add' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_and' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_binomial' => ['GMP|false', 'n'=>'GMP|string|int', 'k'=>'int'],
'gmp_clrbit' => ['void', 'num'=>'GMP|string|int', 'index'=>'int'],
'gmp_cmp' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_com' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_div' => ['GMP', 'num1'=>'GMP|resource|string', 'num2'=>'GMP|resource|string', 'rounding_mode='=>'int'],
'gmp_div_q' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_div_qr' => ['array{0: GMP, 1: GMP}', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_div_r' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_divexact' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_export' => ['string|false', 'num'=>'GMP|string|int', 'word_size='=>'int', 'flags='=>'int'],
'gmp_fact' => ['GMP', 'num'=>'int'],
'gmp_gcd' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_gcdext' => ['array<string,GMP>', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_hamdist' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_import' => ['GMP|false', 'data'=>'string', 'word_size='=>'int', 'flags='=>'int'],
'gmp_init' => ['GMP', 'num'=>'int|string', 'base='=>'int'],
'gmp_intval' => ['int', 'num'=>'GMP|string|int'],
'gmp_invert' => ['GMP|false', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_jacobi' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_kronecker' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_lcm' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_legendre' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_mod' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_mul' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_neg' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_nextprime' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_or' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_perfect_power' => ['bool', 'num'=>'GMP|string|int'],
'gmp_perfect_square' => ['bool', 'num'=>'GMP|string|int'],
'gmp_popcount' => ['int', 'num'=>'GMP|string|int'],
'gmp_pow' => ['GMP', 'num'=>'GMP|string|int', 'exponent'=>'int'],
'gmp_powm' => ['GMP', 'num'=>'GMP|string|int', 'exponent'=>'GMP|string|int', 'modulus'=>'GMP|string|int'],
'gmp_prob_prime' => ['int', 'num'=>'GMP|string|int', 'repetitions='=>'int'],
'gmp_random' => ['GMP', 'limiter='=>'int'],
'gmp_random_bits' => ['GMP', 'bits'=>'int'],
'gmp_random_range' => ['GMP', 'min'=>'GMP|string|int', 'max'=>'GMP|string|int'],
'gmp_random_seed' => ['void', 'seed'=>'GMP|string|int'],
'gmp_root' => ['GMP', 'num'=>'GMP|string|int', 'nth'=>'int'],
'gmp_rootrem' => ['array{0: GMP, 1: GMP}', 'num'=>'GMP|string|int', 'nth'=>'int'],
'gmp_scan0' => ['int', 'num1'=>'GMP|string|int', 'start'=>'int'],
'gmp_scan1' => ['int', 'num1'=>'GMP|string|int', 'start'=>'int'],
'gmp_setbit' => ['void', 'num'=>'GMP|string|int', 'index'=>'int', 'value='=>'bool'],
'gmp_sign' => ['int', 'num'=>'GMP|string|int'],
'gmp_sqrt' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_sqrtrem' => ['array{0: GMP, 1: GMP}', 'num'=>'GMP|string|int'],
'gmp_strval' => ['numeric-string', 'num'=>'GMP|string|int', 'base='=>'int'],
'gmp_sub' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_testbit' => ['bool', 'num'=>'GMP|string|int', 'index'=>'int'],
'gmp_xor' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmstrftime' => ['string', 'format'=>'string', 'timestamp='=>'int'],
'gnupg::adddecryptkey' => ['bool', 'fingerprint'=>'string', 'passphrase'=>'string'],
'gnupg::addencryptkey' => ['bool', 'fingerprint'=>'string'],
'gnupg::addsignkey' => ['bool', 'fingerprint'=>'string', 'passphrase='=>'string'],
'gnupg::cleardecryptkeys' => ['bool'],
'gnupg::clearencryptkeys' => ['bool'],
'gnupg::clearsignkeys' => ['bool'],
'gnupg::decrypt' => ['string|false', 'text'=>'string'],
'gnupg::decryptverify' => ['array|false', 'text'=>'string', '&plaintext'=>'string'],
'gnupg::encrypt' => ['string|false', 'plaintext'=>'string'],
'gnupg::encryptsign' => ['string|false', 'plaintext'=>'string'],
'gnupg::export' => ['string|false', 'fingerprint'=>'string'],
'gnupg::geterror' => ['string|false'],
'gnupg::getprotocol' => ['int'],
'gnupg::import' => ['array|false', 'keydata'=>'string'],
'gnupg::init' => ['resource'],
'gnupg::keyinfo' => ['array', 'pattern'=>'string'],
'gnupg::setarmor' => ['bool', 'armor'=>'int'],
'gnupg::seterrormode' => ['void', 'errormode'=>'int'],
'gnupg::setsignmode' => ['bool', 'signmode'=>'int'],
'gnupg::sign' => ['string|false', 'plaintext'=>'string'],
'gnupg::verify' => ['array|false', 'signed_text'=>'string', 'signature'=>'string', '&plaintext='=>'string'],
'gnupg_adddecryptkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string', 'passphrase'=>'string'],
'gnupg_addencryptkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string'],
'gnupg_addsignkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string', 'passphrase='=>'string'],
'gnupg_cleardecryptkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_clearencryptkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_clearsignkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_decrypt' => ['string', 'identifier'=>'resource', 'text'=>'string'],
'gnupg_decryptverify' => ['array', 'identifier'=>'resource', 'text'=>'string', 'plaintext'=>'string'],
'gnupg_encrypt' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_encryptsign' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_export' => ['string', 'identifier'=>'resource', 'fingerprint'=>'string'],
'gnupg_geterror' => ['string', 'identifier'=>'resource'],
'gnupg_getprotocol' => ['int', 'identifier'=>'resource'],
'gnupg_import' => ['array', 'identifier'=>'resource', 'keydata'=>'string'],
'gnupg_init' => ['resource'],
'gnupg_keyinfo' => ['array', 'identifier'=>'resource', 'pattern'=>'string'],
'gnupg_setarmor' => ['bool', 'identifier'=>'resource', 'armor'=>'int'],
'gnupg_seterrormode' => ['void', 'identifier'=>'resource', 'errormode'=>'int'],
'gnupg_setsignmode' => ['bool', 'identifier'=>'resource', 'signmode'=>'int'],
'gnupg_sign' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_verify' => ['array', 'identifier'=>'resource', 'signed_text'=>'string', 'signature'=>'string', 'plaintext='=>'string'],
'gopher_parsedir' => ['array', 'dirent'=>'string'],
'grapheme_extract' => ['string|false', 'haystack'=>'string', 'size'=>'int', 'type='=>'int', 'offset='=>'int', '&w_next='=>'int'],
'grapheme_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'beforeNeedle='=>'bool'],
'grapheme_strlen' => ['int|false|null', 'string'=>'string'],
'grapheme_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'beforeNeedle='=>'bool'],
'grapheme_substr' => ['string|false', 'string'=>'string', 'offset'=>'int', 'length='=>'int'],
'gregoriantojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'gridObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'Grpc\Call::__construct' => ['void', 'channel'=>'Grpc\Channel', 'method'=>'string', 'absolute_deadline'=>'Grpc\Timeval', 'host_override='=>'mixed'],
'Grpc\Call::cancel' => [''],
'Grpc\Call::getPeer' => ['string'],
'Grpc\Call::setCredentials' => ['int', 'creds_obj'=>'Grpc\CallCredentials'],
'Grpc\Call::startBatch' => ['object', 'batch'=>'array'],
'Grpc\CallCredentials::createComposite' => ['Grpc\CallCredentials', 'cred1'=>'Grpc\CallCredentials', 'cred2'=>'Grpc\CallCredentials'],
'Grpc\CallCredentials::createFromPlugin' => ['Grpc\CallCredentials', 'callback'=>'Closure'],
'Grpc\Channel::__construct' => ['void', 'target'=>'string', 'args='=>'array'],
'Grpc\Channel::close' => [''],
'Grpc\Channel::getConnectivityState' => ['int', 'try_to_connect='=>'bool'],
'Grpc\Channel::getTarget' => ['string'],
'Grpc\Channel::watchConnectivityState' => ['bool', 'last_state'=>'int', 'deadline_obj'=>'Grpc\Timeval'],
'Grpc\ChannelCredentials::createComposite' => ['Grpc\ChannelCredentials', 'cred1'=>'Grpc\ChannelCredentials', 'cred2'=>'Grpc\CallCredentials'],
'Grpc\ChannelCredentials::createDefault' => ['Grpc\ChannelCredentials'],
'Grpc\ChannelCredentials::createInsecure' => ['null'],
'Grpc\ChannelCredentials::createSsl' => ['Grpc\ChannelCredentials', 'pem_root_certs'=>'string', 'pem_private_key='=>'string', 'pem_cert_chain='=>'string'],
'Grpc\ChannelCredentials::setDefaultRootsPem' => ['', 'pem_roots'=>'string'],
'Grpc\Server::__construct' => ['void', 'args'=>'array'],
'Grpc\Server::addHttp2Port' => ['bool', 'addr'=>'string'],
'Grpc\Server::addSecureHttp2Port' => ['bool', 'addr'=>'string', 'creds_obj'=>'Grpc\ServerCredentials'],
'Grpc\Server::requestCall' => ['', 'tag_new'=>'int', 'tag_cancel'=>'int'],
'Grpc\Server::start' => [''],
'Grpc\ServerCredentials::createSsl' => ['object', 'pem_root_certs'=>'string', 'pem_private_key'=>'string', 'pem_cert_chain'=>'string'],
'Grpc\Timeval::__construct' => ['void', 'usec'=>'int'],
'Grpc\Timeval::add' => ['Grpc\Timeval', 'other'=>'Grpc\Timeval'],
'Grpc\Timeval::compare' => ['int', 'a'=>'Grpc\Timeval', 'b'=>'Grpc\Timeval'],
'Grpc\Timeval::infFuture' => ['Grpc\Timeval'],
'Grpc\Timeval::infPast' => ['Grpc\Timeval'],
'Grpc\Timeval::now' => ['Grpc\Timeval'],
'Grpc\Timeval::similar' => ['bool', 'a'=>'Grpc\Timeval', 'b'=>'Grpc\Timeval', 'threshold'=>'Grpc\Timeval'],
'Grpc\Timeval::sleepUntil' => [''],
'Grpc\Timeval::subtract' => ['Grpc\Timeval', 'other'=>'Grpc\Timeval'],
'Grpc\Timeval::zero' => ['Grpc\Timeval'],
'gupnp_context_get_host_ip' => ['string', 'context'=>'resource'],
'gupnp_context_get_port' => ['int', 'context'=>'resource'],
'gupnp_context_get_subscription_timeout' => ['int', 'context'=>'resource'],
'gupnp_context_host_path' => ['bool', 'context'=>'resource', 'local_path'=>'string', 'server_path'=>'string'],
'gupnp_context_new' => ['resource', 'host_ip='=>'string', 'port='=>'int'],
'gupnp_context_set_subscription_timeout' => ['void', 'context'=>'resource', 'timeout'=>'int'],
'gupnp_context_timeout_add' => ['bool', 'context'=>'resource', 'timeout'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_context_unhost_path' => ['bool', 'context'=>'resource', 'server_path'=>'string'],
'gupnp_control_point_browse_start' => ['bool', 'cpoint'=>'resource'],
'gupnp_control_point_browse_stop' => ['bool', 'cpoint'=>'resource'],
'gupnp_control_point_callback_set' => ['bool', 'cpoint'=>'resource', 'signal'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_control_point_new' => ['resource', 'context'=>'resource', 'target'=>'string'],
'gupnp_device_action_callback_set' => ['bool', 'root_device'=>'resource', 'signal'=>'int', 'action_name'=>'string', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_device_info_get' => ['array', 'root_device'=>'resource'],
'gupnp_device_info_get_service' => ['resource', 'root_device'=>'resource', 'type'=>'string'],
'gupnp_root_device_get_available' => ['bool', 'root_device'=>'resource'],
'gupnp_root_device_get_relative_location' => ['string', 'root_device'=>'resource'],
'gupnp_root_device_new' => ['resource', 'context'=>'resource', 'location'=>'string', 'description_dir'=>'string'],
'gupnp_root_device_set_available' => ['bool', 'root_device'=>'resource', 'available'=>'bool'],
'gupnp_root_device_start' => ['bool', 'root_device'=>'resource'],
'gupnp_root_device_stop' => ['bool', 'root_device'=>'resource'],
'gupnp_service_action_get' => ['mixed', 'action'=>'resource', 'name'=>'string', 'type'=>'int'],
'gupnp_service_action_return' => ['bool', 'action'=>'resource'],
'gupnp_service_action_return_error' => ['bool', 'action'=>'resource', 'error_code'=>'int', 'error_description='=>'string'],
'gupnp_service_action_set' => ['bool', 'action'=>'resource', 'name'=>'string', 'type'=>'int', 'value'=>'mixed'],
'gupnp_service_freeze_notify' => ['bool', 'service'=>'resource'],
'gupnp_service_info_get' => ['array', 'proxy'=>'resource'],
'gupnp_service_info_get_introspection' => ['mixed', 'proxy'=>'resource', 'callback='=>'mixed', 'arg='=>'mixed'],
'gupnp_service_introspection_get_state_variable' => ['array', 'introspection'=>'resource', 'variable_name'=>'string'],
'gupnp_service_notify' => ['bool', 'service'=>'resource', 'name'=>'string', 'type'=>'int', 'value'=>'mixed'],
'gupnp_service_proxy_action_get' => ['mixed', 'proxy'=>'resource', 'action'=>'string', 'name'=>'string', 'type'=>'int'],
'gupnp_service_proxy_action_set' => ['bool', 'proxy'=>'resource', 'action'=>'string', 'name'=>'string', 'value'=>'mixed', 'type'=>'int'],
'gupnp_service_proxy_add_notify' => ['bool', 'proxy'=>'resource', 'value'=>'string', 'type'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_service_proxy_callback_set' => ['bool', 'proxy'=>'resource', 'signal'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_service_proxy_get_subscribed' => ['bool', 'proxy'=>'resource'],
'gupnp_service_proxy_remove_notify' => ['bool', 'proxy'=>'resource', 'value'=>'string'],
'gupnp_service_proxy_send_action' => ['array', 'proxy'=>'resource', 'action'=>'string', 'in_params'=>'array', 'out_params'=>'array'],
'gupnp_service_proxy_set_subscribed' => ['bool', 'proxy'=>'resource', 'subscribed'=>'bool'],
'gupnp_service_thaw_notify' => ['bool', 'service'=>'resource'],
'gzclose' => ['bool', 'stream'=>'resource'],
'gzcompress' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzdecode' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzdeflate' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzencode' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzeof' => ['bool|int', 'stream'=>'resource'],
'gzfile' => ['list<string>', 'filename'=>'string', 'use_include_path='=>'int'],
'gzgetc' => ['string|false', 'stream'=>'resource'],
'gzgets' => ['string|false', 'stream'=>'resource', 'length='=>'int'],
'gzgetss' => ['string|false', 'zp'=>'resource', 'length'=>'int', 'allowable_tags='=>'string'],
'gzinflate' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzopen' => ['resource|false', 'filename'=>'string', 'mode'=>'string', 'use_include_path='=>'int'],
'gzpassthru' => ['int|false', 'stream'=>'resource'],
'gzputs' => ['int', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'gzread' => ['string|false', 'stream'=>'resource', 'length'=>'int'],
'gzrewind' => ['bool', 'stream'=>'resource'],
'gzseek' => ['int', 'stream'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'gztell' => ['int|false', 'stream'=>'resource'],
'gzuncompress' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzwrite' => ['int', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'HaruAnnotation::setBorderStyle' => ['bool', 'width'=>'float', 'dash_on'=>'int', 'dash_off'=>'int'],
'HaruAnnotation::setHighlightMode' => ['bool', 'mode'=>'int'],
'HaruAnnotation::setIcon' => ['bool', 'icon'=>'int'],
'HaruAnnotation::setOpened' => ['bool', 'opened'=>'bool'],
'HaruDestination::setFit' => ['bool'],
'HaruDestination::setFitB' => ['bool'],
'HaruDestination::setFitBH' => ['bool', 'top'=>'float'],
'HaruDestination::setFitBV' => ['bool', 'left'=>'float'],
'HaruDestination::setFitH' => ['bool', 'top'=>'float'],
'HaruDestination::setFitR' => ['bool', 'left'=>'float', 'bottom'=>'float', 'right'=>'float', 'top'=>'float'],
'HaruDestination::setFitV' => ['bool', 'left'=>'float'],
'HaruDestination::setXYZ' => ['bool', 'left'=>'float', 'top'=>'float', 'zoom'=>'float'],
'HaruDoc::__construct' => ['void'],
'HaruDoc::addPage' => ['object'],
'HaruDoc::addPageLabel' => ['bool', 'first_page'=>'int', 'style'=>'int', 'first_num'=>'int', 'prefix='=>'string'],
'HaruDoc::createOutline' => ['object', 'title'=>'string', 'parent_outline='=>'object', 'encoder='=>'object'],
'HaruDoc::getCurrentEncoder' => ['object'],
'HaruDoc::getCurrentPage' => ['object'],
'HaruDoc::getEncoder' => ['object', 'encoding'=>'string'],
'HaruDoc::getFont' => ['object', 'fontname'=>'string', 'encoding='=>'string'],
'HaruDoc::getInfoAttr' => ['string', 'type'=>'int'],
'HaruDoc::getPageLayout' => ['int'],
'HaruDoc::getPageMode' => ['int'],
'HaruDoc::getStreamSize' => ['int'],
'HaruDoc::insertPage' => ['object', 'page'=>'object'],
'HaruDoc::loadJPEG' => ['object', 'filename'=>'string'],
'HaruDoc::loadPNG' => ['object', 'filename'=>'string', 'deferred='=>'bool'],
'HaruDoc::loadRaw' => ['object', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'color_space'=>'int'],
'HaruDoc::loadTTC' => ['string', 'fontfile'=>'string', 'index'=>'int', 'embed='=>'bool'],
'HaruDoc::loadTTF' => ['string', 'fontfile'=>'string', 'embed='=>'bool'],
'HaruDoc::loadType1' => ['string', 'afmfile'=>'string', 'pfmfile='=>'string'],
'HaruDoc::output' => ['bool'],
'HaruDoc::readFromStream' => ['string', 'bytes'=>'int'],
'HaruDoc::resetError' => ['bool'],
'HaruDoc::resetStream' => ['bool'],
'HaruDoc::save' => ['bool', 'file'=>'string'],
'HaruDoc::saveToStream' => ['bool'],
'HaruDoc::setCompressionMode' => ['bool', 'mode'=>'int'],
'HaruDoc::setCurrentEncoder' => ['bool', 'encoding'=>'string'],
'HaruDoc::setEncryptionMode' => ['bool', 'mode'=>'int', 'key_len='=>'int'],
'HaruDoc::setInfoAttr' => ['bool', 'type'=>'int', 'info'=>'string'],
'HaruDoc::setInfoDateAttr' => ['bool', 'type'=>'int', 'year'=>'int', 'month'=>'int', 'day'=>'int', 'hour'=>'int', 'min'=>'int', 'sec'=>'int', 'ind'=>'string', 'off_hour'=>'int', 'off_min'=>'int'],
'HaruDoc::setOpenAction' => ['bool', 'destination'=>'object'],
'HaruDoc::setPageLayout' => ['bool', 'layout'=>'int'],
'HaruDoc::setPageMode' => ['bool', 'mode'=>'int'],
'HaruDoc::setPagesConfiguration' => ['bool', 'page_per_pages'=>'int'],
'HaruDoc::setPassword' => ['bool', 'owner_password'=>'string', 'user_password'=>'string'],
'HaruDoc::setPermission' => ['bool', 'permission'=>'int'],
'HaruDoc::useCNSEncodings' => ['bool'],
'HaruDoc::useCNSFonts' => ['bool'],
'HaruDoc::useCNTEncodings' => ['bool'],
'HaruDoc::useCNTFonts' => ['bool'],
'HaruDoc::useJPEncodings' => ['bool'],
'HaruDoc::useJPFonts' => ['bool'],
'HaruDoc::useKREncodings' => ['bool'],
'HaruDoc::useKRFonts' => ['bool'],
'HaruEncoder::getByteType' => ['int', 'text'=>'string', 'index'=>'int'],
'HaruEncoder::getType' => ['int'],
'HaruEncoder::getUnicode' => ['int', 'character'=>'int'],
'HaruEncoder::getWritingMode' => ['int'],
'HaruFont::getAscent' => ['int'],
'HaruFont::getCapHeight' => ['int'],
'HaruFont::getDescent' => ['int'],
'HaruFont::getEncodingName' => ['string'],
'HaruFont::getFontName' => ['string'],
'HaruFont::getTextWidth' => ['array', 'text'=>'string'],
'HaruFont::getUnicodeWidth' => ['int', 'character'=>'int'],
'HaruFont::getXHeight' => ['int'],
'HaruFont::measureText' => ['int', 'text'=>'string', 'width'=>'float', 'font_size'=>'float', 'char_space'=>'float', 'word_space'=>'float', 'word_wrap='=>'bool'],
'HaruImage::getBitsPerComponent' => ['int'],
'HaruImage::getColorSpace' => ['string'],
'HaruImage::getHeight' => ['int'],
'HaruImage::getSize' => ['array'],
'HaruImage::getWidth' => ['int'],
'HaruImage::setColorMask' => ['bool', 'rmin'=>'int', 'rmax'=>'int', 'gmin'=>'int', 'gmax'=>'int', 'bmin'=>'int', 'bmax'=>'int'],
'HaruImage::setMaskImage' => ['bool', 'mask_image'=>'object'],
'HaruOutline::setDestination' => ['bool', 'destination'=>'object'],
'HaruOutline::setOpened' => ['bool', 'opened'=>'bool'],
'HaruPage::arc' => ['bool', 'x'=>'float', 'y'=>'float', 'ray'=>'float', 'ang1'=>'float', 'ang2'=>'float'],
'HaruPage::beginText' => ['bool'],
'HaruPage::circle' => ['bool', 'x'=>'float', 'y'=>'float', 'ray'=>'float'],
'HaruPage::closePath' => ['bool'],
'HaruPage::concat' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'HaruPage::createDestination' => ['object'],
'HaruPage::createLinkAnnotation' => ['object', 'rectangle'=>'array', 'destination'=>'object'],
'HaruPage::createTextAnnotation' => ['object', 'rectangle'=>'array', 'text'=>'string', 'encoder='=>'object'],
'HaruPage::createURLAnnotation' => ['object', 'rectangle'=>'array', 'url'=>'string'],
'HaruPage::curveTo' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::curveTo2' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::curveTo3' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::drawImage' => ['bool', 'image'=>'object', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'HaruPage::ellipse' => ['bool', 'x'=>'float', 'y'=>'float', 'xray'=>'float', 'yray'=>'float'],
'HaruPage::endPath' => ['bool'],
'HaruPage::endText' => ['bool'],
'HaruPage::eofill' => ['bool'],
'HaruPage::eoFillStroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::fill' => ['bool'],
'HaruPage::fillStroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::getCharSpace' => ['float'],
'HaruPage::getCMYKFill' => ['array'],
'HaruPage::getCMYKStroke' => ['array'],
'HaruPage::getCurrentFont' => ['object'],
'HaruPage::getCurrentFontSize' => ['float'],
'HaruPage::getCurrentPos' => ['array'],
'HaruPage::getCurrentTextPos' => ['array'],
'HaruPage::getDash' => ['array'],
'HaruPage::getFillingColorSpace' => ['int'],
'HaruPage::getFlatness' => ['float'],
'HaruPage::getGMode' => ['int'],
'HaruPage::getGrayFill' => ['float'],
'HaruPage::getGrayStroke' => ['float'],
'HaruPage::getHeight' => ['float'],
'HaruPage::getHorizontalScaling' => ['float'],
'HaruPage::getLineCap' => ['int'],
'HaruPage::getLineJoin' => ['int'],
'HaruPage::getLineWidth' => ['float'],
'HaruPage::getMiterLimit' => ['float'],
'HaruPage::getRGBFill' => ['array'],
'HaruPage::getRGBStroke' => ['array'],
'HaruPage::getStrokingColorSpace' => ['int'],
'HaruPage::getTextLeading' => ['float'],
'HaruPage::getTextMatrix' => ['array'],
'HaruPage::getTextRenderingMode' => ['int'],
'HaruPage::getTextRise' => ['float'],
'HaruPage::getTextWidth' => ['float', 'text'=>'string'],
'HaruPage::getTransMatrix' => ['array'],
'HaruPage::getWidth' => ['float'],
'HaruPage::getWordSpace' => ['float'],
'HaruPage::lineTo' => ['bool', 'x'=>'float', 'y'=>'float'],
'HaruPage::measureText' => ['int', 'text'=>'string', 'width'=>'float', 'wordwrap='=>'bool'],
'HaruPage::moveTextPos' => ['bool', 'x'=>'float', 'y'=>'float', 'set_leading='=>'bool'],
'HaruPage::moveTo' => ['bool', 'x'=>'float', 'y'=>'float'],
'HaruPage::moveToNextLine' => ['bool'],
'HaruPage::rectangle' => ['bool', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'HaruPage::setCharSpace' => ['bool', 'char_space'=>'float'],
'HaruPage::setCMYKFill' => ['bool', 'c'=>'float', 'm'=>'float', 'y'=>'float', 'k'=>'float'],
'HaruPage::setCMYKStroke' => ['bool', 'c'=>'float', 'm'=>'float', 'y'=>'float', 'k'=>'float'],
'HaruPage::setDash' => ['bool', 'pattern'=>'array', 'phase'=>'int'],
'HaruPage::setFlatness' => ['bool', 'flatness'=>'float'],
'HaruPage::setFontAndSize' => ['bool', 'font'=>'object', 'size'=>'float'],
'HaruPage::setGrayFill' => ['bool', 'value'=>'float'],
'HaruPage::setGrayStroke' => ['bool', 'value'=>'float'],
'HaruPage::setHeight' => ['bool', 'height'=>'float'],
'HaruPage::setHorizontalScaling' => ['bool', 'scaling'=>'float'],
'HaruPage::setLineCap' => ['bool', 'cap'=>'int'],
'HaruPage::setLineJoin' => ['bool', 'join'=>'int'],
'HaruPage::setLineWidth' => ['bool', 'width'=>'float'],
'HaruPage::setMiterLimit' => ['bool', 'limit'=>'float'],
'HaruPage::setRGBFill' => ['bool', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'HaruPage::setRGBStroke' => ['bool', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'HaruPage::setRotate' => ['bool', 'angle'=>'int'],
'HaruPage::setSize' => ['bool', 'size'=>'int', 'direction'=>'int'],
'HaruPage::setSlideShow' => ['bool', 'type'=>'int', 'disp_time'=>'float', 'trans_time'=>'float'],
'HaruPage::setTextLeading' => ['bool', 'text_leading'=>'float'],
'HaruPage::setTextMatrix' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'HaruPage::setTextRenderingMode' => ['bool', 'mode'=>'int'],
'HaruPage::setTextRise' => ['bool', 'rise'=>'float'],
'HaruPage::setWidth' => ['bool', 'width'=>'float'],
'HaruPage::setWordSpace' => ['bool', 'word_space'=>'float'],
'HaruPage::showText' => ['bool', 'text'=>'string'],
'HaruPage::showTextNextLine' => ['bool', 'text'=>'string', 'word_space='=>'float', 'char_space='=>'float'],
'HaruPage::stroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::textOut' => ['bool', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'HaruPage::textRect' => ['bool', 'left'=>'float', 'top'=>'float', 'right'=>'float', 'bottom'=>'float', 'text'=>'string', 'align='=>'int'],
'hash' => ['string|false', 'algo'=>'string', 'data'=>'string', 'binary='=>'bool'],
'hash_algos' => ['list<string>'],
'hash_copy' => ['HashContext', 'context'=>'HashContext|resource'],
'hash_equals' => ['bool', 'known_string'=>'string', 'user_string'=>'string'],
'hash_file' => ['string|false', 'algo'=>'string', 'filename'=>'string', 'binary='=>'bool'],
'hash_final' => ['string', 'context'=>'HashContext|resource', 'binary='=>'bool'],
'hash_hkdf' => ['string|false', 'algo'=>'string', 'key'=>'string', 'length='=>'int', 'info='=>'string', 'salt='=>'string'],
'hash_hmac' => ['string|false', 'algo'=>'string', 'data'=>'string', 'key'=>'string', 'binary='=>'bool'],
'hash_hmac_algos' => ['list<string>'],
'hash_hmac_file' => ['string|false', 'algo'=>'string', 'data'=>'string', 'key'=>'string', 'binary='=>'bool'],
'hash_init' => ['HashContext|false', 'algo'=>'string', 'flags='=>'int', 'key='=>'string'],
'hash_pbkdf2' => ['string|false', 'algo'=>'string', 'password'=>'string', 'salt'=>'string', 'iterations'=>'int', 'length='=>'int', 'binary='=>'bool'],
'hash_update' => ['bool', 'context'=>'HashContext', 'data'=>'string'],
'hash_update_file' => ['bool', 'context'=>'HashContext', 'filename'=>'string', 'stream_context='=>'?HashContext'],
'hash_update_stream' => ['int', 'context'=>'HashContext', 'stream'=>'resource', 'length='=>'int'],
'hashTableObj::clear' => ['void'],
'hashTableObj::get' => ['string', 'key'=>'string'],
'hashTableObj::nextkey' => ['string', 'previousKey'=>'string'],
'hashTableObj::remove' => ['int', 'key'=>'string'],
'hashTableObj::set' => ['int', 'key'=>'string', 'value'=>'string'],
'header' => ['void', 'header'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'header_register_callback' => ['bool', 'callback'=>'callable():void'],
'header_remove' => ['void', 'name='=>'string'],
'headers_list' => ['list<string>'],
'headers_sent' => ['bool', '&w_filename='=>'string', '&w_line='=>'int'],
'hebrev' => ['string', 'string'=>'string', 'max_chars_per_line='=>'int'],
'hebrevc' => ['string', 'string'=>'string', 'max_chars_per_line='=>'int'],
'hex2bin' => ['string|false', 'string'=>'string'],
'hexdec' => ['int|float', 'hex_string'=>'string'],
'highlight_file' => ['string|bool', 'filename'=>'string', 'return='=>'bool'],
'highlight_string' => ['string|bool', 'string'=>'string', 'return='=>'bool'],
'hrtime' => ['array{0:int,1:int}|false', 'as_number='=>'false'],
'hrtime\'1' => ['int|float|false', 'as_number='=>'true'],
'HRTime\PerformanceCounter::getElapsedTicks' => ['int'],
'HRTime\PerformanceCounter::getFrequency' => ['int'],
'HRTime\PerformanceCounter::getLastElapsedTicks' => ['int'],
'HRTime\PerformanceCounter::getTicks' => ['int'],
'HRTime\PerformanceCounter::getTicksSince' => ['int', 'start'=>'int'],
'HRTime\PerformanceCounter::isRunning' => ['bool'],
'HRTime\PerformanceCounter::start' => ['void'],
'HRTime\PerformanceCounter::stop' => ['void'],
'HRTime\StopWatch::getElapsedTicks' => ['int'],
'HRTime\StopWatch::getElapsedTime' => ['float', 'unit='=>'int'],
'HRTime\StopWatch::getLastElapsedTicks' => ['int'],
'HRTime\StopWatch::getLastElapsedTime' => ['float', 'unit='=>'int'],
'HRTime\StopWatch::isRunning' => ['bool'],
'HRTime\StopWatch::start' => ['void'],
'HRTime\StopWatch::stop' => ['void'],
'html_entity_decode' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string'],
'htmlentities' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string', 'double_encode='=>'bool'],
'htmlspecialchars' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string', 'double_encode='=>'bool'],
'htmlspecialchars_decode' => ['string', 'string'=>'string', 'flags='=>'int'],
'http\Client::__construct' => ['void', 'driver='=>'string', 'persistent_handle_id='=>'string'],
'http\Client::addCookies' => ['http\Client', 'cookies='=>'?array'],
'http\Client::addSslOptions' => ['http\Client', 'ssl_options='=>'?array'],
'http\Client::attach' => ['void', 'observer'=>'SplObserver'],
'http\Client::configure' => ['http\Client', 'settings'=>'array'],
'http\Client::count' => ['int'],
'http\Client::dequeue' => ['http\Client', 'request'=>'http\Client\Request'],
'http\Client::detach' => ['void', 'observer'=>'SplObserver'],
'http\Client::enableEvents' => ['http\Client', 'enable='=>'mixed'],
'http\Client::enablePipelining' => ['http\Client', 'enable='=>'mixed'],
'http\Client::enqueue' => ['http\Client', 'request'=>'http\Client\Request', 'callable='=>'mixed'],
'http\Client::getAvailableConfiguration' => ['array'],
'http\Client::getAvailableDrivers' => ['array'],
'http\Client::getAvailableOptions' => ['array'],
'http\Client::getCookies' => ['array'],
'http\Client::getHistory' => ['http\Message'],
'http\Client::getObservers' => ['SplObjectStorage'],
'http\Client::getOptions' => ['array'],
'http\Client::getProgressInfo' => ['null|object', 'request'=>'http\Client\Request'],
'http\Client::getResponse' => ['http\Client\Response|null', 'request='=>'?http\Client\Request'],
'http\Client::getSslOptions' => ['array'],
'http\Client::getTransferInfo' => ['object', 'request'=>'http\Client\Request'],
'http\Client::notify' => ['void', 'request='=>'?http\Client\Request'],
'http\Client::once' => ['bool'],
'http\Client::requeue' => ['http\Client', 'request'=>'http\Client\Request', 'callable='=>'mixed'],
'http\Client::reset' => ['http\Client'],
'http\Client::send' => ['http\Client'],
'http\Client::setCookies' => ['http\Client', 'cookies='=>'?array'],
'http\Client::setDebug' => ['http\Client', 'callback'=>'callable'],
'http\Client::setOptions' => ['http\Client', 'options='=>'?array'],
'http\Client::setSslOptions' => ['http\Client', 'ssl_option='=>'?array'],
'http\Client::wait' => ['bool', 'timeout='=>'mixed'],
'http\Client\Curl\User::init' => ['', 'run'=>'callable'],
'http\Client\Curl\User::once' => [''],
'http\Client\Curl\User::send' => [''],
'http\Client\Curl\User::socket' => ['', 'socket'=>'resource', 'action'=>'int'],
'http\Client\Curl\User::timer' => ['', 'timeout_ms'=>'int'],
'http\Client\Curl\User::wait' => ['', 'timeout_ms='=>'mixed'],
'http\Client\Request::__construct' => ['void', 'method='=>'mixed', 'url='=>'mixed', 'headers='=>'?array', 'body='=>'?http\Message\Body'],
'http\Client\Request::__toString' => ['string'],
'http\Client\Request::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Request::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Client\Request::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Client\Request::addQuery' => ['http\Client\Request', 'query_data'=>'mixed'],
'http\Client\Request::addSslOptions' => ['http\Client\Request', 'ssl_options='=>'?array'],
'http\Client\Request::count' => ['int'],
'http\Client\Request::current' => ['mixed'],
'http\Client\Request::detach' => ['http\Message'],
'http\Client\Request::getBody' => ['http\Message\Body'],
'http\Client\Request::getContentType' => ['null|string'],
'http\Client\Request::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Client\Request::getHeaders' => ['array'],
'http\Client\Request::getHttpVersion' => ['string'],
'http\Client\Request::getInfo' => ['null|string'],
'http\Client\Request::getOptions' => ['array'],
'http\Client\Request::getParentMessage' => ['http\Message'],
'http\Client\Request::getQuery' => ['null|string'],
'http\Client\Request::getRequestMethod' => ['false|string'],
'http\Client\Request::getRequestUrl' => ['false|string'],
'http\Client\Request::getResponseCode' => ['false|int'],
'http\Client\Request::getResponseStatus' => ['false|string'],
'http\Client\Request::getSslOptions' => ['array'],
'http\Client\Request::getType' => ['int'],
'http\Client\Request::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Client\Request::key' => ['int|string'],
'http\Client\Request::next' => ['void'],
'http\Client\Request::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Client\Request::reverse' => ['http\Message'],
'http\Client\Request::rewind' => ['void'],
'http\Client\Request::serialize' => ['string'],
'http\Client\Request::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Request::setContentType' => ['http\Client\Request', 'content_type'=>'string'],
'http\Client\Request::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Client\Request::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Client\Request::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Client\Request::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Client\Request::setOptions' => ['http\Client\Request', 'options='=>'?array'],
'http\Client\Request::setQuery' => ['http\Client\Request', 'query_data='=>'mixed'],
'http\Client\Request::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Client\Request::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Client\Request::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Client\Request::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Client\Request::setSslOptions' => ['http\Client\Request', 'ssl_options='=>'?array'],
'http\Client\Request::setType' => ['http\Message', 'type'=>'int'],
'http\Client\Request::splitMultipartBody' => ['http\Message'],
'http\Client\Request::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Client\Request::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Client\Request::toString' => ['string', 'include_parent='=>'mixed'],
'http\Client\Request::unserialize' => ['void', 'serialized'=>'string'],
'http\Client\Request::valid' => ['bool'],
'http\Client\Response::__construct' => ['Iterator'],
'http\Client\Response::__toString' => ['string'],
'http\Client\Response::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Response::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Client\Response::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Client\Response::count' => ['int'],
'http\Client\Response::current' => ['mixed'],
'http\Client\Response::detach' => ['http\Message'],
'http\Client\Response::getBody' => ['http\Message\Body'],
'http\Client\Response::getCookies' => ['array', 'flags='=>'mixed', 'allowed_extras='=>'mixed'],
'http\Client\Response::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Client\Response::getHeaders' => ['array'],
'http\Client\Response::getHttpVersion' => ['string'],
'http\Client\Response::getInfo' => ['null|string'],
'http\Client\Response::getParentMessage' => ['http\Message'],
'http\Client\Response::getRequestMethod' => ['false|string'],
'http\Client\Response::getRequestUrl' => ['false|string'],
'http\Client\Response::getResponseCode' => ['false|int'],
'http\Client\Response::getResponseStatus' => ['false|string'],
'http\Client\Response::getTransferInfo' => ['mixed|object', 'element='=>'mixed'],
'http\Client\Response::getType' => ['int'],
'http\Client\Response::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Client\Response::key' => ['int|string'],
'http\Client\Response::next' => ['void'],
'http\Client\Response::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Client\Response::reverse' => ['http\Message'],
'http\Client\Response::rewind' => ['void'],
'http\Client\Response::serialize' => ['string'],
'http\Client\Response::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Response::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Client\Response::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Client\Response::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Client\Response::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Client\Response::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Client\Response::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Client\Response::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Client\Response::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Client\Response::setType' => ['http\Message', 'type'=>'int'],
'http\Client\Response::splitMultipartBody' => ['http\Message'],
'http\Client\Response::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Client\Response::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Client\Response::toString' => ['string', 'include_parent='=>'mixed'],
'http\Client\Response::unserialize' => ['void', 'serialized'=>'string'],
'http\Client\Response::valid' => ['bool'],
'http\Cookie::__construct' => ['void', 'cookie_string='=>'mixed', 'parser_flags='=>'int', 'allowed_extras='=>'array'],
'http\Cookie::__toString' => ['string'],
'http\Cookie::addCookie' => ['http\Cookie', 'cookie_name'=>'string', 'cookie_value'=>'string'],
'http\Cookie::addCookies' => ['http\Cookie', 'cookies'=>'array'],
'http\Cookie::addExtra' => ['http\Cookie', 'extra_name'=>'string', 'extra_value'=>'string'],
'http\Cookie::addExtras' => ['http\Cookie', 'extras'=>'array'],
'http\Cookie::getCookie' => ['null|string', 'name'=>'string'],
'http\Cookie::getCookies' => ['array'],
'http\Cookie::getDomain' => ['string'],
'http\Cookie::getExpires' => ['int'],
'http\Cookie::getExtra' => ['string', 'name'=>'string'],
'http\Cookie::getExtras' => ['array'],
'http\Cookie::getFlags' => ['int'],
'http\Cookie::getMaxAge' => ['int'],
'http\Cookie::getPath' => ['string'],
'http\Cookie::setCookie' => ['http\Cookie', 'cookie_name'=>'string', 'cookie_value='=>'mixed'],
'http\Cookie::setCookies' => ['http\Cookie', 'cookies='=>'mixed'],
'http\Cookie::setDomain' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setExpires' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setExtra' => ['http\Cookie', 'extra_name'=>'string', 'extra_value='=>'mixed'],
'http\Cookie::setExtras' => ['http\Cookie', 'extras='=>'mixed'],
'http\Cookie::setFlags' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setMaxAge' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setPath' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::toArray' => ['array'],
'http\Cookie::toString' => ['string'],
'http\Encoding\Stream::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream::done' => ['bool'],
'http\Encoding\Stream::finish' => ['string'],
'http\Encoding\Stream::flush' => ['string'],
'http\Encoding\Stream::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Debrotli::__construct' => ['void', 'flags='=>'int'],
'http\Encoding\Stream\Debrotli::decode' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Debrotli::done' => ['bool'],
'http\Encoding\Stream\Debrotli::finish' => ['string'],
'http\Encoding\Stream\Debrotli::flush' => ['string'],
'http\Encoding\Stream\Debrotli::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Dechunk::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Dechunk::decode' => ['false|string', 'data'=>'string', '&decoded_len='=>'mixed'],
'http\Encoding\Stream\Dechunk::done' => ['bool'],
'http\Encoding\Stream\Dechunk::finish' => ['string'],
'http\Encoding\Stream\Dechunk::flush' => ['string'],
'http\Encoding\Stream\Dechunk::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Deflate::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Deflate::done' => ['bool'],
'http\Encoding\Stream\Deflate::encode' => ['string', 'data'=>'string', 'flags='=>'mixed'],
'http\Encoding\Stream\Deflate::finish' => ['string'],
'http\Encoding\Stream\Deflate::flush' => ['string'],
'http\Encoding\Stream\Deflate::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Enbrotli::__construct' => ['void', 'flags='=>'int'],
'http\Encoding\Stream\Enbrotli::done' => ['bool'],
'http\Encoding\Stream\Enbrotli::encode' => ['string', 'data'=>'string', 'flags='=>'int'],
'http\Encoding\Stream\Enbrotli::finish' => ['string'],
'http\Encoding\Stream\Enbrotli::flush' => ['string'],
'http\Encoding\Stream\Enbrotli::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Inflate::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Inflate::decode' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Inflate::done' => ['bool'],
'http\Encoding\Stream\Inflate::finish' => ['string'],
'http\Encoding\Stream\Inflate::flush' => ['string'],
'http\Encoding\Stream\Inflate::update' => ['string', 'data'=>'string'],
'http\Env::getRequestBody' => ['http\Message\Body', 'body_class_name='=>'mixed'],
'http\Env::getRequestHeader' => ['array|null|string', 'header_name='=>'mixed'],
'http\Env::getResponseCode' => ['int'],
'http\Env::getResponseHeader' => ['array|null|string', 'header_name='=>'mixed'],
'http\Env::getResponseStatusForAllCodes' => ['array'],
'http\Env::getResponseStatusForCode' => ['string', 'code'=>'int'],
'http\Env::negotiate' => ['null|string', 'params'=>'string', 'supported'=>'array', 'primary_type_separator='=>'mixed', '&result_array='=>'mixed'],
'http\Env::negotiateCharset' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateContentType' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateEncoding' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateLanguage' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::setResponseCode' => ['bool', 'code'=>'int'],
'http\Env::setResponseHeader' => ['bool', 'header_name'=>'string', 'header_value='=>'mixed', 'response_code='=>'mixed', 'replace_header='=>'mixed'],
'http\Env\Request::__construct' => ['void'],
'http\Env\Request::__toString' => ['string'],
'http\Env\Request::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Request::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Env\Request::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Env\Request::count' => ['int'],
'http\Env\Request::current' => ['mixed'],
'http\Env\Request::detach' => ['http\Message'],
'http\Env\Request::getBody' => ['http\Message\Body'],
'http\Env\Request::getCookie' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getFiles' => ['array'],
'http\Env\Request::getForm' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Env\Request::getHeaders' => ['array'],
'http\Env\Request::getHttpVersion' => ['string'],
'http\Env\Request::getInfo' => ['null|string'],
'http\Env\Request::getParentMessage' => ['http\Message'],
'http\Env\Request::getQuery' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getRequestMethod' => ['false|string'],
'http\Env\Request::getRequestUrl' => ['false|string'],
'http\Env\Request::getResponseCode' => ['false|int'],
'http\Env\Request::getResponseStatus' => ['false|string'],
'http\Env\Request::getType' => ['int'],
'http\Env\Request::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Env\Request::key' => ['int|string'],
'http\Env\Request::next' => ['void'],
'http\Env\Request::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Env\Request::reverse' => ['http\Message'],
'http\Env\Request::rewind' => ['void'],
'http\Env\Request::serialize' => ['string'],
'http\Env\Request::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Request::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Env\Request::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Env\Request::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Env\Request::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Env\Request::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Env\Request::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Env\Request::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Env\Request::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Env\Request::setType' => ['http\Message', 'type'=>'int'],
'http\Env\Request::splitMultipartBody' => ['http\Message'],
'http\Env\Request::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Env\Request::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Env\Request::toString' => ['string', 'include_parent='=>'mixed'],
'http\Env\Request::unserialize' => ['void', 'serialized'=>'string'],
'http\Env\Request::valid' => ['bool'],
'http\Env\Response::__construct' => ['void'],
'http\Env\Response::__invoke' => ['bool', 'data'=>'string', 'ob_flags='=>'int'],
'http\Env\Response::__toString' => ['string'],
'http\Env\Response::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Response::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Env\Response::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Env\Response::count' => ['int'],
'http\Env\Response::current' => ['mixed'],
'http\Env\Response::detach' => ['http\Message'],
'http\Env\Response::getBody' => ['http\Message\Body'],
'http\Env\Response::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Env\Response::getHeaders' => ['array'],
'http\Env\Response::getHttpVersion' => ['string'],
'http\Env\Response::getInfo' => ['?string'],
'http\Env\Response::getParentMessage' => ['http\Message'],
'http\Env\Response::getRequestMethod' => ['false|string'],
'http\Env\Response::getRequestUrl' => ['false|string'],
'http\Env\Response::getResponseCode' => ['false|int'],
'http\Env\Response::getResponseStatus' => ['false|string'],
'http\Env\Response::getType' => ['int'],
'http\Env\Response::isCachedByETag' => ['int', 'header_name='=>'string'],
'http\Env\Response::isCachedByLastModified' => ['int', 'header_name='=>'string'],
'http\Env\Response::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Env\Response::key' => ['int|string'],
'http\Env\Response::next' => ['void'],
'http\Env\Response::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Env\Response::reverse' => ['http\Message'],
'http\Env\Response::rewind' => ['void'],
'http\Env\Response::send' => ['bool', 'stream='=>'resource'],
'http\Env\Response::serialize' => ['string'],
'http\Env\Response::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Response::setCacheControl' => ['http\Env\Response', 'cache_control'=>'string'],
'http\Env\Response::setContentDisposition' => ['http\Env\Response', 'disposition_params'=>'array'],
'http\Env\Response::setContentEncoding' => ['http\Env\Response', 'content_encoding'=>'int'],
'http\Env\Response::setContentType' => ['http\Env\Response', 'content_type'=>'string'],
'http\Env\Response::setCookie' => ['http\Env\Response', 'cookie'=>'mixed'],
'http\Env\Response::setEnvRequest' => ['http\Env\Response', 'env_request'=>'http\Message'],
'http\Env\Response::setEtag' => ['http\Env\Response', 'etag'=>'string'],
'http\Env\Response::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Env\Response::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Env\Response::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Env\Response::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Env\Response::setLastModified' => ['http\Env\Response', 'last_modified'=>'int'],
'http\Env\Response::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Env\Response::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Env\Response::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Env\Response::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Env\Response::setThrottleRate' => ['http\Env\Response', 'chunk_size'=>'int', 'delay='=>'float|int'],
'http\Env\Response::setType' => ['http\Message', 'type'=>'int'],
'http\Env\Response::splitMultipartBody' => ['http\Message'],
'http\Env\Response::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Env\Response::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Env\Response::toString' => ['string', 'include_parent='=>'mixed'],
'http\Env\Response::unserialize' => ['void', 'serialized'=>'string'],
'http\Env\Response::valid' => ['bool'],
'http\Header::__construct' => ['void', 'name='=>'mixed', 'value='=>'mixed'],
'http\Header::__toString' => ['string'],
'http\Header::getParams' => ['http\Params', 'param_sep='=>'mixed', 'arg_sep='=>'mixed', 'val_sep='=>'mixed', 'flags='=>'mixed'],
'http\Header::match' => ['bool', 'value'=>'string', 'flags='=>'mixed'],
'http\Header::negotiate' => ['null|string', 'supported'=>'array', '&result='=>'mixed'],
'http\Header::parse' => ['array|false', 'string'=>'string', 'header_class='=>'mixed'],
'http\Header::serialize' => ['string'],
'http\Header::toString' => ['string'],
'http\Header::unserialize' => ['void', 'serialized'=>'string'],
'http\Header\Parser::getState' => ['int'],
'http\Header\Parser::parse' => ['int', 'data'=>'string', 'flags'=>'int', '&headers'=>'array'],
'http\Header\Parser::stream' => ['int', 'stream'=>'resource', 'flags'=>'int', '&headers'=>'array'],
'http\Message::__construct' => ['void', 'message='=>'mixed', 'greedy='=>'bool'],
'http\Message::__toString' => ['string'],
'http\Message::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Message::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Message::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Message::count' => ['int'],
'http\Message::current' => ['mixed'],
'http\Message::detach' => ['http\Message'],
'http\Message::getBody' => ['http\Message\Body'],
'http\Message::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Message::getHeaders' => ['array'],
'http\Message::getHttpVersion' => ['string'],
'http\Message::getInfo' => ['null|string'],
'http\Message::getParentMessage' => ['http\Message'],
'http\Message::getRequestMethod' => ['false|string'],
'http\Message::getRequestUrl' => ['false|string'],
'http\Message::getResponseCode' => ['false|int'],
'http\Message::getResponseStatus' => ['false|string'],
'http\Message::getType' => ['int'],
'http\Message::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Message::key' => ['int|string'],
'http\Message::next' => ['void'],
'http\Message::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Message::reverse' => ['http\Message'],
'http\Message::rewind' => ['void'],
'http\Message::serialize' => ['string'],
'http\Message::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Message::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Message::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Message::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Message::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Message::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Message::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Message::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Message::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Message::setType' => ['http\Message', 'type'=>'int'],
'http\Message::splitMultipartBody' => ['http\Message'],
'http\Message::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Message::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Message::toString' => ['string', 'include_parent='=>'mixed'],
'http\Message::unserialize' => ['void', 'serialized'=>'string'],
'http\Message::valid' => ['bool'],
'http\Message\Body::__construct' => ['void', 'stream='=>'resource'],
'http\Message\Body::__toString' => ['string'],
'http\Message\Body::addForm' => ['http\Message\Body', 'fields='=>'?array', 'files='=>'?array'],
'http\Message\Body::addPart' => ['http\Message\Body', 'message'=>'http\Message'],
'http\Message\Body::append' => ['http\Message\Body', 'string'=>'string'],
'http\Message\Body::etag' => ['false|string'],
'http\Message\Body::getBoundary' => ['null|string'],
'http\Message\Body::getResource' => ['resource'],
'http\Message\Body::serialize' => ['string'],
'http\Message\Body::stat' => ['int|object', 'field='=>'mixed'],
'http\Message\Body::toCallback' => ['http\Message\Body', 'callback'=>'callable', 'offset='=>'mixed', 'maxlen='=>'mixed'],
'http\Message\Body::toStream' => ['http\Message\Body', 'stream'=>'resource', 'offset='=>'mixed', 'maxlen='=>'mixed'],
'http\Message\Body::toString' => ['string'],
'http\Message\Body::unserialize' => ['void', 'serialized'=>'string'],
'http\Message\Parser::getState' => ['int'],
'http\Message\Parser::parse' => ['int', 'data'=>'string', 'flags'=>'int', '&message'=>'http\Message'],
'http\Message\Parser::stream' => ['int', 'stream'=>'resource', 'flags'=>'int', '&message'=>'http\Message'],
'http\Params::__construct' => ['void', 'params='=>'mixed', 'param_sep='=>'mixed', 'arg_sep='=>'mixed', 'val_sep='=>'mixed', 'flags='=>'mixed'],
'http\Params::__toString' => ['string'],
'http\Params::offsetExists' => ['bool', 'name'=>'mixed'],
'http\Params::offsetGet' => ['mixed', 'name'=>'mixed'],
'http\Params::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'http\Params::offsetUnset' => ['void', 'name'=>'mixed'],
'http\Params::toArray' => ['array'],
'http\Params::toString' => ['string'],
'http\QueryString::__construct' => ['void', 'querystring'=>'string'],
'http\QueryString::__toString' => ['string'],
'http\QueryString::get' => ['http\QueryString|string|mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getArray' => ['array|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getBool' => ['bool|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getFloat' => ['float|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getGlobalInstance' => ['http\QueryString'],
'http\QueryString::getInt' => ['int|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getIterator' => ['IteratorAggregate'],
'http\QueryString::getObject' => ['object|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getString' => ['string|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::mod' => ['http\QueryString', 'params='=>'mixed'],
'http\QueryString::offsetExists' => ['bool', 'offset'=>'mixed'],
'http\QueryString::offsetGet' => ['mixed|null', 'offset'=>'mixed'],
'http\QueryString::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'http\QueryString::offsetUnset' => ['void', 'offset'=>'mixed'],
'http\QueryString::serialize' => ['string'],
'http\QueryString::set' => ['http\QueryString', 'params'=>'mixed'],
'http\QueryString::toArray' => ['array'],
'http\QueryString::toString' => ['string'],
'http\QueryString::unserialize' => ['void', 'serialized'=>'string'],
'http\QueryString::xlate' => ['http\QueryString'],
'http\Url::__construct' => ['void', 'old_url='=>'mixed', 'new_url='=>'mixed', 'flags='=>'int'],
'http\Url::__toString' => ['string'],
'http\Url::mod' => ['http\Url', 'parts'=>'mixed', 'flags='=>'float|int|mixed'],
'http\Url::toArray' => ['string[]'],
'http\Url::toString' => ['string'],
'http_build_cookie' => ['string', 'cookie'=>'array'],
'http_build_query' => ['string', 'data'=>'array|object', 'numeric_prefix='=>'string', 'arg_separator='=>'string', 'encoding_type='=>'int'],
'http_build_str' => ['string', 'query'=>'array', 'prefix='=>'?string', 'arg_separator='=>'string'],
'http_build_url' => ['string', 'url='=>'string|array', 'parts='=>'string|array', 'flags='=>'int', 'new_url='=>'array'],
'http_cache_etag' => ['bool', 'etag='=>'string'],
'http_cache_last_modified' => ['bool', 'timestamp_or_expires='=>'int'],
'http_chunked_decode' => ['string|false', 'encoded'=>'string'],
'http_date' => ['string', 'timestamp='=>'int'],
'http_deflate' => ['?string', 'data'=>'string', 'flags='=>'int'],
'http_get' => ['string', 'url'=>'string', 'options='=>'array', 'info='=>'array'],
'http_get_request_body' => ['?string'],
'http_get_request_body_stream' => ['?resource'],
'http_get_request_headers' => ['array'],
'http_head' => ['string', 'url'=>'string', 'options='=>'array', 'info='=>'array'],
'http_inflate' => ['?string', 'data'=>'string'],
'http_match_etag' => ['bool', 'etag'=>'string', 'for_range='=>'bool'],
'http_match_modified' => ['bool', 'timestamp='=>'int', 'for_range='=>'bool'],
'http_match_request_header' => ['bool', 'header'=>'string', 'value'=>'string', 'match_case='=>'bool'],
'http_negotiate_charset' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_negotiate_content_type' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_negotiate_language' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_parse_cookie' => ['stdClass|false', 'cookie'=>'string', 'flags='=>'int', 'allowed_extras='=>'array'],
'http_parse_headers' => ['array|false', 'header'=>'string'],
'http_parse_message' => ['object', 'message'=>'string'],
'http_parse_params' => ['stdClass', 'param'=>'string', 'flags='=>'int'],
'http_persistent_handles_clean' => ['string', 'ident='=>'string'],
'http_persistent_handles_count' => ['stdClass|false'],
'http_persistent_handles_ident' => ['string|false', 'ident='=>'string'],
'http_post_data' => ['string', 'url'=>'string', 'data'=>'string', 'options='=>'array', 'info='=>'array'],
'http_post_fields' => ['string', 'url'=>'string', 'data'=>'array', 'files='=>'array', 'options='=>'array', 'info='=>'array'],
'http_put_data' => ['string', 'url'=>'string', 'data'=>'string', 'options='=>'array', 'info='=>'array'],
'http_put_file' => ['string', 'url'=>'string', 'file'=>'string', 'options='=>'array', 'info='=>'array'],
'http_put_stream' => ['string', 'url'=>'string', 'stream'=>'resource', 'options='=>'array', 'info='=>'array'],
'http_redirect' => ['int|false', 'url='=>'string', 'params='=>'array', 'session='=>'bool', 'status='=>'int'],
'http_request' => ['string', 'method'=>'int', 'url'=>'string', 'body='=>'string', 'options='=>'array', 'info='=>'array'],
'http_request_body_encode' => ['string|false', 'fields'=>'array', 'files'=>'array'],
'http_request_method_exists' => ['bool', 'method'=>'mixed'],
'http_request_method_name' => ['string|false', 'method'=>'int'],
'http_request_method_register' => ['int|false', 'method'=>'string'],
'http_request_method_unregister' => ['bool', 'method'=>'mixed'],
'http_response_code' => ['int|bool', 'response_code='=>'int'],
'http_send_content_disposition' => ['bool', 'filename'=>'string', 'inline='=>'bool'],
'http_send_content_type' => ['bool', 'content_type='=>'string'],
'http_send_data' => ['bool', 'data'=>'string'],
'http_send_file' => ['bool', 'file'=>'string'],
'http_send_last_modified' => ['bool', 'timestamp='=>'int'],
'http_send_status' => ['bool', 'status'=>'int'],
'http_send_stream' => ['bool', 'stream'=>'resource'],
'http_support' => ['int', 'feature='=>'int'],
'http_throttle' => ['void', 'sec'=>'float', 'bytes='=>'int'],
'HttpDeflateStream::__construct' => ['void', 'flags='=>'int'],
'HttpDeflateStream::factory' => ['HttpDeflateStream', 'flags='=>'int', 'class_name='=>'string'],
'HttpDeflateStream::finish' => ['string', 'data='=>'string'],
'HttpDeflateStream::flush' => ['string|false', 'data='=>'string'],
'HttpDeflateStream::update' => ['string|false', 'data'=>'string'],
'HttpInflateStream::__construct' => ['void', 'flags='=>'int'],
'HttpInflateStream::factory' => ['HttpInflateStream', 'flags='=>'int', 'class_name='=>'string'],
'HttpInflateStream::finish' => ['string', 'data='=>'string'],
'HttpInflateStream::flush' => ['string|false', 'data='=>'string'],
'HttpInflateStream::update' => ['string|false', 'data'=>'string'],
'HttpMessage::__construct' => ['void', 'message='=>'string'],
'HttpMessage::__toString' => ['string'],
'HttpMessage::addHeaders' => ['void', 'headers'=>'array', 'append='=>'bool'],
'HttpMessage::count' => ['int'],
'HttpMessage::current' => ['mixed'],
'HttpMessage::detach' => ['HttpMessage'],
'HttpMessage::factory' => ['?HttpMessage', 'raw_message='=>'string', 'class_name='=>'string'],
'HttpMessage::fromEnv' => ['?HttpMessage', 'message_type'=>'int', 'class_name='=>'string'],
'HttpMessage::fromString' => ['?HttpMessage', 'raw_message='=>'string', 'class_name='=>'string'],
'HttpMessage::getBody' => ['string'],
'HttpMessage::getHeader' => ['?string', 'header'=>'string'],
'HttpMessage::getHeaders' => ['array'],
'HttpMessage::getHttpVersion' => ['string'],
'HttpMessage::getInfo' => [''],
'HttpMessage::getParentMessage' => ['HttpMessage'],
'HttpMessage::getRequestMethod' => ['string|false'],
'HttpMessage::getRequestUrl' => ['string|false'],
'HttpMessage::getResponseCode' => ['int'],
'HttpMessage::getResponseStatus' => ['string'],
'HttpMessage::getType' => ['int'],
'HttpMessage::guessContentType' => ['string|false', 'magic_file'=>'string', 'magic_mode='=>'int'],
'HttpMessage::key' => ['int|string'],
'HttpMessage::next' => ['void'],
'HttpMessage::prepend' => ['void', 'message'=>'HttpMessage', 'top='=>'bool'],
'HttpMessage::reverse' => ['HttpMessage'],
'HttpMessage::rewind' => ['void'],
'HttpMessage::send' => ['bool'],
'HttpMessage::serialize' => ['string'],
'HttpMessage::setBody' => ['void', 'body'=>'string'],
'HttpMessage::setHeaders' => ['void', 'headers'=>'array'],
'HttpMessage::setHttpVersion' => ['bool', 'version'=>'string'],
'HttpMessage::setInfo' => ['', 'http_info'=>''],
'HttpMessage::setRequestMethod' => ['bool', 'method'=>'string'],
'HttpMessage::setRequestUrl' => ['bool', 'url'=>'string'],
'HttpMessage::setResponseCode' => ['bool', 'code'=>'int'],
'HttpMessage::setResponseStatus' => ['bool', 'status'=>'string'],
'HttpMessage::setType' => ['void', 'type'=>'int'],
'HttpMessage::toMessageTypeObject' => ['HttpRequest|HttpResponse|null'],
'HttpMessage::toString' => ['string', 'include_parent='=>'bool'],
'HttpMessage::unserialize' => ['void', 'serialized'=>'string'],
'HttpMessage::valid' => ['bool'],
'HttpQueryString::__construct' => ['void', 'global='=>'bool', 'add='=>'mixed'],
'HttpQueryString::__toString' => ['string'],
'HttpQueryString::factory' => ['', 'global'=>'', 'params'=>'', 'class_name'=>''],
'HttpQueryString::get' => ['mixed', 'key='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'HttpQueryString::getArray' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getBool' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getFloat' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getInt' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getObject' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getString' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::mod' => ['HttpQueryString', 'params'=>'mixed'],
'HttpQueryString::offsetExists' => ['bool', 'offset'=>'mixed'],
'HttpQueryString::offsetGet' => ['mixed', 'offset'=>'mixed'],
'HttpQueryString::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'HttpQueryString::offsetUnset' => ['void', 'offset'=>'mixed'],
'HttpQueryString::serialize' => ['string'],
'HttpQueryString::set' => ['string', 'params'=>'mixed'],
'HttpQueryString::singleton' => ['HttpQueryString', 'global='=>'bool'],
'HttpQueryString::toArray' => ['array'],
'HttpQueryString::toString' => ['string'],
'HttpQueryString::unserialize' => ['void', 'serialized'=>'string'],
'HttpQueryString::xlate' => ['bool', 'ie'=>'string', 'oe'=>'string'],
'HttpRequest::__construct' => ['void', 'url='=>'string', 'request_method='=>'int', 'options='=>'array'],
'HttpRequest::addBody' => ['', 'request_body_data'=>''],
'HttpRequest::addCookies' => ['bool', 'cookies'=>'array'],
'HttpRequest::addHeaders' => ['bool', 'headers'=>'array'],
'HttpRequest::addPostFields' => ['bool', 'post_data'=>'array'],
'HttpRequest::addPostFile' => ['bool', 'name'=>'string', 'file'=>'string', 'content_type='=>'string'],
'HttpRequest::addPutData' => ['bool', 'put_data'=>'string'],
'HttpRequest::addQueryData' => ['bool', 'query_params'=>'array'],
'HttpRequest::addRawPostData' => ['bool', 'raw_post_data'=>'string'],
'HttpRequest::addSslOptions' => ['bool', 'options'=>'array'],
'HttpRequest::clearHistory' => ['void'],
'HttpRequest::enableCookies' => ['bool'],
'HttpRequest::encodeBody' => ['', 'fields'=>'', 'files'=>''],
'HttpRequest::factory' => ['', 'url'=>'', 'method'=>'', 'options'=>'', 'class_name'=>''],
'HttpRequest::flushCookies' => [''],
'HttpRequest::get' => ['', 'url'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::getBody' => [''],
'HttpRequest::getContentType' => ['string'],
'HttpRequest::getCookies' => ['array'],
'HttpRequest::getHeaders' => ['array'],
'HttpRequest::getHistory' => ['HttpMessage'],
'HttpRequest::getMethod' => ['int'],
'HttpRequest::getOptions' => ['array'],
'HttpRequest::getPostFields' => ['array'],
'HttpRequest::getPostFiles' => ['array'],
'HttpRequest::getPutData' => ['string'],
'HttpRequest::getPutFile' => ['string'],
'HttpRequest::getQueryData' => ['string'],
'HttpRequest::getRawPostData' => ['string'],
'HttpRequest::getRawRequestMessage' => ['string'],
'HttpRequest::getRawResponseMessage' => ['string'],
'HttpRequest::getRequestMessage' => ['HttpMessage'],
'HttpRequest::getResponseBody' => ['string'],
'HttpRequest::getResponseCode' => ['int'],
'HttpRequest::getResponseCookies' => ['stdClass[]', 'flags='=>'int', 'allowed_extras='=>'array'],
'HttpRequest::getResponseData' => ['array'],
'HttpRequest::getResponseHeader' => ['mixed', 'name='=>'string'],
'HttpRequest::getResponseInfo' => ['mixed', 'name='=>'string'],
'HttpRequest::getResponseMessage' => ['HttpMessage'],
'HttpRequest::getResponseStatus' => ['string'],
'HttpRequest::getSslOptions' => ['array'],
'HttpRequest::getUrl' => ['string'],
'HttpRequest::head' => ['', 'url'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::methodExists' => ['', 'method'=>''],
'HttpRequest::methodName' => ['', 'method_id'=>''],
'HttpRequest::methodRegister' => ['', 'method_name'=>''],
'HttpRequest::methodUnregister' => ['', 'method'=>''],
'HttpRequest::postData' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::postFields' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putData' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putFile' => ['', 'url'=>'', 'file'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putStream' => ['', 'url'=>'', 'stream'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::resetCookies' => ['bool', 'session_only='=>'bool'],
'HttpRequest::send' => ['HttpMessage'],
'HttpRequest::setBody' => ['bool', 'request_body_data='=>'string'],
'HttpRequest::setContentType' => ['bool', 'content_type'=>'string'],
'HttpRequest::setCookies' => ['bool', 'cookies='=>'array'],
'HttpRequest::setHeaders' => ['bool', 'headers='=>'array'],
'HttpRequest::setMethod' => ['bool', 'request_method'=>'int'],
'HttpRequest::setOptions' => ['bool', 'options='=>'array'],
'HttpRequest::setPostFields' => ['bool', 'post_data'=>'array'],
'HttpRequest::setPostFiles' => ['bool', 'post_files'=>'array'],
'HttpRequest::setPutData' => ['bool', 'put_data='=>'string'],
'HttpRequest::setPutFile' => ['bool', 'file='=>'string'],
'HttpRequest::setQueryData' => ['bool', 'query_data'=>'mixed'],
'HttpRequest::setRawPostData' => ['bool', 'raw_post_data='=>'string'],
'HttpRequest::setSslOptions' => ['bool', 'options='=>'array'],
'HttpRequest::setUrl' => ['bool', 'url'=>'string'],
'HttpRequestDataShare::__construct' => ['void'],
'HttpRequestDataShare::__destruct' => ['void'],
'HttpRequestDataShare::attach' => ['', 'request'=>'HttpRequest'],
'HttpRequestDataShare::count' => ['int'],
'HttpRequestDataShare::detach' => ['', 'request'=>'HttpRequest'],
'HttpRequestDataShare::factory' => ['', 'global'=>'', 'class_name'=>''],
'HttpRequestDataShare::reset' => [''],
'HttpRequestDataShare::singleton' => ['', 'global'=>''],
'HttpRequestPool::__construct' => ['void', 'request='=>'HttpRequest'],
'HttpRequestPool::__destruct' => ['void'],
'HttpRequestPool::attach' => ['bool', 'request'=>'HttpRequest'],
'HttpRequestPool::count' => ['int'],
'HttpRequestPool::current' => ['mixed'],
'HttpRequestPool::detach' => ['bool', 'request'=>'HttpRequest'],
'HttpRequestPool::enableEvents' => ['', 'enable'=>''],
'HttpRequestPool::enablePipelining' => ['', 'enable'=>''],
'HttpRequestPool::getAttachedRequests' => ['array'],
'HttpRequestPool::getFinishedRequests' => ['array'],
'HttpRequestPool::key' => ['int|string'],
'HttpRequestPool::next' => ['void'],
'HttpRequestPool::reset' => ['void'],
'HttpRequestPool::rewind' => ['void'],
'HttpRequestPool::send' => ['bool'],
'HttpRequestPool::socketPerform' => ['bool'],
'HttpRequestPool::socketSelect' => ['bool', 'timeout='=>'float'],
'HttpRequestPool::valid' => ['bool'],
'HttpResponse::capture' => ['void'],
'HttpResponse::getBufferSize' => ['int'],
'HttpResponse::getCache' => ['bool'],
'HttpResponse::getCacheControl' => ['string'],
'HttpResponse::getContentDisposition' => ['string'],
'HttpResponse::getContentType' => ['string'],
'HttpResponse::getData' => ['string'],
'HttpResponse::getETag' => ['string'],
'HttpResponse::getFile' => ['string'],
'HttpResponse::getGzip' => ['bool'],
'HttpResponse::getHeader' => ['mixed', 'name='=>'string'],
'HttpResponse::getLastModified' => ['int'],
'HttpResponse::getRequestBody' => ['string'],
'HttpResponse::getRequestBodyStream' => ['resource'],
'HttpResponse::getRequestHeaders' => ['array'],
'HttpResponse::getStream' => ['resource'],
'HttpResponse::getThrottleDelay' => ['float'],
'HttpResponse::guessContentType' => ['string|false', 'magic_file'=>'string', 'magic_mode='=>'int'],
'HttpResponse::redirect' => ['void', 'url='=>'string', 'params='=>'array', 'session='=>'bool', 'status='=>'int'],
'HttpResponse::send' => ['bool', 'clean_ob='=>'bool'],
'HttpResponse::setBufferSize' => ['bool', 'bytes'=>'int'],
'HttpResponse::setCache' => ['bool', 'cache'=>'bool'],
'HttpResponse::setCacheControl' => ['bool', 'control'=>'string', 'max_age='=>'int', 'must_revalidate='=>'bool'],
'HttpResponse::setContentDisposition' => ['bool', 'filename'=>'string', 'inline='=>'bool'],
'HttpResponse::setContentType' => ['bool', 'content_type'=>'string'],
'HttpResponse::setData' => ['bool', 'data'=>'mixed'],
'HttpResponse::setETag' => ['bool', 'etag'=>'string'],
'HttpResponse::setFile' => ['bool', 'file'=>'string'],
'HttpResponse::setGzip' => ['bool', 'gzip'=>'bool'],
'HttpResponse::setHeader' => ['bool', 'name'=>'string', 'value='=>'mixed', 'replace='=>'bool'],
'HttpResponse::setLastModified' => ['bool', 'timestamp'=>'int'],
'HttpResponse::setStream' => ['bool', 'stream'=>'resource'],
'HttpResponse::setThrottleDelay' => ['bool', 'seconds'=>'float'],
'HttpResponse::status' => ['bool', 'status'=>'int'],
'HttpUtil::buildCookie' => ['', 'cookie_array'=>''],
'HttpUtil::buildStr' => ['', 'query'=>'', 'prefix'=>'', 'arg_sep'=>''],
'HttpUtil::buildUrl' => ['', 'url'=>'', 'parts'=>'', 'flags'=>'', '&composed'=>''],
'HttpUtil::chunkedDecode' => ['', 'encoded_string'=>''],
'HttpUtil::date' => ['', 'timestamp'=>''],
'HttpUtil::deflate' => ['', 'plain'=>'', 'flags'=>''],
'HttpUtil::inflate' => ['', 'encoded'=>''],
'HttpUtil::matchEtag' => ['', 'plain_etag'=>'', 'for_range'=>''],
'HttpUtil::matchModified' => ['', 'last_modified'=>'', 'for_range'=>''],
'HttpUtil::matchRequestHeader' => ['', 'header_name'=>'', 'header_value'=>'', 'case_sensitive'=>''],
'HttpUtil::negotiateCharset' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::negotiateContentType' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::negotiateLanguage' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::parseCookie' => ['', 'cookie_string'=>''],
'HttpUtil::parseHeaders' => ['', 'headers_string'=>''],
'HttpUtil::parseMessage' => ['', 'message_string'=>''],
'HttpUtil::parseParams' => ['', 'param_string'=>'', 'flags'=>''],
'HttpUtil::support' => ['', 'feature'=>''],
'hw_api::checkin' => ['bool', 'parameter'=>'array'],
'hw_api::checkout' => ['bool', 'parameter'=>'array'],
'hw_api::children' => ['array', 'parameter'=>'array'],
'hw_api::content' => ['HW_API_Content', 'parameter'=>'array'],
'hw_api::copy' => ['hw_api_content', 'parameter'=>'array'],
'hw_api::dbstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::dcstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::dstanchors' => ['array', 'parameter'=>'array'],
'hw_api::dstofsrcanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::find' => ['array', 'parameter'=>'array'],
'hw_api::ftstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::hwstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::identify' => ['bool', 'parameter'=>'array'],
'hw_api::info' => ['array', 'parameter'=>'array'],
'hw_api::insert' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertcollection' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertdocument' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::link' => ['bool', 'parameter'=>'array'],
'hw_api::lock' => ['bool', 'parameter'=>'array'],
'hw_api::move' => ['bool', 'parameter'=>'array'],
'hw_api::object' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::objectbyanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::parents' => ['array', 'parameter'=>'array'],
'hw_api::remove' => ['bool', 'parameter'=>'array'],
'hw_api::replace' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::setcommittedversion' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::srcanchors' => ['array', 'parameter'=>'array'],
'hw_api::srcsofdst' => ['array', 'parameter'=>'array'],
'hw_api::unlock' => ['bool', 'parameter'=>'array'],
'hw_api::user' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::userlist' => ['array', 'parameter'=>'array'],
'hw_api_attribute' => ['HW_API_Attribute', 'name='=>'string', 'value='=>'string'],
'hw_api_attribute::key' => ['string'],
'hw_api_attribute::langdepvalue' => ['string', 'language'=>'string'],
'hw_api_attribute::value' => ['string'],
'hw_api_attribute::values' => ['array'],
'hw_api_content' => ['HW_API_Content', 'content'=>'string', 'mimetype'=>'string'],
'hw_api_content::mimetype' => ['string'],
'hw_api_content::read' => ['string', 'buffer'=>'string', 'length'=>'int'],
'hw_api_error::count' => ['int'],
'hw_api_error::reason' => ['HW_API_Reason'],
'hw_api_object' => ['hw_api_object', 'parameter'=>'array'],
'hw_api_object::assign' => ['bool', 'parameter'=>'array'],
'hw_api_object::attreditable' => ['bool', 'parameter'=>'array'],
'hw_api_object::count' => ['int', 'parameter'=>'array'],
'hw_api_object::insert' => ['bool', 'attribute'=>'hw_api_attribute'],
'hw_api_object::remove' => ['bool', 'name'=>'string'],
'hw_api_object::title' => ['string', 'parameter'=>'array'],
'hw_api_object::value' => ['string', 'name'=>'string'],
'hw_api_reason::description' => ['string'],
'hw_api_reason::type' => ['HW_API_Reason'],
'hw_Array2Objrec' => ['string', 'object_array'=>'array'],
'hw_changeobject' => ['bool', 'link'=>'int', 'objid'=>'int', 'attributes'=>'array'],
'hw_Children' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_ChildrenObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_Close' => ['bool', 'connection'=>'int'],
'hw_Connect' => ['int', 'host'=>'string', 'port'=>'int', 'username='=>'string', 'password='=>'string'],
'hw_connection_info' => ['', 'link'=>'int'],
'hw_cp' => ['int', 'connection'=>'int', 'object_id_array'=>'array', 'destination_id'=>'int'],
'hw_Deleteobject' => ['bool', 'connection'=>'int', 'object_to_delete'=>'int'],
'hw_DocByAnchor' => ['int', 'connection'=>'int', 'anchorid'=>'int'],
'hw_DocByAnchorObj' => ['string', 'connection'=>'int', 'anchorid'=>'int'],
'hw_Document_Attributes' => ['string', 'hw_document'=>'int'],
'hw_Document_BodyTag' => ['string', 'hw_document'=>'int', 'prefix='=>'string'],
'hw_Document_Content' => ['string', 'hw_document'=>'int'],
'hw_Document_SetContent' => ['bool', 'hw_document'=>'int', 'content'=>'string'],
'hw_Document_Size' => ['int', 'hw_document'=>'int'],
'hw_dummy' => ['string', 'link'=>'int', 'id'=>'int', 'msgid'=>'int'],
'hw_EditText' => ['bool', 'connection'=>'int', 'hw_document'=>'int'],
'hw_Error' => ['int', 'connection'=>'int'],
'hw_ErrorMsg' => ['string', 'connection'=>'int'],
'hw_Free_Document' => ['bool', 'hw_document'=>'int'],
'hw_GetAnchors' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetAnchorsObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetAndLock' => ['string', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildColl' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildDocColl' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildDocCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetObject' => ['', 'connection'=>'int', 'objectid'=>'', 'query='=>'string'],
'hw_GetObjectByQuery' => ['array', 'connection'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryColl' => ['array', 'connection'=>'int', 'objectid'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryObj' => ['array', 'connection'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetParents' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetParentsObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_getrellink' => ['string', 'link'=>'int', 'rootid'=>'int', 'sourceid'=>'int', 'destid'=>'int'],
'hw_GetRemote' => ['int', 'connection'=>'int', 'objectid'=>'int'],
'hw_getremotechildren' => ['', 'connection'=>'int', 'object_record'=>'string'],
'hw_GetSrcByDestObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetText' => ['int', 'connection'=>'int', 'objectid'=>'int', 'prefix='=>''],
'hw_getusername' => ['string', 'connection'=>'int'],
'hw_Identify' => ['string', 'link'=>'int', 'username'=>'string', 'password'=>'string'],
'hw_InCollections' => ['array', 'connection'=>'int', 'object_id_array'=>'array', 'collection_id_array'=>'array', 'return_collections'=>'int'],
'hw_Info' => ['string', 'connection'=>'int'],
'hw_InsColl' => ['int', 'connection'=>'int', 'objectid'=>'int', 'object_array'=>'array'],
'hw_InsDoc' => ['int', 'connection'=>'', 'parentid'=>'int', 'object_record'=>'string', 'text='=>'string'],
'hw_insertanchors' => ['bool', 'hwdoc'=>'int', 'anchorecs'=>'array', 'dest'=>'array', 'urlprefixes='=>'array'],
'hw_InsertDocument' => ['int', 'connection'=>'int', 'parent_id'=>'int', 'hw_document'=>'int'],
'hw_InsertObject' => ['int', 'connection'=>'int', 'object_rec'=>'string', 'parameter'=>'string'],
'hw_mapid' => ['int', 'connection'=>'int', 'server_id'=>'int', 'object_id'=>'int'],
'hw_Modifyobject' => ['bool', 'connection'=>'int', 'object_to_change'=>'int', 'remove'=>'array', 'add'=>'array', 'mode='=>'int'],
'hw_mv' => ['int', 'connection'=>'int', 'object_id_array'=>'array', 'source_id'=>'int', 'destination_id'=>'int'],
'hw_New_Document' => ['int', 'object_record'=>'string', 'document_data'=>'string', 'document_size'=>'int'],
'hw_objrec2array' => ['array', 'object_record'=>'string', 'format='=>'array'],
'hw_Output_Document' => ['bool', 'hw_document'=>'int'],
'hw_pConnect' => ['int', 'host'=>'string', 'port'=>'int', 'username='=>'string', 'password='=>'string'],
'hw_PipeDocument' => ['int', 'connection'=>'int', 'objectid'=>'int', 'url_prefixes='=>'array'],
'hw_Root' => ['int'],
'hw_setlinkroot' => ['int', 'link'=>'int', 'rootid'=>'int'],
'hw_stat' => ['string', 'link'=>'int'],
'hw_Unlock' => ['bool', 'connection'=>'int', 'objectid'=>'int'],
'hw_Who' => ['array', 'connection'=>'int'],
'hwapi_attribute_new' => ['HW_API_Attribute', 'name='=>'string', 'value='=>'string'],
'hwapi_content_new' => ['HW_API_Content', 'content'=>'string', 'mimetype'=>'string'],
'hwapi_hgcsp' => ['HW_API', 'hostname'=>'string', 'port='=>'int'],
'hwapi_object_new' => ['hw_api_object', 'parameter'=>'array'],
'hypot' => ['float', 'x'=>'float', 'y'=>'float'],
'ibase_add_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password'=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_affected_rows' => ['int', 'link_identifier='=>'resource'],
'ibase_backup' => ['mixed', 'service_handle'=>'resource', 'source_db'=>'string', 'dest_file'=>'string', 'options='=>'int', 'verbose='=>'bool'],
'ibase_blob_add' => ['void', 'blob_handle'=>'resource', 'data'=>'string'],
'ibase_blob_cancel' => ['bool', 'blob_handle'=>'resource'],
'ibase_blob_close' => ['string|bool', 'blob_handle'=>'resource'],
'ibase_blob_create' => ['resource', 'link_identifier='=>'resource'],
'ibase_blob_echo' => ['bool', 'link_identifier'=>'', 'blob_id'=>'string'],
'ibase_blob_echo\'1' => ['bool', 'blob_id'=>'string'],
'ibase_blob_get' => ['string|false', 'blob_handle'=>'resource', 'length'=>'int'],
'ibase_blob_import' => ['string|false', 'link_identifier'=>'resource', 'file_handle'=>'resource'],
'ibase_blob_info' => ['array', 'link_identifier'=>'resource', 'blob_id'=>'string'],
'ibase_blob_info\'1' => ['array', 'blob_id'=>'string'],
'ibase_blob_open' => ['resource|false', 'link_identifier'=>'', 'blob_id'=>'string'],
'ibase_blob_open\'1' => ['resource', 'blob_id'=>'string'],
'ibase_close' => ['bool', 'link_identifier='=>'resource'],
'ibase_commit' => ['bool', 'link_identifier='=>'resource'],
'ibase_commit_ret' => ['bool', 'link_identifier='=>'resource'],
'ibase_connect' => ['resource|false', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'charset='=>'string', 'buffers='=>'int', 'dialect='=>'int', 'role='=>'string'],
'ibase_db_info' => ['string', 'service_handle'=>'resource', 'db'=>'string', 'action'=>'int', 'argument='=>'int'],
'ibase_delete_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password='=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_drop_db' => ['bool', 'link_identifier='=>'resource'],
'ibase_errcode' => ['int|false'],
'ibase_errmsg' => ['string|false'],
'ibase_execute' => ['resource|false', 'query'=>'resource', 'bind_arg='=>'mixed', '...args='=>'mixed'],
'ibase_fetch_assoc' => ['array|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_fetch_object' => ['object|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_fetch_row' => ['array|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_field_info' => ['array', 'query_result'=>'resource', 'field_number'=>'int'],
'ibase_free_event_handler' => ['bool', 'event'=>'resource'],
'ibase_free_query' => ['bool', 'query'=>'resource'],
'ibase_free_result' => ['bool', 'result'=>'resource'],
'ibase_gen_id' => ['int|string', 'generator'=>'string', 'increment='=>'int', 'link_identifier='=>'resource'],
'ibase_maintain_db' => ['bool', 'service_handle'=>'resource', 'db'=>'string', 'action'=>'int', 'argument='=>'int'],
'ibase_modify_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password'=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_name_result' => ['bool', 'result'=>'resource', 'name'=>'string'],
'ibase_num_fields' => ['int', 'query_result'=>'resource'],
'ibase_num_params' => ['int', 'query'=>'resource'],
'ibase_num_rows' => ['int', 'result_identifier'=>''],
'ibase_param_info' => ['array', 'query'=>'resource', 'field_number'=>'int'],
'ibase_pconnect' => ['resource|false', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'charset='=>'string', 'buffers='=>'int', 'dialect='=>'int', 'role='=>'string'],
'ibase_prepare' => ['resource|false', 'link_identifier'=>'', 'query'=>'string', 'trans_identifier'=>''],
'ibase_query' => ['resource|false', 'link_identifier='=>'resource', 'string='=>'string', 'bind_arg='=>'int', '...args='=>''],
'ibase_restore' => ['mixed', 'service_handle'=>'resource', 'source_file'=>'string', 'dest_db'=>'string', 'options='=>'int', 'verbose='=>'bool'],
'ibase_rollback' => ['bool', 'link_identifier='=>'resource'],
'ibase_rollback_ret' => ['bool', 'link_identifier='=>'resource'],
'ibase_server_info' => ['string', 'service_handle'=>'resource', 'action'=>'int'],
'ibase_service_attach' => ['resource', 'host'=>'string', 'dba_username'=>'string', 'dba_password'=>'string'],
'ibase_service_detach' => ['bool', 'service_handle'=>'resource'],
'ibase_set_event_handler' => ['resource', 'link_identifier'=>'', 'callback'=>'callable', 'event='=>'string', '...args='=>''],
'ibase_set_event_handler\'1' => ['resource', 'callback'=>'callable', 'event'=>'string', '...args'=>''],
'ibase_timefmt' => ['bool', 'format'=>'string', 'columntype='=>'int'],
'ibase_trans' => ['resource|false', 'trans_args='=>'int', 'link_identifier='=>'', '...args='=>''],
'ibase_wait_event' => ['string', 'link_identifier'=>'', 'event='=>'string', '...args='=>''],
'ibase_wait_event\'1' => ['string', 'event'=>'string', '...args'=>''],
'iconv' => ['string|false', 'from_encoding'=>'string', 'to_encoding'=>'string', 'string'=>'string'],
'iconv_get_encoding' => ['mixed', 'type='=>'string'],
'iconv_mime_decode' => ['string|false', 'string'=>'string', 'mode='=>'int', 'encoding='=>'string'],
'iconv_mime_decode_headers' => ['array|false', 'headers'=>'string', 'mode='=>'int', 'encoding='=>'string'],
'iconv_mime_encode' => ['string|false', 'field_name'=>'string', 'field_value'=>'string', 'options='=>'array'],
'iconv_set_encoding' => ['bool', 'type'=>'string', 'encoding'=>'string'],
'iconv_strlen' => ['int|false', 'string'=>'string', 'encoding='=>'string'],
'iconv_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'iconv_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'encoding='=>'string'],
'iconv_substr' => ['string|false', 'string'=>'string', 'offset'=>'int', 'length='=>'int', 'encoding='=>'string'],
'id3_get_frame_long_name' => ['string', 'frameid'=>'string'],
'id3_get_frame_short_name' => ['string', 'frameid'=>'string'],
'id3_get_genre_id' => ['int', 'genre'=>'string'],
'id3_get_genre_list' => ['array'],
'id3_get_genre_name' => ['string', 'genre_id'=>'int'],
'id3_get_tag' => ['array', 'filename'=>'string', 'version='=>'int'],
'id3_get_version' => ['int', 'filename'=>'string'],
'id3_remove_tag' => ['bool', 'filename'=>'string', 'version='=>'int'],
'id3_set_tag' => ['bool', 'filename'=>'string', 'tag'=>'array', 'version='=>'int'],
'idate' => ['int', 'format'=>'string', 'timestamp='=>'int'],
'idn_strerror' => ['string', 'errorcode'=>'int'],
'idn_to_ascii' => ['string|false', 'domain'=>'string', 'flags='=>'int', 'variant='=>'int', '&w_idna_info='=>'array'],
'idn_to_utf8' => ['string|false', 'domain'=>'string', 'flags='=>'int', 'variant='=>'int', '&w_idna_info='=>'array'],
'ifx_affected_rows' => ['int', 'result_id'=>'resource'],
'ifx_blobinfile_mode' => ['bool', 'mode'=>'int'],
'ifx_byteasvarchar' => ['bool', 'mode'=>'int'],
'ifx_close' => ['bool', 'link_identifier='=>'resource'],
'ifx_connect' => ['resource', 'database='=>'string', 'userid='=>'string', 'password='=>'string'],
'ifx_copy_blob' => ['int', 'bid'=>'int'],
'ifx_create_blob' => ['int', 'type'=>'int', 'mode'=>'int', 'param'=>'string'],
'ifx_create_char' => ['int', 'param'=>'string'],
'ifx_do' => ['bool', 'result_id'=>'resource'],
'ifx_error' => ['string', 'link_identifier='=>'resource'],
'ifx_errormsg' => ['string', 'errorcode='=>'int'],
'ifx_fetch_row' => ['array', 'result_id'=>'resource', 'position='=>'mixed'],
'ifx_fieldproperties' => ['array', 'result_id'=>'resource'],
'ifx_fieldtypes' => ['array', 'result_id'=>'resource'],
'ifx_free_blob' => ['bool', 'bid'=>'int'],
'ifx_free_char' => ['bool', 'bid'=>'int'],
'ifx_free_result' => ['bool', 'result_id'=>'resource'],
'ifx_get_blob' => ['string', 'bid'=>'int'],
'ifx_get_char' => ['string', 'bid'=>'int'],
'ifx_getsqlca' => ['array', 'result_id'=>'resource'],
'ifx_htmltbl_result' => ['int', 'result_id'=>'resource', 'html_table_options='=>'string'],
'ifx_nullformat' => ['bool', 'mode'=>'int'],
'ifx_num_fields' => ['int', 'result_id'=>'resource'],
'ifx_num_rows' => ['int', 'result_id'=>'resource'],
'ifx_pconnect' => ['resource', 'database='=>'string', 'userid='=>'string', 'password='=>'string'],
'ifx_prepare' => ['resource', 'query'=>'string', 'link_identifier'=>'resource', 'cursor_def='=>'int', 'blobidarray='=>'mixed'],
'ifx_query' => ['resource', 'query'=>'string', 'link_identifier'=>'resource', 'cursor_type='=>'int', 'blobidarray='=>'mixed'],
'ifx_textasvarchar' => ['bool', 'mode'=>'int'],
'ifx_update_blob' => ['bool', 'bid'=>'int', 'content'=>'string'],
'ifx_update_char' => ['bool', 'bid'=>'int', 'content'=>'string'],
'ifxus_close_slob' => ['bool', 'bid'=>'int'],
'ifxus_create_slob' => ['int', 'mode'=>'int'],
'ifxus_free_slob' => ['bool', 'bid'=>'int'],
'ifxus_open_slob' => ['int', 'bid'=>'int', 'mode'=>'int'],
'ifxus_read_slob' => ['string', 'bid'=>'int', 'nbytes'=>'int'],
'ifxus_seek_slob' => ['int', 'bid'=>'int', 'mode'=>'int', 'offset'=>'int'],
'ifxus_tell_slob' => ['int', 'bid'=>'int'],
'ifxus_write_slob' => ['int', 'bid'=>'int', 'content'=>'string'],
'igbinary_serialize' => ['string|false', 'value'=>'mixed'],
'igbinary_unserialize' => ['mixed', 'string'=>'string'],
'ignore_user_abort' => ['int', 'enable='=>'bool'],
'iis_add_server' => ['int', 'path'=>'string', 'comment'=>'string', 'server_ip'=>'string', 'port'=>'int', 'host_name'=>'string', 'rights'=>'int', 'start_server'=>'int'],
'iis_get_dir_security' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string'],
'iis_get_script_map' => ['string', 'server_instance'=>'int', 'virtual_path'=>'string', 'script_extension'=>'string'],
'iis_get_server_by_comment' => ['int', 'comment'=>'string'],
'iis_get_server_by_path' => ['int', 'path'=>'string'],
'iis_get_server_rights' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string'],
'iis_get_service_state' => ['int', 'service_id'=>'string'],
'iis_remove_server' => ['int', 'server_instance'=>'int'],
'iis_set_app_settings' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'application_scope'=>'string'],
'iis_set_dir_security' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'directory_flags'=>'int'],
'iis_set_script_map' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'script_extension'=>'string', 'engine_path'=>'string', 'allow_scripting'=>'int'],
'iis_set_server_rights' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'directory_flags'=>'int'],
'iis_start_server' => ['int', 'server_instance'=>'int'],
'iis_start_service' => ['int', 'service_id'=>'string'],
'iis_stop_server' => ['int', 'server_instance'=>'int'],
'iis_stop_service' => ['int', 'service_id'=>'string'],
'image2wbmp' => ['bool', 'im'=>'resource', 'filename='=>'?string', 'threshold='=>'int'],
'image_type_to_extension' => ['string', 'image_type'=>'int', 'include_dot='=>'bool'],
'image_type_to_mime_type' => ['string', 'image_type'=>'int'],
'imageaffine' => ['resource|false', 'image'=>'resource', 'affine'=>'array', 'clip='=>'array'],
'imageaffineconcat' => ['array|false', 'm1'=>'array', 'm2'=>'array'],
'imageaffinematrixconcat' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'matrix1'=>'array', 'matrix2'=>'array'],
'imageaffinematrixget' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'type'=>'int', 'options'=>'array|float'],
'imagealphablending' => ['bool', 'image'=>'resource', 'enable'=>'bool'],
'imageantialias' => ['bool', 'image'=>'resource', 'enable'=>'bool'],
'imagearc' => ['bool', 'image'=>'resource', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'start_angle'=>'int', 'end_angle'=>'int', 'color'=>'int'],
'imagebmp' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null', 'compressed='=>'bool'],
'imagechar' => ['bool', 'image'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'char'=>'string', 'color'=>'int'],
'imagecharup' => ['bool', 'image'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'char'=>'string', 'color'=>'int'],
'imagecolorallocate' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorallocatealpha' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorat' => ['int|false', 'image'=>'resource', 'x'=>'int', 'y'=>'int'],
'imagecolorclosest' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorclosestalpha' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorclosesthwb' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolordeallocate' => ['bool', 'image'=>'resource', 'color'=>'int'],
'imagecolorexact' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorexactalpha' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolormatch' => ['bool', 'image1'=>'resource', 'image2'=>'resource'],
'imagecolorresolve' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorresolvealpha' => ['int|false', 'image'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorset' => ['void', 'image'=>'resource', 'color'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int'],
'imagecolorsforindex' => ['array|false', 'image'=>'resource', 'color'=>'int'],
'imagecolorstotal' => ['int|false', 'image'=>'resource'],
'imagecolortransparent' => ['int|false', 'image'=>'resource', 'color='=>'int'],
'imageconvolution' => ['bool', 'image'=>'resource', 'matrix'=>'array', 'divisor'=>'float', 'offset'=>'float'],
'imagecopy' => ['bool', 'dst_image'=>'resource', 'src_image'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecopymerge' => ['bool', 'dst_image'=>'resource', 'src_image'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int', 'pct'=>'int'],
'imagecopymergegray' => ['bool', 'dst_image'=>'resource', 'src_image'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int', 'pct'=>'int'],
'imagecopyresampled' => ['bool', 'dst_image'=>'resource', 'src_image'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_width'=>'int', 'dst_height'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecopyresized' => ['bool', 'dst_image'=>'resource', 'src_image'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_width'=>'int', 'dst_height'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecreate' => ['resource|false', 'width'=>'int', 'height'=>'int'],
'imagecreatefrombmp' => ['resource|false', 'filename'=>'string'],
'imagecreatefromgd' => ['resource|false', 'filename'=>'string'],
'imagecreatefromgd2' => ['resource|false', 'filename'=>'string'],
'imagecreatefromgd2part' => ['resource|false', 'filename'=>'string', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int'],
'imagecreatefromgif' => ['resource|false', 'filename'=>'string'],
'imagecreatefromjpeg' => ['resource|false', 'filename'=>'string'],
'imagecreatefrompng' => ['resource|false', 'filename'=>'string'],
'imagecreatefromstring' => ['resource|false', 'data'=>'string'],
'imagecreatefromwbmp' => ['resource|false', 'filename'=>'string'],
'imagecreatefromwebp' => ['resource|false', 'filename'=>'string'],
'imagecreatefromxbm' => ['resource|false', 'filename'=>'string'],
'imagecreatefromxpm' => ['resource|false', 'filename'=>'string'],
'imagecreatetruecolor' => ['resource|false', 'width'=>'int', 'height'=>'int'],
'imagecrop' => ['resource|false', 'image'=>'resource', 'rectangle'=>'array'],
'imagecropauto' => ['resource|false', 'image'=>'resource', 'mode'=>'int', 'threshold'=>'float', 'color'=>'int'],
'imagedashedline' => ['bool', 'image'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imagedestroy' => ['bool', 'image'=>'resource'],
'imageellipse' => ['bool', 'image'=>'resource', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'color'=>'int'],
'imagefill' => ['bool', 'image'=>'resource', 'x'=>'int', 'y'=>'int', 'color'=>'int'],
'imagefilledarc' => ['bool', 'image'=>'resource', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'start_angle'=>'int', 'end_angle'=>'int', 'color'=>'int', 'style'=>'int'],
'imagefilledellipse' => ['bool', 'image'=>'resource', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'color'=>'int'],
'imagefilledpolygon' => ['bool', 'image'=>'resource', 'points'=>'array', 'num_points_or_color'=>'int', 'color'=>'int'],
'imagefilledrectangle' => ['bool', 'image'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imagefilltoborder' => ['bool', 'image'=>'resource', 'x'=>'int', 'y'=>'int', 'border_color'=>'int', 'color'=>'int'],
'imagefilter' => ['bool', 'image'=>'resource', 'filter'=>'int', 'args='=>'int', 'arg2='=>'int', 'arg3='=>'int', 'arg4='=>'int'],
'imageflip' => ['bool', 'image'=>'resource', 'mode'=>'int'],
'imagefontheight' => ['int', 'font'=>'int'],
'imagefontwidth' => ['int', 'font'=>'int'],
'imageftbbox' => ['array|false', 'size'=>'float', 'angle'=>'float', 'font_filename'=>'string', 'string'=>'string', 'options='=>'array'],
'imagefttext' => ['array|false', 'image'=>'resource', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'color'=>'int', 'font_filename'=>'string', 'text'=>'string', 'options='=>'array'],
'imagegammacorrect' => ['bool', 'image'=>'resource', 'input_gamma'=>'float', 'output_gamma'=>'float'],
'imagegd' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null'],
'imagegd2' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null', 'chunk_size='=>'int', 'mode='=>'int'],
'imagegetclip' => ['array|false', 'image'=>'resource'],
'imagegif' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null'],
'imagegrabscreen' => ['false|resource'],
'imagegrabwindow' => ['false|resource', 'handle'=>'int', 'client_area='=>'int'],
'imageinterlace' => ['int|false', 'image'=>'resource', 'enable='=>'int'],
'imageistruecolor' => ['bool', 'image'=>'resource'],
'imagejpeg' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null', 'quality='=>'int'],
'imagejpeg\'1' => ['string|false', 'image'=>'resource', 'file='=>'null', 'quality='=>'int'],
'imagelayereffect' => ['bool', 'image'=>'resource', 'effect'=>'int'],
'imageline' => ['bool', 'image'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imageloadfont' => ['int|false', 'filename'=>'string'],
'imageObj::pasteImage' => ['void', 'srcImg'=>'imageObj', 'transparentColorHex'=>'int', 'dstX'=>'int', 'dstY'=>'int', 'angle'=>'int'],
'imageObj::saveImage' => ['int', 'filename'=>'string', 'oMap'=>'mapObj'],
'imageObj::saveWebImage' => ['string'],
'imageopenpolygon' => ['bool', 'image'=>'resource', 'points'=>'array', 'num_points_or_color'=>'int', 'color'=>'int'],
'imagepalettecopy' => ['void', 'dst'=>'resource', 'src'=>'resource'],
'imagepalettetotruecolor' => ['bool', 'image'=>'resource'],
'imagepng' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null', 'quality='=>'int', 'filters='=>'int'],
'imagepolygon' => ['bool', 'image'=>'resource', 'points'=>'array', 'num_points_or_color'=>'int', 'color'=>'int'],
'imagerectangle' => ['bool', 'image'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imageresolution' => ['array|bool', 'image'=>'resource', 'resolution_x='=>'int', 'resolution_y='=>'int'],
'imagerotate' => ['resource|false', 'image'=>'resource', 'angle'=>'float', 'background_color'=>'int', 'ignore_transparent='=>'int'],
'imagesavealpha' => ['bool', 'image'=>'resource', 'enable'=>'bool'],
'imagescale' => ['resource|false', 'image'=>'resource', 'width'=>'int', 'height='=>'int', 'mode='=>'int'],
'imagesetbrush' => ['bool', 'image'=>'resource', 'brush'=>'resource'],
'imagesetclip' => ['bool', 'image'=>'resource', 'x1'=>'int', 'x2'=>'int', 'y1'=>'int', 'y2'=>'int'],
'imagesetinterpolation' => ['bool', 'image'=>'resource', 'method'=>'int'],
'imagesetpixel' => ['bool', 'image'=>'resource', 'x'=>'int', 'y'=>'int', 'color'=>'int'],
'imagesetstyle' => ['bool', 'image'=>'resource', 'style'=>'non-empty-array'],
'imagesetthickness' => ['bool', 'image'=>'resource', 'thickness'=>'int'],
'imagesettile' => ['bool', 'image'=>'resource', 'tile'=>'resource'],
'imagestring' => ['bool', 'image'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'string'=>'string', 'color'=>'int'],
'imagestringup' => ['bool', 'image'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'string'=>'string', 'color'=>'int'],
'imagesx' => ['int|false', 'image'=>'resource'],
'imagesy' => ['int|false', 'image'=>'resource'],
'imagetruecolortopalette' => ['bool', 'image'=>'resource', 'dither'=>'bool', 'num_colors'=>'int'],
'imagettfbbox' => ['false|array', 'size'=>'float', 'angle'=>'float', 'font_filename'=>'string', 'string'=>'string'],
'imagettftext' => ['false|array', 'image'=>'resource', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'color'=>'int', 'font_filename'=>'string', 'text'=>'string'],
'imagetypes' => ['int'],
'imagewbmp' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null', 'foreground_color='=>'int'],
'imagewebp' => ['bool', 'image'=>'resource', 'file='=>'string|resource|null', 'quality='=>'int'],
'imagexbm' => ['bool', 'image'=>'resource', 'filename='=>'?string', 'foreground_color='=>'int'],
'Imagick::__construct' => ['void', 'files='=>'string|string[]'],
'Imagick::__toString' => ['string'],
'Imagick::adaptiveBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::adaptiveResizeImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'bestfit='=>'bool'],
'Imagick::adaptiveSharpenImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::adaptiveThresholdImage' => ['bool', 'width'=>'int', 'height'=>'int', 'offset'=>'int'],
'Imagick::addImage' => ['bool', 'source'=>'Imagick'],
'Imagick::addNoiseImage' => ['bool', 'noise_type'=>'int', 'channel='=>'int'],
'Imagick::affineTransformImage' => ['bool', 'matrix'=>'ImagickDraw'],
'Imagick::animateImages' => ['bool', 'x_server'=>'string'],
'Imagick::annotateImage' => ['bool', 'draw_settings'=>'ImagickDraw', 'x'=>'float', 'y'=>'float', 'angle'=>'float', 'text'=>'string'],
'Imagick::appendImages' => ['Imagick', 'stack'=>'bool'],
'Imagick::autoGammaImage' => ['bool', 'channel='=>'int'],
'Imagick::autoLevelImage' => ['void', 'CHANNEL='=>'string'],
'Imagick::autoOrient' => ['bool'],
'Imagick::averageImages' => ['Imagick'],
'Imagick::blackThresholdImage' => ['bool', 'threshold'=>'mixed'],
'Imagick::blueShiftImage' => ['void', 'factor='=>'float'],
'Imagick::blurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::borderImage' => ['bool', 'bordercolor'=>'mixed', 'width'=>'int', 'height'=>'int'],
'Imagick::brightnessContrastImage' => ['void', 'brightness'=>'string', 'contrast'=>'string', 'CHANNEL='=>'string'],
'Imagick::charcoalImage' => ['bool', 'radius'=>'float', 'sigma'=>'float'],
'Imagick::chopImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::clampImage' => ['void', 'CHANNEL='=>'string'],
'Imagick::clear' => ['bool'],
'Imagick::clipImage' => ['bool'],
'Imagick::clipImagePath' => ['void', 'pathname'=>'string', 'inside'=>'string'],
'Imagick::clipPathImage' => ['bool', 'pathname'=>'string', 'inside'=>'bool'],
'Imagick::clone' => ['Imagick'],
'Imagick::clutImage' => ['bool', 'lookup_table'=>'Imagick', 'channel='=>'float'],
'Imagick::coalesceImages' => ['Imagick'],
'Imagick::colorFloodfillImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int'],
'Imagick::colorizeImage' => ['bool', 'colorize'=>'mixed', 'opacity'=>'mixed'],
'Imagick::colorMatrixImage' => ['void', 'color_matrix'=>'string'],
'Imagick::combineImages' => ['Imagick', 'channeltype'=>'int'],
'Imagick::commentImage' => ['bool', 'comment'=>'string'],
'Imagick::compareImageChannels' => ['array{Imagick, float}', 'image'=>'Imagick', 'channeltype'=>'int', 'metrictype'=>'int'],
'Imagick::compareImageLayers' => ['Imagick', 'method'=>'int'],
'Imagick::compareImages' => ['array{Imagick, float}', 'compare'=>'Imagick', 'metric'=>'int'],
'Imagick::compositeImage' => ['bool', 'composite_object'=>'Imagick', 'composite'=>'int', 'x'=>'int', 'y'=>'int', 'channel='=>'int'],
'Imagick::compositeImageGravity' => ['bool', 'Imagick'=>'Imagick', 'COMPOSITE_CONSTANT'=>'int', 'GRAVITY_CONSTANT'=>'int'],
'Imagick::contrastImage' => ['bool', 'sharpen'=>'bool'],
'Imagick::contrastStretchImage' => ['bool', 'black_point'=>'float', 'white_point'=>'float', 'channel='=>'int'],
'Imagick::convolveImage' => ['bool', 'kernel'=>'array', 'channel='=>'int'],
'Imagick::count' => ['void', 'mode='=>'string'],
'Imagick::cropImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::cropThumbnailImage' => ['bool', 'width'=>'int', 'height'=>'int', 'legacy='=>'bool'],
'Imagick::current' => ['Imagick'],
'Imagick::cycleColormapImage' => ['bool', 'displace'=>'int'],
'Imagick::decipherImage' => ['bool', 'passphrase'=>'string'],
'Imagick::deconstructImages' => ['Imagick'],
'Imagick::deleteImageArtifact' => ['bool', 'artifact'=>'string'],
'Imagick::deleteImageProperty' => ['void', 'name'=>'string'],
'Imagick::deskewImage' => ['bool', 'threshold'=>'float'],
'Imagick::despeckleImage' => ['bool'],
'Imagick::destroy' => ['bool'],
'Imagick::displayImage' => ['bool', 'servername'=>'string'],
'Imagick::displayImages' => ['bool', 'servername'=>'string'],
'Imagick::distortImage' => ['bool', 'method'=>'int', 'arguments'=>'array', 'bestfit'=>'bool'],
'Imagick::drawImage' => ['bool', 'draw'=>'ImagickDraw'],
'Imagick::edgeImage' => ['bool', 'radius'=>'float'],
'Imagick::embossImage' => ['bool', 'radius'=>'float', 'sigma'=>'float'],
'Imagick::encipherImage' => ['bool', 'passphrase'=>'string'],
'Imagick::enhanceImage' => ['bool'],
'Imagick::equalizeImage' => ['bool'],
'Imagick::evaluateImage' => ['bool', 'op'=>'int', 'constant'=>'float', 'channel='=>'int'],
'Imagick::evaluateImages' => ['bool', 'EVALUATE_CONSTANT'=>'int'],
'Imagick::exportImagePixels' => ['list<int>', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int', 'map'=>'string', 'storage'=>'int'],
'Imagick::extentImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::filter' => ['void', 'ImagickKernel'=>'ImagickKernel', 'CHANNEL='=>'int'],
'Imagick::flattenImages' => ['Imagick'],
'Imagick::flipImage' => ['bool'],
'Imagick::floodFillPaintImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'target'=>'mixed', 'x'=>'int', 'y'=>'int', 'invert'=>'bool', 'channel='=>'int'],
'Imagick::flopImage' => ['bool'],
'Imagick::forwardFourierTransformimage' => ['void', 'magnitude'=>'bool'],
'Imagick::frameImage' => ['bool', 'matte_color'=>'mixed', 'width'=>'int', 'height'=>'int', 'inner_bevel'=>'int', 'outer_bevel'=>'int'],
'Imagick::functionImage' => ['bool', 'function'=>'int', 'arguments'=>'array', 'channel='=>'int'],
'Imagick::fxImage' => ['Imagick', 'expression'=>'string', 'channel='=>'int'],
'Imagick::gammaImage' => ['bool', 'gamma'=>'float', 'channel='=>'int'],
'Imagick::gaussianBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::getColorspace' => ['int'],
'Imagick::getCompression' => ['int'],
'Imagick::getCompressionQuality' => ['int'],
'Imagick::getConfigureOptions' => ['string'],
'Imagick::getCopyright' => ['string'],
'Imagick::getFeatures' => ['string'],
'Imagick::getFilename' => ['string'],
'Imagick::getFont' => ['string|false'],
'Imagick::getFormat' => ['string'],
'Imagick::getGravity' => ['int'],
'Imagick::getHDRIEnabled' => ['int'],
'Imagick::getHomeURL' => ['string'],
'Imagick::getImage' => ['Imagick'],
'Imagick::getImageAlphaChannel' => ['int'],
'Imagick::getImageArtifact' => ['string', 'artifact'=>'string'],
'Imagick::getImageAttribute' => ['string', 'key'=>'string'],
'Imagick::getImageBackgroundColor' => ['ImagickPixel'],
'Imagick::getImageBlob' => ['string'],
'Imagick::getImageBluePrimary' => ['array{x:float, y:float}'],
'Imagick::getImageBorderColor' => ['ImagickPixel'],
'Imagick::getImageChannelDepth' => ['int', 'channel'=>'int'],
'Imagick::getImageChannelDistortion' => ['float', 'reference'=>'Imagick', 'channel'=>'int', 'metric'=>'int'],
'Imagick::getImageChannelDistortions' => ['float', 'reference'=>'Imagick', 'metric'=>'int', 'channel='=>'int'],
'Imagick::getImageChannelExtrema' => ['array{minima:int, maxima:int}', 'channel'=>'int'],
'Imagick::getImageChannelKurtosis' => ['array{kurtosis:float, skewness:float}', 'channel='=>'int'],
'Imagick::getImageChannelMean' => ['array{mean:float, standardDeviation:float}', 'channel'=>'int'],
'Imagick::getImageChannelRange' => ['array{minima:float, maxima:float}', 'channel'=>'int'],
'Imagick::getImageChannelStatistics' => ['array<int, array{mean:float, minima:float, maxima:float, standardDeviation:float, depth:int}>'],
'Imagick::getImageClipMask' => ['Imagick'],
'Imagick::getImageColormapColor' => ['ImagickPixel', 'index'=>'int'],
'Imagick::getImageColors' => ['int'],
'Imagick::getImageColorspace' => ['int'],
'Imagick::getImageCompose' => ['int'],
'Imagick::getImageCompression' => ['int'],
'Imagick::getImageCompressionQuality' => ['int'],
'Imagick::getImageDelay' => ['int'],
'Imagick::getImageDepth' => ['int'],
'Imagick::getImageDispose' => ['int'],
'Imagick::getImageDistortion' => ['float', 'reference'=>'magickwand', 'metric'=>'int'],
'Imagick::getImageExtrema' => ['array{min:int, max:int}'],
'Imagick::getImageFilename' => ['string'],
'Imagick::getImageFormat' => ['string'],
'Imagick::getImageGamma' => ['float'],
'Imagick::getImageGeometry' => ['array{width:int, height:int}'],
'Imagick::getImageGravity' => ['int'],
'Imagick::getImageGreenPrimary' => ['array{x:float, y:float}'],
'Imagick::getImageHeight' => ['int'],
'Imagick::getImageHistogram' => ['list<ImagickPixel>'],
'Imagick::getImageIndex' => ['int'],
'Imagick::getImageInterlaceScheme' => ['int'],
'Imagick::getImageInterpolateMethod' => ['int'],
'Imagick::getImageIterations' => ['int'],
'Imagick::getImageLength' => ['int'],
'Imagick::getImageMagickLicense' => ['string'],
'Imagick::getImageMatte' => ['bool'],
'Imagick::getImageMatteColor' => ['ImagickPixel'],
'Imagick::getImageMimeType' => ['string'],
'Imagick::getImageOrientation' => ['int'],
'Imagick::getImagePage' => ['array{width:int, height:int, x:int, y:int}'],
'Imagick::getImagePixelColor' => ['ImagickPixel', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageProfile' => ['string', 'name'=>'string'],
'Imagick::getImageProfiles' => ['array', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperties' => ['array<int|string, string>', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperty' => ['string|false', 'name'=>'string'],
'Imagick::getImageRedPrimary' => ['array{x:float, y:float}'],
'Imagick::getImageRegion' => ['Imagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageRenderingIntent' => ['int'],
'Imagick::getImageResolution' => ['array{x:float, y:float}'],
'Imagick::getImagesBlob' => ['string'],
'Imagick::getImageScene' => ['int'],
'Imagick::getImageSignature' => ['string'],
'Imagick::getImageSize' => ['int'],
'Imagick::getImageTicksPerSecond' => ['int'],
'Imagick::getImageTotalInkDensity' => ['float'],
'Imagick::getImageType' => ['int'],
'Imagick::getImageUnits' => ['int'],
'Imagick::getImageVirtualPixelMethod' => ['int'],
'Imagick::getImageWhitePoint' => ['array{x:float, y:float}'],
'Imagick::getImageWidth' => ['int'],
'Imagick::getInterlaceScheme' => ['int'],
'Imagick::getIteratorIndex' => ['int'],
'Imagick::getNumberImages' => ['int'],
'Imagick::getOption' => ['string', 'key'=>'string'],
'Imagick::getPackageName' => ['string'],
'Imagick::getPage' => ['array{width:int, height:int, x:int, y:int}'],
'Imagick::getPixelIterator' => ['ImagickPixelIterator'],
'Imagick::getPixelRegionIterator' => ['ImagickPixelIterator', 'x'=>'int', 'y'=>'int', 'columns'=>'int', 'rows'=>'int'],
'Imagick::getPointSize' => ['float'],
'Imagick::getQuantum' => ['int'],
'Imagick::getQuantumDepth' => ['array{quantumDepthLong:int, quantumDepthString:string}'],
'Imagick::getQuantumRange' => ['array{quantumRangeLong:int, quantumRangeString:string}'],
'Imagick::getRegistry' => ['string|false', 'key'=>'string'],
'Imagick::getReleaseDate' => ['string'],
'Imagick::getResource' => ['int', 'type'=>'int'],
'Imagick::getResourceLimit' => ['int', 'type'=>'int'],
'Imagick::getSamplingFactors' => ['array'],
'Imagick::getSize' => ['array{columns:int, rows: int}'],
'Imagick::getSizeOffset' => ['int'],
'Imagick::getVersion' => ['array{versionNumber: int, versionString:string}'],
'Imagick::haldClutImage' => ['bool', 'clut'=>'Imagick', 'channel='=>'int'],
'Imagick::hasNextImage' => ['bool'],
'Imagick::hasPreviousImage' => ['bool'],
'Imagick::identifyFormat' => ['string|false', 'embedText'=>'string'],
'Imagick::identifyImage' => ['array<string, mixed>', 'appendrawoutput='=>'bool'],
'Imagick::identifyImageType' => ['int'],
'Imagick::implodeImage' => ['bool', 'radius'=>'float'],
'Imagick::importImagePixels' => ['bool', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int', 'map'=>'string', 'storage'=>'int', 'pixels'=>'list<int>'],
'Imagick::inverseFourierTransformImage' => ['void', 'complement'=>'string', 'magnitude'=>'string'],
'Imagick::key' => ['int|string'],
'Imagick::labelImage' => ['bool', 'label'=>'string'],
'Imagick::levelImage' => ['bool', 'blackpoint'=>'float', 'gamma'=>'float', 'whitepoint'=>'float', 'channel='=>'int'],
'Imagick::linearStretchImage' => ['bool', 'blackpoint'=>'float', 'whitepoint'=>'float'],
'Imagick::liquidRescaleImage' => ['bool', 'width'=>'int', 'height'=>'int', 'delta_x'=>'float', 'rigidity'=>'float'],
'Imagick::listRegistry' => ['array'],
'Imagick::localContrastImage' => ['bool', 'radius'=>'float', 'strength'=>'float'],
'Imagick::magnifyImage' => ['bool'],
'Imagick::mapImage' => ['bool', 'map'=>'Imagick', 'dither'=>'bool'],
'Imagick::matteFloodfillImage' => ['bool', 'alpha'=>'float', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int'],
'Imagick::medianFilterImage' => ['bool', 'radius'=>'float'],
'Imagick::mergeImageLayers' => ['Imagick', 'layer_method'=>'int'],
'Imagick::minifyImage' => ['bool'],
'Imagick::modulateImage' => ['bool', 'brightness'=>'float', 'saturation'=>'float', 'hue'=>'float'],
'Imagick::montageImage' => ['Imagick', 'draw'=>'ImagickDraw', 'tile_geometry'=>'string', 'thumbnail_geometry'=>'string', 'mode'=>'int', 'frame'=>'string'],
'Imagick::morphImages' => ['Imagick', 'number_frames'=>'int'],
'Imagick::morphology' => ['void', 'morphologyMethod'=>'int', 'iterations'=>'int', 'ImagickKernel'=>'ImagickKernel', 'CHANNEL='=>'string'],
'Imagick::mosaicImages' => ['Imagick'],
'Imagick::motionBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float', 'channel='=>'int'],
'Imagick::negateImage' => ['bool', 'gray'=>'bool', 'channel='=>'int'],
'Imagick::newImage' => ['bool', 'cols'=>'int', 'rows'=>'int', 'background'=>'mixed', 'format='=>'string'],
'Imagick::newPseudoImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'pseudostring'=>'string'],
'Imagick::next' => ['void'],
'Imagick::nextImage' => ['bool'],
'Imagick::normalizeImage' => ['bool', 'channel='=>'int'],
'Imagick::oilPaintImage' => ['bool', 'radius'=>'float'],
'Imagick::opaquePaintImage' => ['bool', 'target'=>'mixed', 'fill'=>'mixed', 'fuzz'=>'float', 'invert'=>'bool', 'channel='=>'int'],
'Imagick::optimizeImageLayers' => ['bool'],
'Imagick::orderedPosterizeImage' => ['bool', 'threshold_map'=>'string', 'channel='=>'int'],
'Imagick::paintFloodfillImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int', 'channel='=>'int'],
'Imagick::paintOpaqueImage' => ['bool', 'target'=>'mixed', 'fill'=>'mixed', 'fuzz'=>'float', 'channel='=>'int'],
'Imagick::paintTransparentImage' => ['bool', 'target'=>'mixed', 'alpha'=>'float', 'fuzz'=>'float'],
'Imagick::pingImage' => ['bool', 'filename'=>'string'],
'Imagick::pingImageBlob' => ['bool', 'image'=>'string'],
'Imagick::pingImageFile' => ['bool', 'filehandle'=>'resource', 'filename='=>'string'],
'Imagick::polaroidImage' => ['bool', 'properties'=>'ImagickDraw', 'angle'=>'float'],
'Imagick::posterizeImage' => ['bool', 'levels'=>'int', 'dither'=>'bool'],
'Imagick::previewImages' => ['bool', 'preview'=>'int'],
'Imagick::previousImage' => ['bool'],
'Imagick::profileImage' => ['bool', 'name'=>'string', 'profile'=>'string'],
'Imagick::quantizeImage' => ['bool', 'numbercolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Imagick::quantizeImages' => ['bool', 'numbercolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Imagick::queryFontMetrics' => ['array', 'properties'=>'ImagickDraw', 'text'=>'string', 'multiline='=>'bool'],
'Imagick::queryFonts' => ['array', 'pattern='=>'string'],
'Imagick::queryFormats' => ['list<string>', 'pattern='=>'string'],
'Imagick::radialBlurImage' => ['bool', 'angle'=>'float', 'channel='=>'int'],
'Imagick::raiseImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int', 'raise'=>'bool'],
'Imagick::randomThresholdImage' => ['bool', 'low'=>'float', 'high'=>'float', 'channel='=>'int'],
'Imagick::readImage' => ['bool', 'filename'=>'string'],
'Imagick::readImageBlob' => ['bool', 'image'=>'string', 'filename='=>'string'],
'Imagick::readImageFile' => ['bool', 'filehandle'=>'resource', 'filename='=>'string'],
'Imagick::readImages' => ['Imagick', 'filenames'=>'string'],
'Imagick::recolorImage' => ['bool', 'matrix'=>'list<float>'],
'Imagick::reduceNoiseImage' => ['bool', 'radius'=>'float'],
'Imagick::remapImage' => ['bool', 'replacement'=>'Imagick', 'dither'=>'int'],
'Imagick::removeImage' => ['bool'],
'Imagick::removeImageProfile' => ['string', 'name'=>'string'],
'Imagick::render' => ['bool'],
'Imagick::resampleImage' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float', 'filter'=>'int', 'blur'=>'float'],
'Imagick::resetImagePage' => ['bool', 'page'=>'string'],
'Imagick::resetIterator' => [''],
'Imagick::resizeImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'filter'=>'int', 'blur'=>'float', 'bestfit='=>'bool'],
'Imagick::rewind' => ['void'],
'Imagick::rollImage' => ['bool', 'x'=>'int', 'y'=>'int'],
'Imagick::rotateImage' => ['bool', 'background'=>'mixed', 'degrees'=>'float'],
'Imagick::rotationalBlurImage' => ['void', 'angle'=>'string', 'CHANNEL='=>'string'],
'Imagick::roundCorners' => ['bool', 'x_rounding'=>'float', 'y_rounding'=>'float', 'stroke_width='=>'float', 'displace='=>'float', 'size_correction='=>'float'],
'Imagick::roundCornersImage' => ['', 'xRounding'=>'', 'yRounding'=>'', 'strokeWidth'=>'', 'displace'=>'', 'sizeCorrection'=>''],
'Imagick::sampleImage' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::scaleImage' => ['bool', 'cols'=>'int', 'rows'=>'int', 'bestfit='=>'bool'],
'Imagick::segmentImage' => ['bool', 'colorspace'=>'int', 'cluster_threshold'=>'float', 'smooth_threshold'=>'float', 'verbose='=>'bool'],
'Imagick::selectiveBlurImage' => ['void', 'radius'=>'float', 'sigma'=>'float', 'threshold'=>'float', 'CHANNEL'=>'int'],
'Imagick::separateImageChannel' => ['bool', 'channel'=>'int'],
'Imagick::sepiaToneImage' => ['bool', 'threshold'=>'float'],
'Imagick::setAntiAlias' => ['int', 'antialias'=>'bool'],
'Imagick::setBackgroundColor' => ['bool', 'background'=>'mixed'],
'Imagick::setColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::setCompression' => ['bool', 'compression'=>'int'],
'Imagick::setCompressionQuality' => ['bool', 'quality'=>'int'],
'Imagick::setFilename' => ['bool', 'filename'=>'string'],
'Imagick::setFirstIterator' => ['bool'],
'Imagick::setFont' => ['bool', 'font'=>'string'],
'Imagick::setFormat' => ['bool', 'format'=>'string'],
'Imagick::setGravity' => ['bool', 'gravity'=>'int'],
'Imagick::setImage' => ['bool', 'replace'=>'Imagick'],
'Imagick::setImageAlpha' => ['bool', 'alpha'=>'float'],
'Imagick::setImageAlphaChannel' => ['bool', 'mode'=>'int'],
'Imagick::setImageArtifact' => ['bool', 'artifact'=>'string', 'value'=>'string'],
'Imagick::setImageAttribute' => ['void', 'key'=>'string', 'value'=>'string'],
'Imagick::setImageBackgroundColor' => ['bool', 'background'=>'mixed'],
'Imagick::setImageBias' => ['bool', 'bias'=>'float'],
'Imagick::setImageBiasQuantum' => ['void', 'bias'=>'string'],
'Imagick::setImageBluePrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageBorderColor' => ['bool', 'border'=>'mixed'],
'Imagick::setImageChannelDepth' => ['bool', 'channel'=>'int', 'depth'=>'int'],
'Imagick::setImageChannelMask' => ['', 'channel'=>'int'],
'Imagick::setImageClipMask' => ['bool', 'clip_mask'=>'Imagick'],
'Imagick::setImageColormapColor' => ['bool', 'index'=>'int', 'color'=>'ImagickPixel'],
'Imagick::setImageColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::setImageCompose' => ['bool', 'compose'=>'int'],
'Imagick::setImageCompression' => ['bool', 'compression'=>'int'],
'Imagick::setImageCompressionQuality' => ['bool', 'quality'=>'int'],
'Imagick::setImageDelay' => ['bool', 'delay'=>'int'],
'Imagick::setImageDepth' => ['bool', 'depth'=>'int'],
'Imagick::setImageDispose' => ['bool', 'dispose'=>'int'],
'Imagick::setImageExtent' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::setImageFilename' => ['bool', 'filename'=>'string'],
'Imagick::setImageFormat' => ['bool', 'format'=>'string'],
'Imagick::setImageGamma' => ['bool', 'gamma'=>'float'],
'Imagick::setImageGravity' => ['bool', 'gravity'=>'int'],
'Imagick::setImageGreenPrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageIndex' => ['bool', 'index'=>'int'],
'Imagick::setImageInterlaceScheme' => ['bool', 'interlace_scheme'=>'int'],
'Imagick::setImageInterpolateMethod' => ['bool', 'method'=>'int'],
'Imagick::setImageIterations' => ['bool', 'iterations'=>'int'],
'Imagick::setImageMatte' => ['bool', 'matte'=>'bool'],
'Imagick::setImageMatteColor' => ['bool', 'matte'=>'mixed'],
'Imagick::setImageOpacity' => ['bool', 'opacity'=>'float'],
'Imagick::setImageOrientation' => ['bool', 'orientation'=>'int'],
'Imagick::setImagePage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::setImageProfile' => ['bool', 'name'=>'string', 'profile'=>'string'],
'Imagick::setImageProgressMonitor' => ['', 'filename'=>''],
'Imagick::setImageProperty' => ['bool', 'name'=>'string', 'value'=>'string'],
'Imagick::setImageRedPrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageRenderingIntent' => ['bool', 'rendering_intent'=>'int'],
'Imagick::setImageResolution' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'Imagick::setImageScene' => ['bool', 'scene'=>'int'],
'Imagick::setImageTicksPerSecond' => ['bool', 'ticks_per_second'=>'int'],
'Imagick::setImageType' => ['bool', 'image_type'=>'int'],
'Imagick::setImageUnits' => ['bool', 'units'=>'int'],
'Imagick::setImageVirtualPixelMethod' => ['bool', 'method'=>'int'],
'Imagick::setImageWhitePoint' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setInterlaceScheme' => ['bool', 'interlace_scheme'=>'int'],
'Imagick::setIteratorIndex' => ['bool', 'index'=>'int'],
'Imagick::setLastIterator' => ['bool'],
'Imagick::setOption' => ['bool', 'key'=>'string', 'value'=>'string'],
'Imagick::setPage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::setPointSize' => ['bool', 'point_size'=>'float'],
'Imagick::setProgressMonitor' => ['void', 'callback'=>'callable'],
'Imagick::setRegistry' => ['void', 'key'=>'string', 'value'=>'string'],
'Imagick::setResolution' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'Imagick::setResourceLimit' => ['bool', 'type'=>'int', 'limit'=>'int'],
'Imagick::setSamplingFactors' => ['bool', 'factors'=>'list<string>'],
'Imagick::setSize' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::setSizeOffset' => ['bool', 'columns'=>'int', 'rows'=>'int', 'offset'=>'int'],
'Imagick::setType' => ['bool', 'image_type'=>'int'],
'Imagick::shadeImage' => ['bool', 'gray'=>'bool', 'azimuth'=>'float', 'elevation'=>'float'],
'Imagick::shadowImage' => ['bool', 'opacity'=>'float', 'sigma'=>'float', 'x'=>'int', 'y'=>'int'],
'Imagick::sharpenImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::shaveImage' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::shearImage' => ['bool', 'background'=>'mixed', 'x_shear'=>'float', 'y_shear'=>'float'],
'Imagick::sigmoidalContrastImage' => ['bool', 'sharpen'=>'bool', 'alpha'=>'float', 'beta'=>'float', 'channel='=>'int'],
'Imagick::similarityImage' => ['Imagick', 'Imagick'=>'Imagick', '&bestMatch'=>'array', '&similarity'=>'float', 'similarity_threshold'=>'float', 'metric'=>'int'],
'Imagick::sketchImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float'],
'Imagick::smushImages' => ['Imagick', 'stack'=>'string', 'offset'=>'string'],
'Imagick::solarizeImage' => ['bool', 'threshold'=>'int'],
'Imagick::sparseColorImage' => ['bool', 'sparse_method'=>'int', 'arguments'=>'array', 'channel='=>'int'],
'Imagick::spliceImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::spreadImage' => ['bool', 'radius'=>'float'],
'Imagick::statisticImage' => ['void', 'type'=>'int', 'width'=>'int', 'height'=>'int', 'CHANNEL='=>'string'],
'Imagick::steganoImage' => ['Imagick', 'watermark_wand'=>'Imagick', 'offset'=>'int'],
'Imagick::stereoImage' => ['bool', 'offset_wand'=>'Imagick'],
'Imagick::stripImage' => ['bool'],
'Imagick::subImageMatch' => ['Imagick', 'Imagick'=>'Imagick', '&w_offset='=>'array', '&w_similarity='=>'float'],
'Imagick::swirlImage' => ['bool', 'degrees'=>'float'],
'Imagick::textureImage' => ['bool', 'texture_wand'=>'Imagick'],
'Imagick::thresholdImage' => ['bool', 'threshold'=>'float', 'channel='=>'int'],
'Imagick::thumbnailImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'bestfit='=>'bool', 'fill='=>'bool', 'legacy='=>'bool'],
'Imagick::tintImage' => ['bool', 'tint'=>'mixed', 'opacity'=>'mixed'],
'Imagick::transformImage' => ['Imagick', 'crop'=>'string', 'geometry'=>'string'],
'Imagick::transformImageColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::transparentPaintImage' => ['bool', 'target'=>'mixed', 'alpha'=>'float', 'fuzz'=>'float', 'invert'=>'bool'],
'Imagick::transposeImage' => ['bool'],
'Imagick::transverseImage' => ['bool'],
'Imagick::trimImage' => ['bool', 'fuzz'=>'float'],
'Imagick::uniqueImageColors' => ['bool'],
'Imagick::unsharpMaskImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'amount'=>'float', 'threshold'=>'float', 'channel='=>'int'],
'Imagick::valid' => ['bool'],
'Imagick::vignetteImage' => ['bool', 'blackpoint'=>'float', 'whitepoint'=>'float', 'x'=>'int', 'y'=>'int'],
'Imagick::waveImage' => ['bool', 'amplitude'=>'float', 'length'=>'float'],
'Imagick::whiteThresholdImage' => ['bool', 'threshold'=>'mixed'],
'Imagick::writeImage' => ['bool', 'filename='=>'string'],
'Imagick::writeImageFile' => ['bool', 'filehandle'=>'resource'],
'Imagick::writeImages' => ['bool', 'filename'=>'string', 'adjoin'=>'bool'],
'Imagick::writeImagesFile' => ['bool', 'filehandle'=>'resource'],
'ImagickDraw::__construct' => ['void'],
'ImagickDraw::affine' => ['bool', 'affine'=>'array<string, float>'],
'ImagickDraw::annotation' => ['bool', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'ImagickDraw::arc' => ['bool', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float', 'sd'=>'float', 'ed'=>'float'],
'ImagickDraw::bezier' => ['bool', 'coordinates'=>'list<array{x:float, y:float}>'],
'ImagickDraw::circle' => ['bool', 'ox'=>'float', 'oy'=>'float', 'px'=>'float', 'py'=>'float'],
'ImagickDraw::clear' => ['bool'],
'ImagickDraw::clone' => ['ImagickDraw'],
'ImagickDraw::color' => ['bool', 'x'=>'float', 'y'=>'float', 'paintmethod'=>'int'],
'ImagickDraw::comment' => ['bool', 'comment'=>'string'],
'ImagickDraw::composite' => ['bool', 'compose'=>'int', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float', 'compositewand'=>'Imagick'],
'ImagickDraw::destroy' => ['bool'],
'ImagickDraw::ellipse' => ['bool', 'ox'=>'float', 'oy'=>'float', 'rx'=>'float', 'ry'=>'float', 'start'=>'float', 'end'=>'float'],
'ImagickDraw::getBorderColor' => ['ImagickPixel'],
'ImagickDraw::getClipPath' => ['string|false'],
'ImagickDraw::getClipRule' => ['int'],
'ImagickDraw::getClipUnits' => ['int'],
'ImagickDraw::getDensity' => ['?string'],
'ImagickDraw::getFillColor' => ['ImagickPixel'],
'ImagickDraw::getFillOpacity' => ['float'],
'ImagickDraw::getFillRule' => ['int'],
'ImagickDraw::getFont' => ['string|false'],
'ImagickDraw::getFontFamily' => ['string|false'],
'ImagickDraw::getFontResolution' => ['array'],
'ImagickDraw::getFontSize' => ['float'],
'ImagickDraw::getFontStretch' => ['int'],
'ImagickDraw::getFontStyle' => ['int'],
'ImagickDraw::getFontWeight' => ['int'],
'ImagickDraw::getGravity' => ['int'],
'ImagickDraw::getOpacity' => ['float'],
'ImagickDraw::getStrokeAntialias' => ['bool'],
'ImagickDraw::getStrokeColor' => ['ImagickPixel'],
'ImagickDraw::getStrokeDashArray' => ['array'],
'ImagickDraw::getStrokeDashOffset' => ['float'],
'ImagickDraw::getStrokeLineCap' => ['int'],
'ImagickDraw::getStrokeLineJoin' => ['int'],
'ImagickDraw::getStrokeMiterLimit' => ['int'],
'ImagickDraw::getStrokeOpacity' => ['float'],
'ImagickDraw::getStrokeWidth' => ['float'],
'ImagickDraw::getTextAlignment' => ['int'],
'ImagickDraw::getTextAntialias' => ['bool'],
'ImagickDraw::getTextDecoration' => ['int'],
'ImagickDraw::getTextDirection' => ['bool'],
'ImagickDraw::getTextEncoding' => ['string'],
'ImagickDraw::getTextInterlineSpacing' => ['float'],
'ImagickDraw::getTextInterwordSpacing' => ['float'],
'ImagickDraw::getTextKerning' => ['float'],
'ImagickDraw::getTextUnderColor' => ['ImagickPixel'],
'ImagickDraw::getVectorGraphics' => ['string'],
'ImagickDraw::line' => ['bool', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float'],
'ImagickDraw::matte' => ['bool', 'x'=>'float', 'y'=>'float', 'paintmethod'=>'int'],
'ImagickDraw::pathClose' => ['bool'],
'ImagickDraw::pathCurveToAbsolute' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierAbsolute' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierRelative' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierSmoothRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToRelative' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToSmoothAbsolute' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToSmoothRelative' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathEllipticArcAbsolute' => ['bool', 'rx'=>'float', 'ry'=>'float', 'x_axis_rotation'=>'float', 'large_arc_flag'=>'bool', 'sweep_flag'=>'bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathEllipticArcRelative' => ['bool', 'rx'=>'float', 'ry'=>'float', 'x_axis_rotation'=>'float', 'large_arc_flag'=>'bool', 'sweep_flag'=>'bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathFinish' => ['bool'],
'ImagickDraw::pathLineToAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathLineToHorizontalAbsolute' => ['bool', 'x'=>'float'],
'ImagickDraw::pathLineToHorizontalRelative' => ['bool', 'x'=>'float'],
'ImagickDraw::pathLineToRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathLineToVerticalAbsolute' => ['bool', 'y'=>'float'],
'ImagickDraw::pathLineToVerticalRelative' => ['bool', 'y'=>'float'],
'ImagickDraw::pathMoveToAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathMoveToRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathStart' => ['bool'],
'ImagickDraw::point' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::polygon' => ['bool', 'coordinates'=>'list<array{x:float, y:float}>'],
'ImagickDraw::polyline' => ['bool', 'coordinates'=>'list<array{x:float, y:float}>'],
'ImagickDraw::pop' => ['bool'],
'ImagickDraw::popClipPath' => ['bool'],
'ImagickDraw::popDefs' => ['bool'],
'ImagickDraw::popPattern' => ['bool'],
'ImagickDraw::push' => ['bool'],
'ImagickDraw::pushClipPath' => ['bool', 'clip_mask_id'=>'string'],
'ImagickDraw::pushDefs' => ['bool'],
'ImagickDraw::pushPattern' => ['bool', 'pattern_id'=>'string', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'ImagickDraw::rectangle' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'ImagickDraw::render' => ['bool'],
'ImagickDraw::resetVectorGraphics' => ['void'],
'ImagickDraw::rotate' => ['bool', 'degrees'=>'float'],
'ImagickDraw::roundRectangle' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'rx'=>'float', 'ry'=>'float'],
'ImagickDraw::scale' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::setBorderColor' => ['bool', 'color'=>'ImagickPixel|string'],
'ImagickDraw::setClipPath' => ['bool', 'clip_mask'=>'string'],
'ImagickDraw::setClipRule' => ['bool', 'fill_rule'=>'int'],
'ImagickDraw::setClipUnits' => ['bool', 'clip_units'=>'int'],
'ImagickDraw::setDensity' => ['bool', 'density_string'=>'string'],
'ImagickDraw::setFillAlpha' => ['bool', 'opacity'=>'float'],
'ImagickDraw::setFillColor' => ['bool', 'fill_pixel'=>'ImagickPixel|string'],
'ImagickDraw::setFillOpacity' => ['bool', 'fillopacity'=>'float'],
'ImagickDraw::setFillPatternURL' => ['bool', 'fill_url'=>'string'],
'ImagickDraw::setFillRule' => ['bool', 'fill_rule'=>'int'],
'ImagickDraw::setFont' => ['bool', 'font_name'=>'string'],
'ImagickDraw::setFontFamily' => ['bool', 'font_family'=>'string'],
'ImagickDraw::setFontResolution' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::setFontSize' => ['bool', 'pointsize'=>'float'],
'ImagickDraw::setFontStretch' => ['bool', 'fontstretch'=>'int'],
'ImagickDraw::setFontStyle' => ['bool', 'style'=>'int'],
'ImagickDraw::setFontWeight' => ['bool', 'font_weight'=>'int'],
'ImagickDraw::setGravity' => ['bool', 'gravity'=>'int'],
'ImagickDraw::setOpacity' => ['void', 'opacity'=>'float'],
'ImagickDraw::setResolution' => ['void', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'ImagickDraw::setStrokeAlpha' => ['bool', 'opacity'=>'float'],
'ImagickDraw::setStrokeAntialias' => ['bool', 'stroke_antialias'=>'bool'],
'ImagickDraw::setStrokeColor' => ['bool', 'stroke_pixel'=>'ImagickPixel|string'],
'ImagickDraw::setStrokeDashArray' => ['bool', 'dasharray'=>'list<int|float>'],
'ImagickDraw::setStrokeDashOffset' => ['bool', 'dash_offset'=>'float'],
'ImagickDraw::setStrokeLineCap' => ['bool', 'linecap'=>'int'],
'ImagickDraw::setStrokeLineJoin' => ['bool', 'linejoin'=>'int'],
'ImagickDraw::setStrokeMiterLimit' => ['bool', 'miterlimit'=>'int'],
'ImagickDraw::setStrokeOpacity' => ['bool', 'stroke_opacity'=>'float'],
'ImagickDraw::setStrokePatternURL' => ['bool', 'stroke_url'=>'string'],
'ImagickDraw::setStrokeWidth' => ['bool', 'stroke_width'=>'float'],
'ImagickDraw::setTextAlignment' => ['bool', 'alignment'=>'int'],
'ImagickDraw::setTextAntialias' => ['bool', 'antialias'=>'bool'],
'ImagickDraw::setTextDecoration' => ['bool', 'decoration'=>'int'],
'ImagickDraw::setTextDirection' => ['bool', 'direction'=>'int'],
'ImagickDraw::setTextEncoding' => ['bool', 'encoding'=>'string'],
'ImagickDraw::setTextInterlineSpacing' => ['void', 'spacing'=>'float'],
'ImagickDraw::setTextInterwordSpacing' => ['void', 'spacing'=>'float'],
'ImagickDraw::setTextKerning' => ['void', 'kerning'=>'float'],
'ImagickDraw::setTextUnderColor' => ['bool', 'under_color'=>'ImagickPixel|string'],
'ImagickDraw::setVectorGraphics' => ['bool', 'xml'=>'string'],
'ImagickDraw::setViewbox' => ['bool', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int'],
'ImagickDraw::skewX' => ['bool', 'degrees'=>'float'],
'ImagickDraw::skewY' => ['bool', 'degrees'=>'float'],
'ImagickDraw::translate' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickKernel::addKernel' => ['void', 'ImagickKernel'=>'ImagickKernel'],
'ImagickKernel::addUnityKernel' => ['void'],
'ImagickKernel::fromBuiltin' => ['ImagickKernel', 'kernelType'=>'string', 'kernelString'=>'string'],
'ImagickKernel::fromMatrix' => ['ImagickKernel', 'matrix'=>'list<list<float>>', 'origin='=>'array'],
'ImagickKernel::getMatrix' => ['list<list<float|false>>'],
'ImagickKernel::scale' => ['void'],
'ImagickKernel::separate' => ['ImagickKernel[]'],
'ImagickKernel::seperate' => ['void'],
'ImagickPixel::__construct' => ['void', 'color='=>'string'],
'ImagickPixel::clear' => ['bool'],
'ImagickPixel::clone' => ['void'],
'ImagickPixel::destroy' => ['bool'],
'ImagickPixel::getColor' => ['array{r: int|float, g: int|float, b: int|float, a: int|float}', 'normalized='=>'int'],
'ImagickPixel::getColorAsString' => ['string'],
'ImagickPixel::getColorCount' => ['int'],
'ImagickPixel::getColorQuantum' => ['mixed'],
'ImagickPixel::getColorValue' => ['float', 'color'=>'int'],
'ImagickPixel::getColorValueQuantum' => ['mixed'],
'ImagickPixel::getHSL' => ['array{hue: float, saturation: float, luminosity: float}'],
'ImagickPixel::getIndex' => ['int'],
'ImagickPixel::isPixelSimilar' => ['bool', 'color'=>'ImagickPixel', 'fuzz'=>'float'],
'ImagickPixel::isPixelSimilarQuantum' => ['bool', 'color'=>'string', 'fuzz='=>'string'],
'ImagickPixel::isSimilar' => ['bool', 'color'=>'ImagickPixel', 'fuzz'=>'float'],
'ImagickPixel::setColor' => ['bool', 'color'=>'string'],
'ImagickPixel::setcolorcount' => ['void', 'colorCount'=>'string'],
'ImagickPixel::setColorFromPixel' => ['bool', 'srcPixel'=>'ImagickPixel'],
'ImagickPixel::setColorValue' => ['bool', 'color'=>'int', 'value'=>'float'],
'ImagickPixel::setColorValueQuantum' => ['void', 'color'=>'int', 'value'=>'mixed'],
'ImagickPixel::setHSL' => ['bool', 'hue'=>'float', 'saturation'=>'float', 'luminosity'=>'float'],
'ImagickPixel::setIndex' => ['void', 'index'=>'int'],
'ImagickPixelIterator::__construct' => ['void', 'wand'=>'Imagick'],
'ImagickPixelIterator::clear' => ['bool'],
'ImagickPixelIterator::current' => ['mixed'],
'ImagickPixelIterator::destroy' => ['bool'],
'ImagickPixelIterator::getCurrentIteratorRow' => ['array'],
'ImagickPixelIterator::getIteratorRow' => ['int'],
'ImagickPixelIterator::getNextIteratorRow' => ['array'],
'ImagickPixelIterator::getpixeliterator' => ['', 'Imagick'=>'Imagick'],
'ImagickPixelIterator::getpixelregioniterator' => ['', 'Imagick'=>'Imagick', 'x'=>'', 'y'=>'', 'columns'=>'', 'rows'=>''],
'ImagickPixelIterator::getPreviousIteratorRow' => ['array'],
'ImagickPixelIterator::key' => ['int|string'],
'ImagickPixelIterator::newPixelIterator' => ['bool', 'wand'=>'Imagick'],
'ImagickPixelIterator::newPixelRegionIterator' => ['bool', 'wand'=>'Imagick', 'x'=>'int', 'y'=>'int', 'columns'=>'int', 'rows'=>'int'],
'ImagickPixelIterator::next' => ['void'],
'ImagickPixelIterator::resetIterator' => ['bool'],
'ImagickPixelIterator::rewind' => ['void'],
'ImagickPixelIterator::setIteratorFirstRow' => ['bool'],
'ImagickPixelIterator::setIteratorLastRow' => ['bool'],
'ImagickPixelIterator::setIteratorRow' => ['bool', 'row'=>'int'],
'ImagickPixelIterator::syncIterator' => ['bool'],
'ImagickPixelIterator::valid' => ['bool'],
'imap_8bit' => ['string|false', 'string'=>'string'],
'imap_alerts' => ['array|false'],
'imap_append' => ['bool', 'imap'=>'resource', 'folder'=>'string', 'message'=>'string', 'options='=>'string', 'internal_date='=>'string'],
'imap_base64' => ['string|false', 'string'=>'string'],
'imap_binary' => ['string|false', 'string'=>'string'],
'imap_body' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_bodystruct' => ['stdClass|false', 'imap'=>'resource', 'message_num'=>'int', 'section'=>'string'],
'imap_check' => ['stdClass|false', 'imap'=>'resource'],
'imap_clearflag_full' => ['bool', 'imap'=>'resource', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_close' => ['bool', 'imap'=>'resource', 'flags='=>'int'],
'imap_create' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_createmailbox' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_delete' => ['bool', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_deletemailbox' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_errors' => ['array|false'],
'imap_expunge' => ['bool', 'imap'=>'resource'],
'imap_fetch_overview' => ['array|false', 'imap'=>'resource', 'sequence'=>'string', 'flags='=>'int'],
'imap_fetchbody' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'section'=>'string', 'flags='=>'int'],
'imap_fetchheader' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_fetchmime' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'section'=>'string', 'flags='=>'int'],
'imap_fetchstructure' => ['stdClass|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_fetchtext' => ['string|false', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_gc' => ['bool', 'imap'=>'resource', 'flags'=>'int'],
'imap_get_quota' => ['array|false', 'imap'=>'resource', 'quota_root'=>'string'],
'imap_get_quotaroot' => ['array|false', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_getacl' => ['array|false', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_getmailboxes' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_getsubscribed' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_header' => ['stdClass|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'from_length='=>'int', 'subject_length='=>'int', 'default_host='=>'string'],
'imap_headerinfo' => ['stdClass|false', 'imap'=>'resource', 'message_num'=>'int', 'from_length='=>'int', 'subject_length='=>'int', 'default_host='=>'string|null'],
'imap_headers' => ['array|false', 'imap'=>'resource'],
'imap_last_error' => ['string|false'],
'imap_list' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_listmailbox' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_listscan' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_listsubscribed' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_lsub' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string'],
'imap_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string', 'cc='=>'string', 'bcc='=>'string', 'return_path='=>'string'],
'imap_mail_compose' => ['string|false', 'envelope'=>'array', 'bodies'=>'array'],
'imap_mail_copy' => ['bool', 'imap'=>'resource', 'message_nums'=>'string', 'mailbox'=>'string', 'flags='=>'int'],
'imap_mail_move' => ['bool', 'imap'=>'resource', 'message_nums'=>'string', 'mailbox'=>'string', 'flags='=>'int'],
'imap_mailboxmsginfo' => ['stdClass|false', 'imap'=>'resource'],
'imap_mime_header_decode' => ['array|false', 'string'=>'string'],
'imap_msgno' => ['int|false', 'imap'=>'resource', 'message_uid'=>'int'],
'imap_mutf7_to_utf8' => ['string|false', 'string'=>'string'],
'imap_num_msg' => ['int|false', 'imap'=>'resource'],
'imap_num_recent' => ['int|false', 'imap'=>'resource'],
'imap_open' => ['resource|false', 'mailbox'=>'string', 'user'=>'string', 'password'=>'string', 'flags='=>'int', 'retries='=>'int', 'options='=>'?array'],
'imap_ping' => ['bool', 'imap'=>'resource'],
'imap_qprint' => ['string|false', 'string'=>'string'],
'imap_rename' => ['bool', 'imap'=>'resource', 'from'=>'string', 'to'=>'string'],
'imap_renamemailbox' => ['bool', 'imap'=>'resource', 'from'=>'string', 'to'=>'string'],
'imap_reopen' => ['bool', 'imap'=>'resource', 'mailbox'=>'string', 'flags='=>'int', 'retries='=>'int'],
'imap_rfc822_parse_adrlist' => ['array', 'string'=>'string', 'default_hostname'=>'string'],
'imap_rfc822_parse_headers' => ['stdClass', 'headers'=>'string', 'default_hostname='=>'string'],
'imap_rfc822_write_address' => ['string|false', 'mailbox'=>'?string', 'hostname'=>'?string', 'personal'=>'?string'],
'imap_savebody' => ['bool', 'imap'=>'resource', 'file'=>'string|resource', 'message_num'=>'int', 'section='=>'string', 'flags='=>'int'],
'imap_scan' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_scanmailbox' => ['array|false', 'imap'=>'resource', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_search' => ['array|false', 'imap'=>'resource', 'criteria'=>'string', 'flags='=>'int', 'charset='=>'string'],
'imap_set_quota' => ['bool', 'imap'=>'resource', 'quota_root'=>'string', 'mailbox_size'=>'int'],
'imap_setacl' => ['bool', 'imap'=>'resource', 'mailbox'=>'string', 'user_id'=>'string', 'rights'=>'string'],
'imap_setflag_full' => ['bool', 'imap'=>'resource', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_sort' => ['array|false', 'imap'=>'resource', 'criteria'=>'int', 'reverse'=>'int', 'flags='=>'int', 'search_criteria='=>'string', 'charset='=>'string'],
'imap_status' => ['stdClass|false', 'imap'=>'resource', 'mailbox'=>'string', 'flags'=>'int'],
'imap_subscribe' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_thread' => ['array|false', 'imap'=>'resource', 'flags='=>'int'],
'imap_timeout' => ['int|bool', 'timeout_type'=>'int', 'timeout='=>'int'],
'imap_uid' => ['int|false', 'imap'=>'resource', 'message_num'=>'int'],
'imap_undelete' => ['bool', 'imap'=>'resource', 'message_num'=>'int', 'flags='=>'int'],
'imap_unsubscribe' => ['bool', 'imap'=>'resource', 'mailbox'=>'string'],
'imap_utf7_decode' => ['string|false', 'string'=>'string'],
'imap_utf7_encode' => ['string', 'string'=>'string'],
'imap_utf8' => ['string', 'mime_encoded_text'=>'string'],
'imap_utf8_to_mutf7' => ['string|false', 'string'=>'string'],
'implode' => ['string', 'separator'=>'string', 'array'=>'array'],
'implode\'1' => ['string', 'separator'=>'array'],
'import_request_variables' => ['bool', 'types'=>'string', 'prefix='=>'string'],
'in_array' => ['bool', 'needle'=>'mixed', 'haystack'=>'array', 'strict='=>'bool'],
'inclued_get_data' => ['array'],
'inet_ntop' => ['string|false', 'ip'=>'string'],
'inet_pton' => ['string|false', 'ip'=>'string'],
'InfiniteIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'InfiniteIterator::current' => ['mixed'],
'InfiniteIterator::getInnerIterator' => ['Traversable'],
'InfiniteIterator::key' => ['bool|float|int|string'],
'InfiniteIterator::next' => ['void'],
'InfiniteIterator::rewind' => ['void'],
'InfiniteIterator::valid' => ['bool'],
'inflate_add' => ['string|false', 'context'=>'resource', 'data'=>'string', 'flush_mode='=>'int'],
'inflate_get_read_len' => ['int|false', 'context'=>'resource'],
'inflate_get_status' => ['int|false', 'context'=>'resource'],
'inflate_init' => ['resource|false', 'encoding'=>'int', 'options='=>'array'],
'ingres_autocommit' => ['bool', 'link'=>'resource'],
'ingres_autocommit_state' => ['bool', 'link'=>'resource'],
'ingres_charset' => ['string', 'link'=>'resource'],
'ingres_close' => ['bool', 'link'=>'resource'],
'ingres_commit' => ['bool', 'link'=>'resource'],
'ingres_connect' => ['resource', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'options='=>'array'],
'ingres_cursor' => ['string', 'result'=>'resource'],
'ingres_errno' => ['int', 'link='=>'resource'],
'ingres_error' => ['string', 'link='=>'resource'],
'ingres_errsqlstate' => ['string', 'link='=>'resource'],
'ingres_escape_string' => ['string', 'link'=>'resource', 'source_string'=>'string'],
'ingres_execute' => ['bool', 'result'=>'resource', 'params='=>'array', 'types='=>'string'],
'ingres_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'ingres_fetch_assoc' => ['array', 'result'=>'resource'],
'ingres_fetch_object' => ['object', 'result'=>'resource', 'result_type='=>'int'],
'ingres_fetch_proc_return' => ['int', 'result'=>'resource'],
'ingres_fetch_row' => ['array', 'result'=>'resource'],
'ingres_field_length' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_name' => ['string', 'result'=>'resource', 'index'=>'int'],
'ingres_field_nullable' => ['bool', 'result'=>'resource', 'index'=>'int'],
'ingres_field_precision' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_scale' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_type' => ['string', 'result'=>'resource', 'index'=>'int'],
'ingres_free_result' => ['bool', 'result'=>'resource'],
'ingres_next_error' => ['bool', 'link='=>'resource'],
'ingres_num_fields' => ['int', 'result'=>'resource'],
'ingres_num_rows' => ['int', 'result'=>'resource'],
'ingres_pconnect' => ['resource', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'options='=>'array'],
'ingres_prepare' => ['mixed', 'link'=>'resource', 'query'=>'string'],
'ingres_query' => ['mixed', 'link'=>'resource', 'query'=>'string', 'params='=>'array', 'types='=>'string'],
'ingres_result_seek' => ['bool', 'result'=>'resource', 'position'=>'int'],
'ingres_rollback' => ['bool', 'link'=>'resource'],
'ingres_set_environment' => ['bool', 'link'=>'resource', 'options'=>'array'],
'ingres_unbuffered_query' => ['mixed', 'link'=>'resource', 'query'=>'string', 'params='=>'array', 'types='=>'string'],
'ini_alter' => ['string|false', 'option'=>'string', 'value'=>'string'],
'ini_get' => ['string|false', 'option'=>'string'],
'ini_get_all' => ['array|false', 'extension='=>'?string', 'details='=>'bool'],
'ini_restore' => ['void', 'option'=>'string'],
'ini_set' => ['string|false', 'option'=>'string', 'value'=>'string'],
'inotify_add_watch' => ['int', 'inotify_instance'=>'resource', 'pathname'=>'string', 'mask'=>'int'],
'inotify_init' => ['resource|false'],
'inotify_queue_len' => ['int', 'inotify_instance'=>'resource'],
'inotify_read' => ['array|false', 'inotify_instance'=>'resource'],
'inotify_rm_watch' => ['bool', 'inotify_instance'=>'resource', 'watch_descriptor'=>'int'],
'intdiv' => ['int', 'num1'=>'int', 'num2'=>'int'],
'interface_exists' => ['bool', 'interface'=>'string', 'autoload='=>'bool'],
'intl_error_name' => ['string', 'errorCode'=>'int'],
'intl_get_error_code' => ['int'],
'intl_get_error_message' => ['string'],
'intl_is_failure' => ['bool', 'errorCode'=>'int'],
'IntlBreakIterator::__construct' => ['void'],
'IntlBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::current' => ['int'],
'IntlBreakIterator::first' => ['int'],
'IntlBreakIterator::following' => ['int', 'offset'=>'int'],
'IntlBreakIterator::getErrorCode' => ['int'],
'IntlBreakIterator::getErrorMessage' => ['string'],
'IntlBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'int'],
'IntlBreakIterator::getText' => ['string'],
'IntlBreakIterator::isBoundary' => ['bool', 'offset'=>'int'],
'IntlBreakIterator::last' => ['int'],
'IntlBreakIterator::next' => ['int', 'offset='=>'int'],
'IntlBreakIterator::preceding' => ['int', 'offset'=>'int'],
'IntlBreakIterator::previous' => ['int'],
'IntlBreakIterator::setText' => ['bool', 'text'=>'string'],
'intlcal_add' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int', 'value'=>'int'],
'intlcal_after' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_before' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_clear' => ['bool', 'calendar'=>'IntlCalendar', 'field='=>'int'],
'intlcal_create_instance' => ['IntlCalendar', 'timezone='=>'mixed', 'locale='=>'string'],
'intlcal_equals' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_field_difference' => ['int', 'calendar'=>'IntlCalendar', 'timestamp'=>'float', 'field'=>'int'],
'intlcal_from_date_time' => ['IntlCalendar', 'datetime'=>'DateTime|string'],
'intlcal_get' => ['mixed', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_maximum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_available_locales' => ['array'],
'intlcal_get_day_of_week_type' => ['int', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_get_first_day_of_week' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_greatest_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_keyword_values_for_locale' => ['Iterator|false', 'keyword'=>'string', 'locale'=>'string', 'onlyCommon'=>'bool'],
'intlcal_get_least_maximum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_locale' => ['string', 'calendar'=>'IntlCalendar', 'type'=>'int'],
'intlcal_get_maximum' => ['int|false', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_minimal_days_in_first_week' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_now' => ['float'],
'intlcal_get_repeated_wall_time_option' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_skipped_wall_time_option' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_time' => ['float', 'calendar'=>'IntlCalendar'],
'intlcal_get_time_zone' => ['IntlTimeZone', 'calendar'=>'IntlCalendar'],
'intlcal_get_type' => ['string', 'calendar'=>'IntlCalendar'],
'intlcal_get_weekend_transition' => ['int', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'string'],
'intlcal_in_daylight_time' => ['bool', 'calendar'=>'IntlCalendar'],
'intlcal_is_equivalent_to' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_is_lenient' => ['bool', 'calendar'=>'IntlCalendar'],
'intlcal_is_set' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_is_weekend' => ['bool', 'calendar'=>'IntlCalendar', 'timestamp='=>'float'],
'intlcal_roll' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int', 'value'=>'mixed'],
'intlcal_set' => ['bool', 'calendar'=>'IntlCalendar', 'year'=>'int', 'month'=>'int'],
'intlcal_set\'1' => ['bool', 'calendar'=>'IntlCalendar', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'intlcal_set_first_day_of_week' => ['bool', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_set_lenient' => ['bool', 'calendar'=>'IntlCalendar', 'lenient'=>'bool'],
'intlcal_set_repeated_wall_time_option' => ['bool', 'calendar'=>'IntlCalendar', 'option'=>'int'],
'intlcal_set_skipped_wall_time_option' => ['bool', 'calendar'=>'IntlCalendar', 'option'=>'int'],
'intlcal_set_time' => ['bool', 'calendar'=>'IntlCalendar', 'timestamp'=>'float'],
'intlcal_set_time_zone' => ['bool', 'calendar'=>'IntlCalendar', 'timezone'=>'mixed'],
'intlcal_to_date_time' => ['DateTime|false', 'calendar'=>'IntlCalendar'],
'IntlCalendar::__construct' => ['void'],
'IntlCalendar::add' => ['bool', 'field'=>'int', 'amount'=>'int'],
'IntlCalendar::after' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::before' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::clear' => ['bool', 'field='=>'int'],
'IntlCalendar::createInstance' => ['IntlCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'IntlCalendar::equals' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::fieldDifference' => ['int', 'when'=>'float', 'field'=>'int'],
'IntlCalendar::fromDateTime' => ['IntlCalendar', 'dateTime'=>'DateTime|string'],
'IntlCalendar::get' => ['int', 'field'=>'int'],
'IntlCalendar::getActualMaximum' => ['int', 'field'=>'int'],
'IntlCalendar::getActualMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getAvailableLocales' => ['array'],
'IntlCalendar::getDayOfWeekType' => ['int', 'dayOfWeek'=>'int'],
'IntlCalendar::getErrorCode' => ['int'],
'IntlCalendar::getErrorMessage' => ['string'],
'IntlCalendar::getFirstDayOfWeek' => ['int'],
'IntlCalendar::getGreatestMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getKeywordValuesForLocale' => ['Iterator|false', 'key'=>'string', 'locale'=>'string', 'commonlyUsed'=>'bool'],
'IntlCalendar::getLeastMaximum' => ['int', 'field'=>'int'],
'IntlCalendar::getLocale' => ['string', 'localeType'=>'int'],
'IntlCalendar::getMaximum' => ['int|false', 'field'=>'int'],
'IntlCalendar::getMinimalDaysInFirstWeek' => ['int'],
'IntlCalendar::getMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getNow' => ['float'],
'IntlCalendar::getRepeatedWallTimeOption' => ['int'],
'IntlCalendar::getSkippedWallTimeOption' => ['int'],
'IntlCalendar::getTime' => ['float'],
'IntlCalendar::getTimeZone' => ['IntlTimeZone'],
'IntlCalendar::getType' => ['string'],
'IntlCalendar::getWeekendTransition' => ['int', 'dayOfWeek'=>'string'],
'IntlCalendar::inDaylightTime' => ['bool'],
'IntlCalendar::isEquivalentTo' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::isLenient' => ['bool'],
'IntlCalendar::isSet' => ['bool', 'field'=>'int'],
'IntlCalendar::isWeekend' => ['bool', 'date='=>'float'],
'IntlCalendar::roll' => ['bool', 'field'=>'int', 'amountOrUpOrDown'=>'mixed'],
'IntlCalendar::set' => ['bool', 'field'=>'int', 'value'=>'int'],
'IntlCalendar::set\'1' => ['bool', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'IntlCalendar::setFirstDayOfWeek' => ['bool', 'dayOfWeek'=>'int'],
'IntlCalendar::setLenient' => ['bool', 'isLenient'=>'string'],
'IntlCalendar::setMinimalDaysInFirstWeek' => ['bool', 'minimalDays'=>'int'],
'IntlCalendar::setRepeatedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlCalendar::setSkippedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlCalendar::setTime' => ['bool', 'date'=>'float'],
'IntlCalendar::setTimeZone' => ['bool', 'timeZone'=>'mixed'],
'IntlCalendar::toDateTime' => ['DateTime|false'],
'IntlChar::charAge' => ['array', 'char'=>'int|string'],
'IntlChar::charDigitValue' => ['int', 'codepoint'=>'mixed'],
'IntlChar::charDirection' => ['int', 'codepoint'=>'mixed'],
'IntlChar::charFromName' => ['?int', 'name'=>'string', 'namechoice='=>'int'],
'IntlChar::charMirror' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::charName' => ['string', 'char'=>'int|string', 'namechoice='=>'int'],
'IntlChar::charType' => ['int', 'codepoint'=>'mixed'],
'IntlChar::chr' => ['string', 'codepoint'=>'mixed'],
'IntlChar::digit' => ['int|false', 'char'=>'int|string', 'radix='=>'int'],
'IntlChar::enumCharNames' => ['void', 'start'=>'mixed', 'limit'=>'mixed', 'callback'=>'callable', 'nameChoice='=>'int'],
'IntlChar::enumCharTypes' => ['void', 'cb='=>'callable'],
'IntlChar::foldCase' => ['int|string', 'char'=>'int|string', 'options='=>'int'],
'IntlChar::forDigit' => ['int', 'digit'=>'int', 'radix'=>'int'],
'IntlChar::getBidiPairedBracket' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::getBlockCode' => ['int', 'char'=>'int|string'],
'IntlChar::getCombiningClass' => ['int', 'codepoint'=>'mixed'],
'IntlChar::getFC_NFKC_Closure' => ['string', 'char'=>'int|string'],
'IntlChar::getIntPropertyMaxValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyMinValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyMxValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyValue' => ['int', 'char'=>'int|string', 'property'=>'int'],
'IntlChar::getNumericValue' => ['float', 'char'=>'int|string'],
'IntlChar::getPropertyEnum' => ['int', 'alias'=>'string'],
'IntlChar::getPropertyName' => ['string|false', 'property'=>'int', 'namechoice='=>'int'],
'IntlChar::getPropertyValueEnum' => ['int', 'property'=>'int', 'name'=>'string'],
'IntlChar::getPropertyValueName' => ['string|false', 'prop'=>'int', 'value'=>'int', 'namechoice='=>'int'],
'IntlChar::getUnicodeVersion' => ['array'],
'IntlChar::hasBinaryProperty' => ['bool', 'char'=>'int|string', 'property'=>'int'],
'IntlChar::isalnum' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isalpha' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isbase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isblank' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::iscntrl' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isdefined' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isdigit' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isgraph' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDIgnorable' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDPart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDStart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isISOControl' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaIDPart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaIDStart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaSpaceChar' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::islower' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isMirrored' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isprint' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::ispunct' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isspace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::istitle' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUAlphabetic' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isULowercase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isupper' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUUppercase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUWhiteSpace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isWhitespace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isxdigit' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::ord' => ['int', 'character'=>'mixed'],
'IntlChar::tolower' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::totitle' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::toupper' => ['mixed', 'codepoint'=>'mixed'],
'IntlCodePointBreakIterator::__construct' => ['void'],
'IntlCodePointBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlCodePointBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::current' => ['int'],
'IntlCodePointBreakIterator::first' => ['int'],
'IntlCodePointBreakIterator::following' => ['int', 'offset'=>'string'],
'IntlCodePointBreakIterator::getErrorCode' => ['int'],
'IntlCodePointBreakIterator::getErrorMessage' => ['string'],
'IntlCodePointBreakIterator::getLastCodePoint' => ['int'],
'IntlCodePointBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlCodePointBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'string'],
'IntlCodePointBreakIterator::getText' => ['string'],
'IntlCodePointBreakIterator::isBoundary' => ['bool', 'offset'=>'string'],
'IntlCodePointBreakIterator::last' => ['int'],
'IntlCodePointBreakIterator::next' => ['int', 'offset='=>'string'],
'IntlCodePointBreakIterator::preceding' => ['int', 'offset'=>'string'],
'IntlCodePointBreakIterator::previous' => ['int'],
'IntlCodePointBreakIterator::setText' => ['bool', 'text'=>'string'],
'IntlDateFormatter::__construct' => ['void', 'locale'=>'?string', 'datetype'=>'?int', 'timetype'=>'?int', 'timezone='=>'null|string|IntlTimeZone|DateTimeZone', 'calendar='=>'null|int|IntlCalendar', 'pattern='=>'string'],
'IntlDateFormatter::create' => ['IntlDateFormatter|false', 'locale'=>'?string', 'datetype'=>'?int', 'timetype'=>'?int', 'timezone='=>'null|string|IntlTimeZone|DateTimeZone', 'calendar='=>'int|IntlCalendar', 'pattern='=>'string'],
'IntlDateFormatter::format' => ['string|false', 'args'=>''],
'IntlDateFormatter::formatObject' => ['string|false', 'object'=>'object', 'format='=>'mixed', 'locale='=>'string'],
'IntlDateFormatter::getCalendar' => ['int'],
'IntlDateFormatter::getCalendarObject' => ['IntlCalendar'],
'IntlDateFormatter::getDateType' => ['int'],
'IntlDateFormatter::getErrorCode' => ['int'],
'IntlDateFormatter::getErrorMessage' => ['string'],
'IntlDateFormatter::getLocale' => ['string|false'],
'IntlDateFormatter::getPattern' => ['string'],
'IntlDateFormatter::getTimeType' => ['int'],
'IntlDateFormatter::getTimeZone' => ['IntlTimeZone|false'],
'IntlDateFormatter::getTimeZoneId' => ['string'],
'IntlDateFormatter::isLenient' => ['bool'],
'IntlDateFormatter::localtime' => ['array', 'text_to_parse'=>'string', '&w_parse_pos='=>'int'],
'IntlDateFormatter::parse' => ['int|false', 'text_to_parse'=>'string', '&rw_parse_pos='=>'int'],
'IntlDateFormatter::setCalendar' => ['bool', 'calendar'=>''],
'IntlDateFormatter::setLenient' => ['bool', 'lenient'=>'bool'],
'IntlDateFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'IntlDateFormatter::setTimeZone' => ['bool', 'timezone'=>''],
'IntlDateFormatter::setTimeZoneId' => ['bool', 'zone'=>'string', 'fmt='=>'IntlDateFormatter'],
'IntlException::__clone' => ['void'],
'IntlException::__construct' => ['void'],
'IntlException::__toString' => ['string'],
'IntlException::__wakeup' => ['void'],
'IntlException::getCode' => ['int'],
'IntlException::getFile' => ['string'],
'IntlException::getLine' => ['int'],
'IntlException::getMessage' => ['string'],
'IntlException::getPrevious' => ['?Throwable'],
'IntlException::getTrace' => ['list<array<string,mixed>>'],
'IntlException::getTraceAsString' => ['string'],
'intlgregcal_create_instance' => ['IntlGregorianCalendar', 'timezoneOrYear='=>'mixed', 'localeOrMonth='=>'string'],
'intlgregcal_get_gregorian_change' => ['float', 'calendar'=>'IntlGregorianCalendar'],
'intlgregcal_is_leap_year' => ['bool', 'calendar'=>'int'],
'intlgregcal_set_gregorian_change' => ['void', 'calendar'=>'IntlGregorianCalendar', 'timestamp'=>'float'],
'IntlGregorianCalendar::__construct' => ['void'],
'IntlGregorianCalendar::add' => ['bool', 'field'=>'int', 'amount'=>'int'],
'IntlGregorianCalendar::after' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::before' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::clear' => ['bool', 'field='=>'int'],
'IntlGregorianCalendar::createInstance' => ['IntlGregorianCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'IntlGregorianCalendar::equals' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::fieldDifference' => ['int', 'when'=>'float', 'field'=>'int'],
'IntlGregorianCalendar::fromDateTime' => ['IntlCalendar', 'dateTime'=>'DateTime|string'],
'IntlGregorianCalendar::get' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getActualMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getActualMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getAvailableLocales' => ['array'],
'IntlGregorianCalendar::getDayOfWeekType' => ['int', 'dayOfWeek'=>'int'],
'IntlGregorianCalendar::getErrorCode' => ['int'],
'IntlGregorianCalendar::getErrorMessage' => ['string'],
'IntlGregorianCalendar::getFirstDayOfWeek' => ['int'],
'IntlGregorianCalendar::getGreatestMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getGregorianChange' => ['float'],
'IntlGregorianCalendar::getKeywordValuesForLocale' => ['Iterator', 'key'=>'string', 'locale'=>'string', 'commonlyUsed'=>'bool'],
'IntlGregorianCalendar::getLeastMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getLocale' => ['string', 'localeType'=>'int'],
'IntlGregorianCalendar::getMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getMinimalDaysInFirstWeek' => ['int'],
'IntlGregorianCalendar::getMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getNow' => ['float'],
'IntlGregorianCalendar::getRepeatedWallTimeOption' => ['int'],
'IntlGregorianCalendar::getSkippedWallTimeOption' => ['int'],
'IntlGregorianCalendar::getTime' => ['float'],
'IntlGregorianCalendar::getTimeZone' => ['IntlTimeZone'],
'IntlGregorianCalendar::getType' => ['string'],
'IntlGregorianCalendar::getWeekendTransition' => ['int', 'dayOfWeek'=>'string'],
'IntlGregorianCalendar::inDaylightTime' => ['bool'],
'IntlGregorianCalendar::isEquivalentTo' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::isLeapYear' => ['bool', 'year'=>'int'],
'IntlGregorianCalendar::isLenient' => ['bool'],
'IntlGregorianCalendar::isSet' => ['bool', 'field'=>'int'],
'IntlGregorianCalendar::isWeekend' => ['bool', 'date='=>'float'],
'IntlGregorianCalendar::roll' => ['bool', 'field'=>'int', 'amountOrUpOrDown'=>'mixed'],
'IntlGregorianCalendar::set' => ['bool', 'field'=>'int', 'value'=>'int'],
'IntlGregorianCalendar::set\'1' => ['bool', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'IntlGregorianCalendar::setFirstDayOfWeek' => ['bool', 'dayOfWeek'=>'int'],
'IntlGregorianCalendar::setGregorianChange' => ['bool', 'date'=>'float'],
'IntlGregorianCalendar::setLenient' => ['bool', 'isLenient'=>'string'],
'IntlGregorianCalendar::setMinimalDaysInFirstWeek' => ['bool', 'minimalDays'=>'int'],
'IntlGregorianCalendar::setRepeatedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlGregorianCalendar::setSkippedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlGregorianCalendar::setTime' => ['bool', 'date'=>'float'],
'IntlGregorianCalendar::setTimeZone' => ['bool', 'timeZone'=>'mixed'],
'IntlGregorianCalendar::toDateTime' => ['DateTime'],
'IntlIterator::__construct' => ['void'],
'IntlIterator::current' => ['mixed'],
'IntlIterator::key' => ['string'],
'IntlIterator::next' => ['void'],
'IntlIterator::rewind' => ['void'],
'IntlIterator::valid' => ['bool'],
'IntlPartsIterator::getBreakIterator' => ['IntlBreakIterator'],
'IntlRuleBasedBreakIterator::__construct' => ['void', 'rules'=>'string', 'areCompiled='=>'string'],
'IntlRuleBasedBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlRuleBasedBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::current' => ['int'],
'IntlRuleBasedBreakIterator::first' => ['int'],
'IntlRuleBasedBreakIterator::following' => ['int', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::getBinaryRules' => ['string'],
'IntlRuleBasedBreakIterator::getErrorCode' => ['int'],
'IntlRuleBasedBreakIterator::getErrorMessage' => ['string'],
'IntlRuleBasedBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlRuleBasedBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'int'],
'IntlRuleBasedBreakIterator::getRules' => ['string'],
'IntlRuleBasedBreakIterator::getRuleStatus' => ['int'],
'IntlRuleBasedBreakIterator::getRuleStatusVec' => ['array'],
'IntlRuleBasedBreakIterator::getText' => ['string'],
'IntlRuleBasedBreakIterator::isBoundary' => ['bool', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::last' => ['int'],
'IntlRuleBasedBreakIterator::next' => ['int', 'offset='=>'int'],
'IntlRuleBasedBreakIterator::preceding' => ['int', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::previous' => ['int'],
'IntlRuleBasedBreakIterator::setText' => ['bool', 'text'=>'string'],
'IntlTimeZone::countEquivalentIDs' => ['int|false', 'zoneId'=>'string'],
'IntlTimeZone::createDefault' => ['IntlTimeZone'],
'IntlTimeZone::createEnumeration' => ['IntlIterator|false', 'countryOrRawOffset='=>'mixed'],
'IntlTimeZone::createTimeZone' => ['IntlTimeZone|false', 'zoneId'=>'string'],
'IntlTimeZone::createTimeZoneIDEnumeration' => ['IntlIterator|false', 'zoneType'=>'int', 'region='=>'string', 'rawOffset='=>'int'],
'IntlTimeZone::fromDateTimeZone' => ['?IntlTimeZone', 'zoneId'=>'DateTimeZone'],
'IntlTimeZone::getCanonicalID' => ['string|false', 'zoneId'=>'string', '&w_isSystemID='=>'bool'],
'IntlTimeZone::getDisplayName' => ['string|false', 'isDaylight='=>'bool', 'style='=>'int', 'locale='=>'string'],
'IntlTimeZone::getDSTSavings' => ['int'],
'IntlTimeZone::getEquivalentID' => ['string|false', 'zoneId'=>'string', 'index'=>'int'],
'IntlTimeZone::getErrorCode' => ['int'],
'IntlTimeZone::getErrorMessage' => ['string'],
'IntlTimeZone::getGMT' => ['IntlTimeZone'],
'IntlTimeZone::getID' => ['string'],
'IntlTimeZone::getIDForWindowsID' => ['string', 'timezone'=>'string', 'region='=>'string'],
'IntlTimeZone::getOffset' => ['int', 'date'=>'float', 'local'=>'bool', '&w_rawOffset'=>'int', '&w_dstOffset'=>'int'],
'IntlTimeZone::getRawOffset' => ['int'],
'IntlTimeZone::getRegion' => ['string|false', 'zoneId'=>'string'],
'IntlTimeZone::getTZDataVersion' => ['string'],
'IntlTimeZone::getUnknown' => ['IntlTimeZone'],
'IntlTimeZone::getWindowsID' => ['string|false', 'timezone'=>'string'],
'IntlTimeZone::hasSameRules' => ['bool', 'otherTimeZone'=>'IntlTimeZone'],
'IntlTimeZone::toDateTimeZone' => ['DateTimeZone|false'],
'IntlTimeZone::useDaylightTime' => ['bool'],
'intltz_count_equivalent_ids' => ['int', 'timezoneId'=>'string'],
'intltz_create_enumeration' => ['IntlIterator', 'countryOrRawOffset'=>'mixed'],
'intltz_create_time_zone' => ['IntlTimeZone', 'timezoneId'=>'string'],
'intltz_from_date_time_zone' => ['IntlTimeZone', 'timezone'=>'DateTimeZone'],
'intltz_get_canonical_id' => ['string', 'timezoneId'=>'string', '&isSystemId'=>'bool'],
'intltz_get_display_name' => ['string', 'timezone'=>'IntlTimeZone', 'dst'=>'bool', 'style'=>'int', 'locale'=>'string'],
'intltz_get_dst_savings' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_equivalent_id' => ['string', 'timezoneId'=>'string', 'offset'=>'int'],
'intltz_get_error_code' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_error_message' => ['string', 'timezone'=>'IntlTimeZone'],
'intltz_get_id' => ['string', 'timezone'=>'IntlTimeZone'],
'intltz_get_offset' => ['int', 'timezone'=>'IntlTimeZone', 'timestamp'=>'float', 'local'=>'bool', '&rawOffset'=>'int', '&dstOffset'=>'int'],
'intltz_get_raw_offset' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_tz_data_version' => ['string', 'object'=>'IntlTimeZone'],
'intltz_getGMT' => ['IntlTimeZone'],
'intltz_has_same_rules' => ['bool', 'timezone'=>'IntlTimeZone', 'other'=>'IntlTimeZone'],
'intltz_to_date_time_zone' => ['DateTimeZone', 'timezone'=>'IntlTimeZone'],
'intltz_use_daylight_time' => ['bool', 'timezone'=>'IntlTimeZone'],
'intlz_create_default' => ['IntlTimeZone'],
'intval' => ['int', 'value'=>'mixed', 'base='=>'int'],
'InvalidArgumentException::__clone' => ['void'],
'InvalidArgumentException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?InvalidArgumentException'],
'InvalidArgumentException::__toString' => ['string'],
'InvalidArgumentException::getCode' => ['int'],
'InvalidArgumentException::getFile' => ['string'],
'InvalidArgumentException::getLine' => ['int'],
'InvalidArgumentException::getMessage' => ['string'],
'InvalidArgumentException::getPrevious' => ['Throwable|InvalidArgumentException|null'],
'InvalidArgumentException::getTrace' => ['list<array<string,mixed>>'],
'InvalidArgumentException::getTraceAsString' => ['string'],
'ip2long' => ['int|false', 'ip'=>'string'],
'iptcembed' => ['string|bool', 'iptc_data'=>'string', 'filename'=>'string', 'spool='=>'int'],
'iptcparse' => ['array|false', 'iptc_block'=>'string'],
'is_a' => ['bool', 'object_or_class'=>'mixed', 'class'=>'string', 'allow_string='=>'bool'],
'is_array' => ['bool', 'value'=>'mixed'],
'is_bool' => ['bool', 'value'=>'mixed'],
'is_callable' => ['bool', 'value'=>'callable|mixed', 'syntax_only='=>'bool', '&w_callable_name='=>'string'],
'is_countable' => ['bool', 'value'=>'mixed'],
'is_dir' => ['bool', 'filename'=>'string'],
'is_double' => ['bool', 'value'=>'mixed'],
'is_executable' => ['bool', 'filename'=>'string'],
'is_file' => ['bool', 'filename'=>'string'],
'is_finite' => ['bool', 'num'=>'float'],
'is_float' => ['bool', 'value'=>'mixed'],
'is_infinite' => ['bool', 'num'=>'float'],
'is_int' => ['bool', 'value'=>'mixed'],
'is_integer' => ['bool', 'value'=>'mixed'],
'is_iterable' => ['bool', 'value'=>'mixed'],
'is_link' => ['bool', 'filename'=>'string'],
'is_long' => ['bool', 'value'=>'mixed'],
'is_nan' => ['bool', 'num'=>'float'],
'is_null' => ['bool', 'value'=>'mixed'],
'is_numeric' => ['bool', 'value'=>'mixed'],
'is_object' => ['bool', 'value'=>'mixed'],
'is_readable' => ['bool', 'filename'=>'string'],
'is_real' => ['bool', 'value'=>'mixed'],
'is_resource' => ['bool', 'value'=>'mixed'],
'is_scalar' => ['bool', 'value'=>'mixed'],
'is_soap_fault' => ['bool', 'object'=>'mixed'],
'is_string' => ['bool', 'value'=>'mixed'],
'is_subclass_of' => ['bool', 'object_or_class'=>'object|string', 'class'=>'string', 'allow_string='=>'bool'],
'is_tainted' => ['bool', 'string'=>'string'],
'is_uploaded_file' => ['bool', 'filename'=>'string'],
'is_writable' => ['bool', 'filename'=>'string'],
'is_writeable' => ['bool', 'filename'=>'string'],
'isset' => ['bool', 'value'=>'mixed', '...rest='=>'mixed'],
'Iterator::current' => ['mixed'],
'Iterator::key' => ['mixed'],
'Iterator::next' => ['void'],
'Iterator::rewind' => ['void'],
'Iterator::valid' => ['bool'],
'iterator_apply' => ['int', 'iterator'=>'Traversable', 'callback'=>'callable(mixed):bool', 'args='=>'array'],
'iterator_count' => ['int', 'iterator'=>'Traversable'],
'iterator_to_array' => ['array', 'iterator'=>'Traversable', 'preserve_keys='=>'bool'],
'IteratorAggregate::getIterator' => ['Traversable'],
'IteratorIterator::__construct' => ['void', 'it'=>'Traversable'],
'IteratorIterator::current' => ['mixed'],
'IteratorIterator::getInnerIterator' => ['Traversable'],
'IteratorIterator::key' => ['mixed'],
'IteratorIterator::next' => ['void'],
'IteratorIterator::rewind' => ['void'],
'IteratorIterator::valid' => ['bool'],
'java_last_exception_clear' => ['void'],
'java_last_exception_get' => ['object'],
'java_reload' => ['array', 'new_jarpath'=>'string'],
'java_require' => ['array', 'new_classpath'=>'string'],
'java_set_encoding' => ['array', 'encoding'=>'string'],
'java_set_ignore_case' => ['void', 'ignore'=>'bool'],
'java_throw_exceptions' => ['void', 'throw'=>'bool'],
'JavaException::getCause' => ['object'],
'jddayofweek' => ['mixed', 'julian_day'=>'int', 'mode='=>'int'],
'jdmonthname' => ['string', 'julian_day'=>'int', 'mode'=>'int'],
'jdtofrench' => ['string', 'julian_day'=>'int'],
'jdtogregorian' => ['string', 'julian_day'=>'int'],
'jdtojewish' => ['string', 'julian_day'=>'int', 'hebrew='=>'bool', 'flags='=>'int'],
'jdtojulian' => ['string', 'julian_day'=>'int'],
'jdtounix' => ['int|false', 'julian_day'=>'int'],
'jewishtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'jobqueue_license_info' => ['array'],
'join' => ['string', 'separator'=>'string', 'array'=>'array'],
'join\'1' => ['string', 'separator'=>'array'],
'jpeg2wbmp' => ['bool', 'jpegname'=>'string', 'wbmpname'=>'string', 'dest_height'=>'int', 'dest_width'=>'int', 'threshold'=>'int'],
'json_decode' => ['mixed', 'json'=>'string', 'associative='=>'bool', 'depth='=>'int', 'flags='=>'int'],
'json_encode' => ['string|false', 'value'=>'mixed', 'flags='=>'int', 'depth='=>'int'],
'json_last_error' => ['int'],
'json_last_error_msg' => ['string'],
'JsonException::__clone' => ['void'],
'JsonException::__construct' => ['void'],
'JsonException::__toString' => ['string'],
'JsonException::__wakeup' => ['void'],
'JsonException::getCode' => ['int'],
'JsonException::getFile' => ['string'],
'JsonException::getLine' => ['int'],
'JsonException::getMessage' => ['string'],
'JsonException::getPrevious' => ['?Throwable'],
'JsonException::getTrace' => ['list<array<string,mixed>>'],
'JsonException::getTraceAsString' => ['string'],
'JsonIncrementalParser::__construct' => ['void', 'depth'=>'', 'options'=>''],
'JsonIncrementalParser::get' => ['', 'options'=>''],
'JsonIncrementalParser::getError' => [''],
'JsonIncrementalParser::parse' => ['', 'json'=>''],
'JsonIncrementalParser::parseFile' => ['', 'filename'=>''],
'JsonIncrementalParser::reset' => [''],
'JsonSerializable::jsonSerialize' => ['mixed'],
'Judy::__construct' => ['void', 'judy_type'=>'int'],
'Judy::__destruct' => ['void'],
'Judy::byCount' => ['int', 'nth_index'=>'int'],
'Judy::count' => ['int', 'index_start='=>'int', 'index_end='=>'int'],
'Judy::first' => ['mixed', 'index='=>'mixed'],
'Judy::firstEmpty' => ['mixed', 'index='=>'mixed'],
'Judy::free' => ['int'],
'Judy::getType' => ['int'],
'Judy::last' => ['mixed', 'index='=>'string'],
'Judy::lastEmpty' => ['mixed', 'index='=>'int'],
'Judy::memoryUsage' => ['int'],
'Judy::next' => ['mixed', 'index'=>'mixed'],
'Judy::nextEmpty' => ['mixed', 'index'=>'mixed'],
'Judy::offsetExists' => ['bool', 'offset'=>'mixed'],
'Judy::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Judy::offsetSet' => ['bool', 'offset'=>'mixed', 'value'=>'mixed'],
'Judy::offsetUnset' => ['bool', 'offset'=>'mixed'],
'Judy::prev' => ['mixed', 'index'=>'mixed'],
'Judy::prevEmpty' => ['mixed', 'index'=>'mixed'],
'Judy::size' => ['int'],
'judy_type' => ['int', 'array'=>'judy'],
'judy_version' => ['string'],
'juliantojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'kadm5_chpass_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'password'=>'string'],
'kadm5_create_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'password='=>'string', 'options='=>'array'],
'kadm5_delete_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string'],
'kadm5_destroy' => ['bool', 'handle'=>'resource'],
'kadm5_flush' => ['bool', 'handle'=>'resource'],
'kadm5_get_policies' => ['array', 'handle'=>'resource'],
'kadm5_get_principal' => ['array', 'handle'=>'resource', 'principal'=>'string'],
'kadm5_get_principals' => ['array', 'handle'=>'resource'],
'kadm5_init_with_password' => ['resource', 'admin_server'=>'string', 'realm'=>'string', 'principal'=>'string', 'password'=>'string'],
'kadm5_modify_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'options'=>'array'],
'key' => ['int|string|null', 'array'=>'array|object'],
'key_exists' => ['bool', 'key'=>'string|int', 'array'=>'array'],
'krsort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'ksort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'KTaglib_ID3v2_AttachedPictureFrame::getDescription' => ['string'],
'KTaglib_ID3v2_AttachedPictureFrame::getMimeType' => ['string'],
'KTaglib_ID3v2_AttachedPictureFrame::getType' => ['int'],
'KTaglib_ID3v2_AttachedPictureFrame::savePicture' => ['bool', 'filename'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setMimeType' => ['string', 'type'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setPicture' => ['', 'filename'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setType' => ['', 'type'=>'int'],
'KTaglib_ID3v2_Frame::__toString' => ['string'],
'KTaglib_ID3v2_Frame::getDescription' => ['string'],
'KTaglib_ID3v2_Frame::getMimeType' => ['string'],
'KTaglib_ID3v2_Frame::getSize' => ['int'],
'KTaglib_ID3v2_Frame::getType' => ['int'],
'KTaglib_ID3v2_Frame::savePicture' => ['bool', 'filename'=>'string'],
'KTaglib_ID3v2_Frame::setMimeType' => ['string', 'type'=>'string'],
'KTaglib_ID3v2_Frame::setPicture' => ['void', 'filename'=>'string'],
'KTaglib_ID3v2_Frame::setType' => ['void', 'type'=>'int'],
'KTaglib_ID3v2_Tag::addFrame' => ['bool', 'frame'=>'KTaglib_ID3v2_Frame'],
'KTaglib_ID3v2_Tag::getFrameList' => ['array'],
'KTaglib_MPEG_AudioProperties::getBitrate' => ['int'],
'KTaglib_MPEG_AudioProperties::getChannels' => ['int'],
'KTaglib_MPEG_AudioProperties::getLayer' => ['int'],
'KTaglib_MPEG_AudioProperties::getLength' => ['int'],
'KTaglib_MPEG_AudioProperties::getSampleBitrate' => ['int'],
'KTaglib_MPEG_AudioProperties::getVersion' => ['int'],
'KTaglib_MPEG_AudioProperties::isCopyrighted' => ['bool'],
'KTaglib_MPEG_AudioProperties::isOriginal' => ['bool'],
'KTaglib_MPEG_AudioProperties::isProtectionEnabled' => ['bool'],
'KTaglib_MPEG_File::getAudioProperties' => ['KTaglib_MPEG_File'],
'KTaglib_MPEG_File::getID3v1Tag' => ['KTaglib_ID3v1_Tag', 'create='=>'bool'],
'KTaglib_MPEG_File::getID3v2Tag' => ['KTaglib_ID3v2_Tag', 'create='=>'bool'],
'KTaglib_Tag::getAlbum' => ['string'],
'KTaglib_Tag::getArtist' => ['string'],
'KTaglib_Tag::getComment' => ['string'],
'KTaglib_Tag::getGenre' => ['string'],
'KTaglib_Tag::getTitle' => ['string'],
'KTaglib_Tag::getTrack' => ['int'],
'KTaglib_Tag::getYear' => ['int'],
'KTaglib_Tag::isEmpty' => ['bool'],
'labelcacheObj::freeCache' => ['bool'],
'labelObj::__construct' => ['void'],
'labelObj::convertToString' => ['string'],
'labelObj::deleteStyle' => ['int', 'index'=>'int'],
'labelObj::free' => ['void'],
'labelObj::getBinding' => ['string', 'labelbinding'=>'mixed'],
'labelObj::getExpressionString' => ['string'],
'labelObj::getStyle' => ['styleObj', 'index'=>'int'],
'labelObj::getTextString' => ['string'],
'labelObj::moveStyleDown' => ['int', 'index'=>'int'],
'labelObj::moveStyleUp' => ['int', 'index'=>'int'],
'labelObj::removeBinding' => ['int', 'labelbinding'=>'mixed'],
'labelObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'labelObj::setBinding' => ['int', 'labelbinding'=>'mixed', 'value'=>'string'],
'labelObj::setExpression' => ['int', 'expression'=>'string'],
'labelObj::setText' => ['int', 'text'=>'string'],
'labelObj::updateFromString' => ['int', 'snippet'=>'string'],
'Lapack::eigenValues' => ['array', 'a'=>'array', 'left='=>'array', 'right='=>'array'],
'Lapack::identity' => ['array', 'n'=>'int'],
'Lapack::leastSquaresByFactorisation' => ['array', 'a'=>'array', 'b'=>'array'],
'Lapack::leastSquaresBySVD' => ['array', 'a'=>'array', 'b'=>'array'],
'Lapack::pseudoInverse' => ['array', 'a'=>'array'],
'Lapack::singularValues' => ['array', 'a'=>'array'],
'Lapack::solveLinearEquation' => ['array', 'a'=>'array', 'b'=>'array'],
'layerObj::addFeature' => ['int', 'shape'=>'shapeObj'],
'layerObj::applySLD' => ['int', 'sldxml'=>'string', 'namedlayer'=>'string'],
'layerObj::applySLDURL' => ['int', 'sldurl'=>'string', 'namedlayer'=>'string'],
'layerObj::clearProcessing' => ['void'],
'layerObj::close' => ['void'],
'layerObj::convertToString' => ['string'],
'layerObj::draw' => ['int', 'image'=>'imageObj'],
'layerObj::drawQuery' => ['int', 'image'=>'imageObj'],
'layerObj::free' => ['void'],
'layerObj::generateSLD' => ['string'],
'layerObj::getClass' => ['classObj', 'classIndex'=>'int'],
'layerObj::getClassIndex' => ['int', 'shape'=>'', 'classgroup'=>'', 'numclasses'=>''],
'layerObj::getExtent' => ['rectObj'],
'layerObj::getFilterString' => ['?string'],
'layerObj::getGridIntersectionCoordinates' => ['array'],
'layerObj::getItems' => ['array'],
'layerObj::getMetaData' => ['int', 'name'=>'string'],
'layerObj::getNumResults' => ['int'],
'layerObj::getProcessing' => ['array'],
'layerObj::getProjection' => ['string'],
'layerObj::getResult' => ['resultObj', 'index'=>'int'],
'layerObj::getResultsBounds' => ['rectObj'],
'layerObj::getShape' => ['shapeObj', 'result'=>'resultObj'],
'layerObj::getWMSFeatureInfoURL' => ['string', 'clickX'=>'int', 'clickY'=>'int', 'featureCount'=>'int', 'infoFormat'=>'string'],
'layerObj::isVisible' => ['bool'],
'layerObj::moveclassdown' => ['int', 'index'=>'int'],
'layerObj::moveclassup' => ['int', 'index'=>'int'],
'layerObj::ms_newLayerObj' => ['layerObj', 'map'=>'mapObj', 'layer'=>'layerObj'],
'layerObj::nextShape' => ['shapeObj'],
'layerObj::open' => ['int'],
'layerObj::queryByAttributes' => ['int', 'qitem'=>'string', 'qstring'=>'string', 'mode'=>'int'],
'layerObj::queryByFeatures' => ['int', 'slayer'=>'int'],
'layerObj::queryByPoint' => ['int', 'point'=>'pointObj', 'mode'=>'int', 'buffer'=>'float'],
'layerObj::queryByRect' => ['int', 'rect'=>'rectObj'],
'layerObj::queryByShape' => ['int', 'shape'=>'shapeObj'],
'layerObj::removeClass' => ['?classObj', 'index'=>'int'],
'layerObj::removeMetaData' => ['int', 'name'=>'string'],
'layerObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'layerObj::setConnectionType' => ['int', 'connectiontype'=>'int', 'plugin_library'=>'string'],
'layerObj::setFilter' => ['int', 'expression'=>'string'],
'layerObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'layerObj::setProjection' => ['int', 'proj_params'=>'string'],
'layerObj::setWKTProjection' => ['int', 'proj_params'=>'string'],
'layerObj::updateFromString' => ['int', 'snippet'=>'string'],
'lcfirst' => ['string', 'string'=>'string'],
'lcg_value' => ['float'],
'lchgrp' => ['bool', 'filename'=>'string', 'group'=>'string|int'],
'lchown' => ['bool', 'filename'=>'string', 'user'=>'string|int'],
'ldap_8859_to_t61' => ['string', 'value'=>'string'],
'ldap_add' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_add_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_bind' => ['bool', 'ldap'=>'resource', 'dn='=>'string|null', 'password='=>'string|null'],
'ldap_bind_ext' => ['resource|false', 'ldap'=>'resource', 'dn='=>'string|null', 'password='=>'string|null', 'controls='=>'array'],
'ldap_close' => ['bool', 'ldap'=>'resource'],
'ldap_compare' => ['bool|int', 'ldap'=>'resource', 'dn'=>'string', 'attribute'=>'string', 'value'=>'string'],
'ldap_connect' => ['resource|false', 'uri='=>'string', 'port='=>'int', 'wallet='=>'string', 'password='=>'string', 'auth_mode='=>'int'],
'ldap_control_paged_result' => ['bool', 'link_identifier'=>'resource', 'pagesize'=>'int', 'iscritical='=>'bool', 'cookie='=>'string'],
'ldap_control_paged_result_response' => ['bool', 'link_identifier'=>'resource', 'result_identifier'=>'resource', '&w_cookie'=>'string', '&w_estimated'=>'int'],
'ldap_count_entries' => ['int|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_delete' => ['bool', 'ldap'=>'resource', 'dn'=>'string'],
'ldap_delete_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'controls='=>'array'],
'ldap_dn2ufn' => ['string', 'dn'=>'string'],
'ldap_err2str' => ['string', 'errno'=>'int'],
'ldap_errno' => ['int', 'ldap'=>'resource'],
'ldap_error' => ['string', 'ldap'=>'resource'],
'ldap_escape' => ['string', 'value'=>'string', 'ignore='=>'string', 'flags='=>'int'],
'ldap_exop' => ['mixed', 'ldap'=>'resource', 'request_oid'=>'string', 'request_data='=>'string', 'controls='=>'array|null', '&w_response_data='=>'string', '&w_response_oid='=>'string'],
'ldap_exop_passwd' => ['mixed', 'ldap'=>'resource', 'user='=>'string', 'old_password='=>'string', 'new_password='=>'string', 'controls='=>'array'],
'ldap_exop_refresh' => ['int|false', 'ldap'=>'resource', 'dn'=>'string', 'ttl'=>'int'],
'ldap_exop_whoami' => ['string|false', 'ldap'=>'resource'],
'ldap_explode_dn' => ['array|false', 'dn'=>'string', 'with_attrib'=>'int'],
'ldap_first_attribute' => ['string|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_first_entry' => ['resource|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_first_reference' => ['resource|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_free_result' => ['bool', 'ldap'=>'resource'],
'ldap_get_attributes' => ['array|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_get_dn' => ['string|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_get_entries' => ['array|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_get_option' => ['bool', 'ldap'=>'resource', 'option'=>'int', '&w_value'=>'mixed'],
'ldap_get_values' => ['array|false', 'ldap'=>'resource', 'entry'=>'resource', 'attribute'=>'string'],
'ldap_get_values_len' => ['array|false', 'ldap'=>'resource', 'entry'=>'resource', 'attribute'=>'string'],
'ldap_list' => ['resource|false', 'ldap'=>'resource|array', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_mod_add' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_add_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_mod_del' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_del_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_mod_replace' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_replace_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_modify' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_modify_batch' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'modifications_info'=>'array'],
'ldap_next_attribute' => ['string|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_next_entry' => ['resource|false', 'ldap'=>'resource', 'result'=>'resource'],
'ldap_next_reference' => ['resource|false', 'ldap'=>'resource', 'entry'=>'resource'],
'ldap_parse_exop' => ['bool', 'ldap'=>'resource', 'result'=>'resource', '&w_response_data='=>'string', '&w_response_oid='=>'string'],
'ldap_parse_reference' => ['bool', 'ldap'=>'resource', 'entry'=>'resource', 'referrals'=>'array'],
'ldap_parse_result' => ['bool', 'ldap'=>'resource', 'result'=>'resource', '&w_error_code'=>'int', '&w_matched_dn='=>'string', '&w_error_message='=>'string', '&w_referrals='=>'array', '&w_controls='=>'array'],
'ldap_read' => ['resource|false', 'ldap'=>'resource|array', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_rename' => ['bool', 'ldap'=>'resource', 'dn'=>'string', 'new_rdn'=>'string', 'new_parent'=>'string', 'delete_old_rdn'=>'bool'],
'ldap_rename_ext' => ['resource|false', 'ldap'=>'resource', 'dn'=>'string', 'new_rdn'=>'string', 'new_parent'=>'string', 'delete_old_rdn'=>'bool', 'controls='=>'array'],
'ldap_sasl_bind' => ['bool', 'ldap'=>'resource', 'dn='=>'string', 'password='=>'string', 'mech='=>'string', 'realm='=>'string', 'authc_id='=>'string', 'authz_id='=>'string', 'props='=>'string'],
'ldap_search' => ['resource|false', 'ldap'=>'resource|resource[]', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_set_option' => ['bool', 'ldap'=>'resource|null', 'option'=>'int', 'value'=>'mixed'],
'ldap_set_rebind_proc' => ['bool', 'ldap'=>'resource', 'callback'=>'string'],
'ldap_sort' => ['bool', 'link_identifier'=>'resource', 'result_identifier'=>'resource', 'sortfilter'=>'string'],
'ldap_start_tls' => ['bool', 'ldap'=>'resource'],
'ldap_t61_to_8859' => ['string', 'value'=>'string'],
'ldap_unbind' => ['bool', 'ldap'=>'resource'],
'leak' => ['', 'num_bytes'=>'int'],
'leak_variable' => ['', 'variable'=>'', 'leak_data'=>'bool'],
'legendObj::convertToString' => ['string'],
'legendObj::free' => ['void'],
'legendObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'legendObj::updateFromString' => ['int', 'snippet'=>'string'],
'LengthException::__clone' => ['void'],
'LengthException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?LengthException'],
'LengthException::__toString' => ['string'],
'LengthException::getCode' => ['int'],
'LengthException::getFile' => ['string'],
'LengthException::getLine' => ['int'],
'LengthException::getMessage' => ['string'],
'LengthException::getPrevious' => ['Throwable|LengthException|null'],
'LengthException::getTrace' => ['list<array<string,mixed>>'],
'LengthException::getTraceAsString' => ['string'],
'LevelDB::__construct' => ['void', 'name'=>'string', 'options='=>'array', 'read_options='=>'array', 'write_options='=>'array'],
'LevelDB::close' => [''],
'LevelDB::compactRange' => ['', 'start'=>'', 'limit'=>''],
'LevelDB::delete' => ['bool', 'key'=>'string', 'write_options='=>'array'],
'LevelDB::destroy' => ['', 'name'=>'', 'options='=>'array'],
'LevelDB::get' => ['bool|string', 'key'=>'string', 'read_options='=>'array'],
'LevelDB::getApproximateSizes' => ['', 'start'=>'', 'limit'=>''],
'LevelDB::getIterator' => ['LevelDBIterator', 'options='=>'array'],
'LevelDB::getProperty' => ['mixed', 'name'=>'string'],
'LevelDB::getSnapshot' => ['LevelDBSnapshot'],
'LevelDB::put' => ['', 'key'=>'string', 'value'=>'string', 'write_options='=>'array'],
'LevelDB::repair' => ['', 'name'=>'', 'options='=>'array'],
'LevelDB::set' => ['', 'key'=>'string', 'value'=>'string', 'write_options='=>'array'],
'LevelDB::write' => ['', 'batch'=>'LevelDBWriteBatch', 'write_options='=>'array'],
'LevelDBIterator::__construct' => ['void', 'db'=>'LevelDB', 'read_options='=>'array'],
'LevelDBIterator::current' => ['mixed'],
'LevelDBIterator::destroy' => [''],
'LevelDBIterator::getError' => [''],
'LevelDBIterator::key' => ['int|string'],
'LevelDBIterator::last' => [''],
'LevelDBIterator::next' => ['void'],
'LevelDBIterator::prev' => [''],
'LevelDBIterator::rewind' => ['void'],
'LevelDBIterator::seek' => ['', 'key'=>''],
'LevelDBIterator::valid' => ['bool'],
'LevelDBSnapshot::__construct' => ['void', 'db'=>'LevelDB'],
'LevelDBSnapshot::release' => [''],
'LevelDBWriteBatch::__construct' => ['void', 'name'=>'', 'options='=>'array', 'read_options='=>'array', 'write_options='=>'array'],
'LevelDBWriteBatch::clear' => [''],
'LevelDBWriteBatch::delete' => ['', 'key'=>'', 'write_options='=>'array'],
'LevelDBWriteBatch::put' => ['', 'key'=>'', 'value'=>'', 'write_options='=>'array'],
'LevelDBWriteBatch::set' => ['', 'key'=>'', 'value'=>'', 'write_options='=>'array'],
'levenshtein' => ['int', 'string1'=>'string', 'string2'=>'string'],
'levenshtein\'1' => ['int', 'string1'=>'string', 'string2'=>'string', 'insertion_cost'=>'int', 'repetition_cost'=>'int', 'deletion_cost'=>'int'],
'libxml_clear_errors' => ['void'],
'libxml_disable_entity_loader' => ['bool', 'disable='=>'bool'],
'libxml_get_errors' => ['array<int,LibXMLError>'],
'libxml_get_last_error' => ['LibXMLError|false'],
'libxml_set_external_entity_loader' => ['bool', 'resolver_function'=>'callable'],
'libxml_set_streams_context' => ['void', 'context'=>'resource'],
'libxml_use_internal_errors' => ['bool', 'use_errors='=>'bool'],
'LimitIterator::__construct' => ['void', 'iterator'=>'Iterator', 'offset='=>'int', 'count='=>'int'],
'LimitIterator::current' => ['mixed'],
'LimitIterator::getInnerIterator' => ['Iterator'],
'LimitIterator::getPosition' => ['int'],
'LimitIterator::key' => ['mixed'],
'LimitIterator::next' => ['void'],
'LimitIterator::rewind' => ['void'],
'LimitIterator::seek' => ['int', 'position'=>'int'],
'LimitIterator::valid' => ['bool'],
'lineObj::__construct' => ['void'],
'lineObj::add' => ['int', 'point'=>'pointObj'],
'lineObj::addXY' => ['int', 'x'=>'float', 'y'=>'float', 'm'=>'float'],
'lineObj::addXYZ' => ['int', 'x'=>'float', 'y'=>'float', 'z'=>'float', 'm'=>'float'],
'lineObj::ms_newLineObj' => ['lineObj'],
'lineObj::point' => ['pointObj', 'i'=>'int'],
'lineObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'link' => ['bool', 'target'=>'string', 'link'=>'string'],
'linkinfo' => ['int|false', 'path'=>'string'],
'litespeed_request_headers' => ['array'],
'litespeed_response_headers' => ['array'],
'Locale::acceptFromHttp' => ['string|false', 'header'=>'string'],
'Locale::canonicalize' => ['string', 'locale'=>'string'],
'Locale::composeLocale' => ['string', 'subtags'=>'array'],
'Locale::filterMatches' => ['bool', 'langtag'=>'string', 'locale'=>'string', 'canonicalize='=>'bool'],
'Locale::getAllVariants' => ['array', 'locale'=>'string'],
'Locale::getDefault' => ['string'],
'Locale::getDisplayLanguage' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayName' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayRegion' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayScript' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayVariant' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getKeywords' => ['array|false', 'locale'=>'string'],
'Locale::getPrimaryLanguage' => ['string', 'locale'=>'string'],
'Locale::getRegion' => ['string', 'locale'=>'string'],
'Locale::getScript' => ['string', 'locale'=>'string'],
'Locale::lookup' => ['string', 'langtag'=>'array', 'locale'=>'string', 'canonicalize='=>'bool', 'default='=>'string'],
'Locale::parseLocale' => ['array', 'locale'=>'string'],
'Locale::setDefault' => ['bool', 'locale'=>'string'],
'locale_accept_from_http' => ['string|false', 'header'=>'string'],
'locale_canonicalize' => ['string', 'locale'=>'string'],
'locale_compose' => ['string|false', 'subtags'=>'array'],
'locale_filter_matches' => ['bool', 'languageTag'=>'string', 'locale'=>'string', 'canonicalize='=>'bool'],
'locale_get_all_variants' => ['array', 'locale'=>'string'],
'locale_get_default' => ['string'],
'locale_get_display_language' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_name' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_region' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_script' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_variant' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_keywords' => ['array|false', 'locale'=>'string'],
'locale_get_primary_language' => ['string', 'locale'=>'string'],
'locale_get_region' => ['string', 'locale'=>'string'],
'locale_get_script' => ['string', 'locale'=>'string'],
'locale_lookup' => ['string', 'languageTag'=>'array', 'locale'=>'string', 'canonicalize='=>'bool', 'defaultLocale='=>'string'],
'locale_parse' => ['array', 'locale'=>'string'],
'locale_set_default' => ['bool', 'locale'=>'string'],
'localeconv' => ['array'],
'localtime' => ['array', 'timestamp='=>'int', 'associative='=>'bool'],
'log' => ['float', 'num'=>'float', 'base='=>'float'],
'log10' => ['float', 'num'=>'float'],
'log1p' => ['float', 'num'=>'float'],
'LogicException::__clone' => ['void'],
'LogicException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?LogicException'],
'LogicException::__toString' => ['string'],
'LogicException::getCode' => ['int'],
'LogicException::getFile' => ['string'],
'LogicException::getLine' => ['int'],
'LogicException::getMessage' => ['string'],
'LogicException::getPrevious' => ['Throwable|LogicException|null'],
'LogicException::getTrace' => ['list<array<string,mixed>>'],
'LogicException::getTraceAsString' => ['string'],
'long2ip' => ['string', 'ip'=>'string|int'],
'lstat' => ['array|false', 'filename'=>'string'],
'ltrim' => ['string', 'string'=>'string', 'characters='=>'string'],
'Lua::__call' => ['mixed', 'lua_func'=>'callable', 'args='=>'array', 'use_self='=>'int'],
'Lua::__construct' => ['void', 'lua_script_file'=>'string'],
'Lua::assign' => ['?Lua', 'name'=>'string', 'value'=>'mixed'],
'Lua::call' => ['mixed', 'lua_func'=>'callable', 'args='=>'array', 'use_self='=>'int'],
'Lua::eval' => ['mixed', 'statements'=>'string'],
'Lua::getVersion' => ['string'],
'Lua::include' => ['mixed', 'file'=>'string'],
'Lua::registerCallback' => ['Lua|null|false', 'name'=>'string', 'function'=>'callable'],
'LuaClosure::__invoke' => ['void', 'arg'=>'mixed', '...args='=>'mixed'],
'lzf_compress' => ['string', 'data'=>'string'],
'lzf_decompress' => ['string', 'data'=>'string'],
'lzf_optimized_for' => ['int'],
'm_checkstatus' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_completeauthorizations' => ['int', 'conn'=>'resource', 'array'=>'int'],
'm_connect' => ['int', 'conn'=>'resource'],
'm_connectionerror' => ['string', 'conn'=>'resource'],
'm_deletetrans' => ['bool', 'conn'=>'resource', 'identifier'=>'int'],
'm_destroyconn' => ['bool', 'conn'=>'resource'],
'm_destroyengine' => ['void'],
'm_getcell' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column'=>'string', 'row'=>'int'],
'm_getcellbynum' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column'=>'int', 'row'=>'int'],
'm_getcommadelimited' => ['string', 'conn'=>'resource', 'identifier'=>'int'],
'm_getheader' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column_num'=>'int'],
'm_initconn' => ['resource'],
'm_initengine' => ['int', 'location'=>'string'],
'm_iscommadelimited' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_maxconntimeout' => ['bool', 'conn'=>'resource', 'secs'=>'int'],
'm_monitor' => ['int', 'conn'=>'resource'],
'm_numcolumns' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_numrows' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_parsecommadelimited' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_responsekeys' => ['array', 'conn'=>'resource', 'identifier'=>'int'],
'm_responseparam' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'key'=>'string'],
'm_returnstatus' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_setblocking' => ['int', 'conn'=>'resource', 'tf'=>'int'],
'm_setdropfile' => ['int', 'conn'=>'resource', 'directory'=>'string'],
'm_setip' => ['int', 'conn'=>'resource', 'host'=>'string', 'port'=>'int'],
'm_setssl' => ['int', 'conn'=>'resource', 'host'=>'string', 'port'=>'int'],
'm_setssl_cafile' => ['int', 'conn'=>'resource', 'cafile'=>'string'],
'm_setssl_files' => ['int', 'conn'=>'resource', 'sslkeyfile'=>'string', 'sslcertfile'=>'string'],
'm_settimeout' => ['int', 'conn'=>'resource', 'seconds'=>'int'],
'm_sslcert_gen_hash' => ['string', 'filename'=>'string'],
'm_transactionssent' => ['int', 'conn'=>'resource'],
'm_transinqueue' => ['int', 'conn'=>'resource'],
'm_transkeyval' => ['int', 'conn'=>'resource', 'identifier'=>'int', 'key'=>'string', 'value'=>'string'],
'm_transnew' => ['int', 'conn'=>'resource'],
'm_transsend' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_uwait' => ['int', 'microsecs'=>'int'],
'm_validateidentifier' => ['int', 'conn'=>'resource', 'tf'=>'int'],
'm_verifyconnection' => ['bool', 'conn'=>'resource', 'tf'=>'int'],
'm_verifysslcert' => ['bool', 'conn'=>'resource', 'tf'=>'int'],
'magic_quotes_runtime' => ['bool', 'new_setting'=>'bool'],
'mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string|array|null', 'additional_params='=>'string'],
'mailparse_determine_best_xfer_encoding' => ['string', 'fp'=>'resource'],
'mailparse_msg_create' => ['resource'],
'mailparse_msg_extract_part' => ['void', 'mimemail'=>'resource', 'msgbody'=>'string', 'callbackfunc='=>'callable'],
'mailparse_msg_extract_part_file' => ['string', 'mimemail'=>'resource', 'filename'=>'mixed', 'callbackfunc='=>'callable'],
'mailparse_msg_extract_whole_part_file' => ['string', 'mimemail'=>'resource', 'filename'=>'string', 'callbackfunc='=>'callable'],
'mailparse_msg_free' => ['bool', 'mimemail'=>'resource'],
'mailparse_msg_get_part' => ['resource', 'mimemail'=>'resource', 'mimesection'=>'string'],
'mailparse_msg_get_part_data' => ['array', 'mimemail'=>'resource'],
'mailparse_msg_get_structure' => ['array', 'mimemail'=>'resource'],
'mailparse_msg_parse' => ['bool', 'mimemail'=>'resource', 'data'=>'string'],
'mailparse_msg_parse_file' => ['resource|false', 'filename'=>'string'],
'mailparse_rfc822_parse_addresses' => ['array', 'addresses'=>'string'],
'mailparse_stream_encode' => ['bool', 'sourcefp'=>'resource', 'destfp'=>'resource', 'encoding'=>'string'],
'mailparse_uudecode_all' => ['array', 'fp'=>'resource'],
'mapObj::__construct' => ['void', 'map_file_name'=>'string', 'new_map_path'=>'string'],
'mapObj::appendOutputFormat' => ['int', 'outputFormat'=>'outputformatObj'],
'mapObj::applyconfigoptions' => ['int'],
'mapObj::applySLD' => ['int', 'sldxml'=>'string'],
'mapObj::applySLDURL' => ['int', 'sldurl'=>'string'],
'mapObj::convertToString' => ['string'],
'mapObj::draw' => ['?imageObj'],
'mapObj::drawLabelCache' => ['int', 'image'=>'imageObj'],
'mapObj::drawLegend' => ['imageObj'],
'mapObj::drawQuery' => ['?imageObj'],
'mapObj::drawReferenceMap' => ['imageObj'],
'mapObj::drawScaleBar' => ['imageObj'],
'mapObj::embedLegend' => ['int', 'image'=>'imageObj'],
'mapObj::embedScalebar' => ['int', 'image'=>'imageObj'],
'mapObj::free' => ['void'],
'mapObj::generateSLD' => ['string'],
'mapObj::getAllGroupNames' => ['array'],
'mapObj::getAllLayerNames' => ['array'],
'mapObj::getColorbyIndex' => ['colorObj', 'iCloIndex'=>'int'],
'mapObj::getConfigOption' => ['string', 'key'=>'string'],
'mapObj::getLabel' => ['labelcacheMemberObj', 'index'=>'int'],
'mapObj::getLayer' => ['layerObj', 'index'=>'int'],
'mapObj::getLayerByName' => ['layerObj', 'layer_name'=>'string'],
'mapObj::getLayersDrawingOrder' => ['array'],
'mapObj::getLayersIndexByGroup' => ['array', 'groupname'=>'string'],
'mapObj::getMetaData' => ['int', 'name'=>'string'],
'mapObj::getNumSymbols' => ['int'],
'mapObj::getOutputFormat' => ['?outputformatObj', 'index'=>'int'],
'mapObj::getProjection' => ['string'],
'mapObj::getSymbolByName' => ['int', 'symbol_name'=>'string'],
'mapObj::getSymbolObjectById' => ['symbolObj', 'symbolid'=>'int'],
'mapObj::loadMapContext' => ['int', 'filename'=>'string', 'unique_layer_name'=>'bool'],
'mapObj::loadOWSParameters' => ['int', 'request'=>'OwsrequestObj', 'version'=>'string'],
'mapObj::moveLayerDown' => ['int', 'layerindex'=>'int'],
'mapObj::moveLayerUp' => ['int', 'layerindex'=>'int'],
'mapObj::ms_newMapObjFromString' => ['mapObj', 'map_file_string'=>'string', 'new_map_path'=>'string'],
'mapObj::offsetExtent' => ['int', 'x'=>'float', 'y'=>'float'],
'mapObj::owsDispatch' => ['int', 'request'=>'OwsrequestObj'],
'mapObj::prepareImage' => ['imageObj'],
'mapObj::prepareQuery' => ['void'],
'mapObj::processLegendTemplate' => ['string', 'params'=>'array'],
'mapObj::processQueryTemplate' => ['string', 'params'=>'array', 'generateimages'=>'bool'],
'mapObj::processTemplate' => ['string', 'params'=>'array', 'generateimages'=>'bool'],
'mapObj::queryByFeatures' => ['int', 'slayer'=>'int'],
'mapObj::queryByIndex' => ['int', 'layerindex'=>'', 'tileindex'=>'', 'shapeindex'=>'', 'addtoquery'=>''],
'mapObj::queryByPoint' => ['int', 'point'=>'pointObj', 'mode'=>'int', 'buffer'=>'float'],
'mapObj::queryByRect' => ['int', 'rect'=>'rectObj'],
'mapObj::queryByShape' => ['int', 'shape'=>'shapeObj'],
'mapObj::removeLayer' => ['layerObj', 'nIndex'=>'int'],
'mapObj::removeMetaData' => ['int', 'name'=>'string'],
'mapObj::removeOutputFormat' => ['int', 'name'=>'string'],
'mapObj::save' => ['int', 'filename'=>'string'],
'mapObj::saveMapContext' => ['int', 'filename'=>'string'],
'mapObj::saveQuery' => ['int', 'filename'=>'string', 'results'=>'int'],
'mapObj::scaleExtent' => ['int', 'zoomfactor'=>'float', 'minscaledenom'=>'float', 'maxscaledenom'=>'float'],
'mapObj::selectOutputFormat' => ['int', 'type'=>'string'],
'mapObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'mapObj::setCenter' => ['int', 'center'=>'pointObj'],
'mapObj::setConfigOption' => ['int', 'key'=>'string', 'value'=>'string'],
'mapObj::setExtent' => ['void', 'minx'=>'float', 'miny'=>'float', 'maxx'=>'float', 'maxy'=>'float'],
'mapObj::setFontSet' => ['int', 'fileName'=>'string'],
'mapObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'mapObj::setProjection' => ['int', 'proj_params'=>'string', 'bSetUnitsAndExtents'=>'bool'],
'mapObj::setRotation' => ['int', 'rotation_angle'=>'float'],
'mapObj::setSize' => ['int', 'width'=>'int', 'height'=>'int'],
'mapObj::setSymbolSet' => ['int', 'fileName'=>'string'],
'mapObj::setWKTProjection' => ['int', 'proj_params'=>'string', 'bSetUnitsAndExtents'=>'bool'],
'mapObj::zoomPoint' => ['int', 'nZoomFactor'=>'int', 'oPixelPos'=>'pointObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj'],
'mapObj::zoomRectangle' => ['int', 'oPixelExt'=>'rectObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj'],
'mapObj::zoomScale' => ['int', 'nScaleDenom'=>'float', 'oPixelPos'=>'pointObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj', 'oMaxGeorefExt'=>'rectObj'],
'max' => ['mixed', 'value'=>'non-empty-array'],
'max\'1' => ['mixed', 'value'=>'', 'values'=>'', '...args='=>''],
'maxdb::__construct' => ['void', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb::affected_rows' => ['int', 'link'=>''],
'maxdb::auto_commit' => ['bool', 'link'=>'', 'mode'=>'bool'],
'maxdb::change_user' => ['bool', 'link'=>'', 'user'=>'string', 'password'=>'string', 'database'=>'string'],
'maxdb::character_set_name' => ['string', 'link'=>''],
'maxdb::close' => ['bool', 'link'=>''],
'maxdb::commit' => ['bool', 'link'=>''],
'maxdb::disable_reads_from_master' => ['', 'link'=>''],
'maxdb::errno' => ['int', 'link'=>''],
'maxdb::error' => ['string', 'link'=>''],
'maxdb::field_count' => ['int', 'link'=>''],
'maxdb::get_host_info' => ['string', 'link'=>''],
'maxdb::info' => ['string', 'link'=>''],
'maxdb::insert_id' => ['', 'link'=>''],
'maxdb::kill' => ['bool', 'link'=>'', 'processid'=>'int'],
'maxdb::more_results' => ['bool', 'link'=>''],
'maxdb::multi_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::next_result' => ['bool', 'link'=>''],
'maxdb::num_rows' => ['int', 'result'=>''],
'maxdb::options' => ['bool', 'link'=>'', 'option'=>'int', 'value'=>''],
'maxdb::ping' => ['bool', 'link'=>''],
'maxdb::prepare' => ['maxdb_stmt', 'link'=>'', 'query'=>'string'],
'maxdb::protocol_version' => ['string', 'link'=>''],
'maxdb::query' => ['', 'link'=>'', 'query'=>'string', 'resultmode='=>'int'],
'maxdb::real_connect' => ['bool', 'link'=>'', 'hostname='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb::real_escape_string' => ['string', 'link'=>'', 'escapestr'=>'string'],
'maxdb::real_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::rollback' => ['bool', 'link'=>''],
'maxdb::rpl_query_type' => ['int', 'link'=>''],
'maxdb::select_db' => ['bool', 'link'=>'', 'dbname'=>'string'],
'maxdb::send_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::server_info' => ['string', 'link'=>''],
'maxdb::server_version' => ['int', 'link'=>''],
'maxdb::sqlstate' => ['string', 'link'=>''],
'maxdb::ssl_set' => ['bool', 'link'=>'', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'maxdb::stat' => ['string', 'link'=>''],
'maxdb::stmt_init' => ['object', 'link'=>''],
'maxdb::store_result' => ['bool', 'link'=>''],
'maxdb::thread_id' => ['int', 'link'=>''],
'maxdb::use_result' => ['resource', 'link'=>''],
'maxdb::warning_count' => ['int', 'link'=>''],
'maxdb_affected_rows' => ['int', 'link'=>'resource'],
'maxdb_autocommit' => ['bool', 'link'=>'', 'mode'=>'bool'],
'maxdb_change_user' => ['bool', 'link'=>'', 'user'=>'string', 'password'=>'string', 'database'=>'string'],
'maxdb_character_set_name' => ['string', 'link'=>''],
'maxdb_close' => ['bool', 'link'=>''],
'maxdb_commit' => ['bool', 'link'=>''],
'maxdb_connect' => ['resource', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb_connect_errno' => ['int'],
'maxdb_connect_error' => ['string'],
'maxdb_data_seek' => ['bool', 'result'=>'', 'offset'=>'int'],
'maxdb_debug' => ['void', 'debug'=>'string'],
'maxdb_disable_reads_from_master' => ['', 'link'=>''],
'maxdb_disable_rpl_parse' => ['bool', 'link'=>'resource'],
'maxdb_dump_debug_info' => ['bool', 'link'=>'resource'],
'maxdb_embedded_connect' => ['resource', 'dbname='=>'string'],
'maxdb_enable_reads_from_master' => ['bool', 'link'=>'resource'],
'maxdb_enable_rpl_parse' => ['bool', 'link'=>'resource'],
'maxdb_errno' => ['int', 'link'=>'resource'],
'maxdb_error' => ['string', 'link'=>'resource'],
'maxdb_fetch_array' => ['', 'result'=>'', 'resulttype='=>'int'],
'maxdb_fetch_assoc' => ['array', 'result'=>''],
'maxdb_fetch_field' => ['', 'result'=>''],
'maxdb_fetch_field_direct' => ['', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_fetch_fields' => ['', 'result'=>''],
'maxdb_fetch_lengths' => ['array', 'result'=>'resource'],
'maxdb_fetch_object' => ['object', 'result'=>'object'],
'maxdb_fetch_row' => ['', 'result'=>''],
'maxdb_field_count' => ['int', 'link'=>''],
'maxdb_field_seek' => ['bool', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_field_tell' => ['int', 'result'=>'resource'],
'maxdb_free_result' => ['', 'result'=>''],
'maxdb_get_client_info' => ['string'],
'maxdb_get_client_version' => ['int'],
'maxdb_get_host_info' => ['string', 'link'=>'resource'],
'maxdb_get_proto_info' => ['string', 'link'=>'resource'],
'maxdb_get_server_info' => ['string', 'link'=>'resource'],
'maxdb_get_server_version' => ['int', 'link'=>'resource'],
'maxdb_info' => ['string', 'link'=>'resource'],
'maxdb_init' => ['resource'],
'maxdb_insert_id' => ['mixed', 'link'=>'resource'],
'maxdb_kill' => ['bool', 'link'=>'', 'processid'=>'int'],
'maxdb_master_query' => ['bool', 'link'=>'resource', 'query'=>'string'],
'maxdb_more_results' => ['bool', 'link'=>'resource'],
'maxdb_multi_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_next_result' => ['bool', 'link'=>'resource'],
'maxdb_num_fields' => ['int', 'result'=>'resource'],
'maxdb_num_rows' => ['int', 'result'=>'resource'],
'maxdb_options' => ['bool', 'link'=>'', 'option'=>'int', 'value'=>''],
'maxdb_ping' => ['bool', 'link'=>''],
'maxdb_prepare' => ['maxdb_stmt', 'link'=>'', 'query'=>'string'],
'maxdb_query' => ['', 'link'=>'', 'query'=>'string', 'resultmode='=>'int'],
'maxdb_real_connect' => ['bool', 'link'=>'', 'hostname='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb_real_escape_string' => ['string', 'link'=>'', 'escapestr'=>'string'],
'maxdb_real_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_report' => ['bool', 'flags'=>'int'],
'maxdb_result::current_field' => ['int', 'result'=>''],
'maxdb_result::data_seek' => ['bool', 'result'=>'', 'offset'=>'int'],
'maxdb_result::fetch_array' => ['', 'result'=>'', 'resulttype='=>'int'],
'maxdb_result::fetch_assoc' => ['array', 'result'=>''],
'maxdb_result::fetch_field' => ['', 'result'=>''],
'maxdb_result::fetch_field_direct' => ['', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_result::fetch_fields' => ['', 'result'=>''],
'maxdb_result::fetch_object' => ['object', 'result'=>'object'],
'maxdb_result::fetch_row' => ['', 'result'=>''],
'maxdb_result::field_count' => ['int', 'result'=>''],
'maxdb_result::field_seek' => ['bool', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_result::free' => ['', 'result'=>''],
'maxdb_result::lengths' => ['array', 'result'=>''],
'maxdb_rollback' => ['bool', 'link'=>''],
'maxdb_rpl_parse_enabled' => ['int', 'link'=>'resource'],
'maxdb_rpl_probe' => ['bool', 'link'=>'resource'],
'maxdb_rpl_query_type' => ['int', 'link'=>''],
'maxdb_select_db' => ['bool', 'link'=>'resource', 'dbname'=>'string'],
'maxdb_send_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_server_end' => ['void'],
'maxdb_server_init' => ['bool', 'server='=>'array', 'groups='=>'array'],
'maxdb_sqlstate' => ['string', 'link'=>'resource'],
'maxdb_ssl_set' => ['bool', 'link'=>'', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'maxdb_stat' => ['string', 'link'=>''],
'maxdb_stmt::affected_rows' => ['int', 'stmt'=>''],
'maxdb_stmt::bind_param' => ['bool', 'stmt'=>'', 'types'=>'string', '&...rw_var'=>''],
'maxdb_stmt::bind_param\'1' => ['bool', 'stmt'=>'', 'types'=>'string', '&rw_var'=>'array'],
'maxdb_stmt::bind_result' => ['bool', 'stmt'=>'', '&w_var1'=>'', '&...w_vars='=>''],
'maxdb_stmt::close' => ['bool', 'stmt'=>''],
'maxdb_stmt::close_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int'],
'maxdb_stmt::data_seek' => ['bool', 'statement'=>'', 'offset'=>'int'],
'maxdb_stmt::errno' => ['int', 'stmt'=>''],
'maxdb_stmt::error' => ['string', 'stmt'=>''],
'maxdb_stmt::execute' => ['bool', 'stmt'=>''],
'maxdb_stmt::fetch' => ['bool', 'stmt'=>''],
'maxdb_stmt::free_result' => ['', 'stmt'=>''],
'maxdb_stmt::num_rows' => ['int', 'stmt'=>''],
'maxdb_stmt::param_count' => ['int', 'stmt'=>''],
'maxdb_stmt::prepare' => ['', 'stmt'=>'', 'query'=>'string'],
'maxdb_stmt::reset' => ['bool', 'stmt'=>''],
'maxdb_stmt::result_metadata' => ['resource', 'stmt'=>''],
'maxdb_stmt::send_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt::stmt_send_long_data' => ['bool', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt::store_result' => ['bool'],
'maxdb_stmt_affected_rows' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_bind_param' => ['bool', 'stmt'=>'', 'types'=>'string', 'var1'=>'', '...args='=>'', 'var='=>'array'],
'maxdb_stmt_bind_result' => ['bool', 'stmt'=>'', '&w_var1'=>'', '&...w_vars='=>''],
'maxdb_stmt_close' => ['bool', 'stmt'=>''],
'maxdb_stmt_close_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int'],
'maxdb_stmt_data_seek' => ['bool', 'statement'=>'', 'offset'=>'int'],
'maxdb_stmt_errno' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_error' => ['string', 'stmt'=>'resource'],
'maxdb_stmt_execute' => ['bool', 'stmt'=>''],
'maxdb_stmt_fetch' => ['bool', 'stmt'=>''],
'maxdb_stmt_free_result' => ['', 'stmt'=>''],
'maxdb_stmt_init' => ['object', 'link'=>''],
'maxdb_stmt_num_rows' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_param_count' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_prepare' => ['', 'stmt'=>'', 'query'=>'string'],
'maxdb_stmt_reset' => ['bool', 'stmt'=>''],
'maxdb_stmt_result_metadata' => ['resource', 'stmt'=>''],
'maxdb_stmt_send_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt_sqlstate' => ['string', 'stmt'=>'resource'],
'maxdb_stmt_store_result' => ['bool', 'stmt'=>''],
'maxdb_store_result' => ['bool', 'link'=>''],
'maxdb_thread_id' => ['int', 'link'=>'resource'],
'maxdb_thread_safe' => ['bool'],
'maxdb_use_result' => ['resource', 'link'=>''],
'maxdb_warning_count' => ['int', 'link'=>'resource'],
'mb_check_encoding' => ['bool', 'value='=>'string', 'encoding='=>'string'],
'mb_chr' => ['string|false', 'codepoint'=>'int', 'encoding='=>'string'],
'mb_convert_case' => ['string|false', 'string'=>'string', 'mode'=>'int', 'encoding='=>'string'],
'mb_convert_encoding' => ['string', 'string'=>'string', 'to_encoding'=>'string', 'from_encoding='=>'mixed'],
'mb_convert_encoding\'1' => ['array<int, string>', 'string'=>'array<int, string>', 'to_encoding'=>'string', 'from_encoding='=>'mixed'],
'mb_convert_kana' => ['string|false', 'string'=>'string', 'mode='=>'string', 'encoding='=>'string'],
'mb_convert_variables' => ['string|false', 'to_encoding'=>'string', 'from_encoding'=>'array|string', '&rw_var'=>'string|array|object', '&...rw_vars='=>'string|array|object'],
'mb_decode_mimeheader' => ['string', 'string'=>'string'],
'mb_decode_numericentity' => ['string|false', 'string'=>'string', 'map'=>'array', 'encoding='=>'string', 'is_hex='=>'bool'],
'mb_detect_encoding' => ['string|false', 'string'=>'string', 'encodings='=>'mixed', 'strict='=>'bool'],
'mb_detect_order' => ['bool|list<string>', 'encoding='=>'mixed'],
'mb_encode_mimeheader' => ['string|false', 'string'=>'string', 'charset='=>'string', 'transfer_encoding='=>'string', 'newline='=>'string', 'indent='=>'int'],
'mb_encode_numericentity' => ['string|false', 'string'=>'string', 'map'=>'array', 'encoding='=>'string', 'hex='=>'bool'],
'mb_encoding_aliases' => ['list<string>|false', 'encoding'=>'string'],
'mb_ereg' => ['int|false', 'pattern'=>'string', 'string'=>'string', '&w_matches='=>'array'],
'mb_ereg_match' => ['bool', 'pattern'=>'string', 'string'=>'string', 'options='=>'string'],
'mb_ereg_replace' => ['string|false', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'options='=>'string'],
'mb_ereg_replace_callback' => ['string|false', 'pattern'=>'string', 'callback'=>'callable', 'string'=>'string', 'options='=>'string'],
'mb_ereg_search' => ['bool', 'pattern='=>'string', 'options='=>'string'],
'mb_ereg_search_getpos' => ['int'],
'mb_ereg_search_getregs' => ['string[]|false'],
'mb_ereg_search_init' => ['bool', 'string'=>'string', 'pattern='=>'string', 'options='=>'string'],
'mb_ereg_search_pos' => ['int[]|false', 'pattern='=>'string', 'options='=>'string'],
'mb_ereg_search_regs' => ['string[]|false', 'pattern='=>'string', 'options='=>'string'],
'mb_ereg_search_setpos' => ['bool', 'offset'=>'int'],
'mb_eregi' => ['int|false', 'pattern'=>'string', 'string'=>'string', '&w_matches='=>'array'],
'mb_eregi_replace' => ['string|false', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'options='=>'string'],
'mb_get_info' => ['array|mixed', 'type='=>'string'],
'mb_http_input' => ['string|false', 'type='=>'string'],
'mb_http_output' => ['string|bool', 'encoding='=>'string'],
'mb_internal_encoding' => ['string|bool', 'encoding='=>'string'],
'mb_language' => ['string|bool', 'language='=>'string'],
'mb_list_encodings' => ['list<string>'],
'mb_ord' => ['int|false', 'string'=>'string', 'encoding='=>'string'],
'mb_output_handler' => ['string', 'string'=>'string', 'status'=>'int'],
'mb_parse_str' => ['bool', 'string'=>'string', '&w_result='=>'array'],
'mb_preferred_mime_name' => ['string|false', 'encoding'=>'string'],
'mb_regex_encoding' => ['string|bool', 'encoding='=>'string'],
'mb_regex_set_options' => ['string', 'options='=>'string'],
'mb_scrub' => ['string|false', 'string'=>'string', 'encoding='=>'string'],
'mb_send_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string|array', 'additional_params='=>'string'],
'mb_split' => ['list<string>', 'pattern'=>'string', 'string'=>'string', 'limit='=>'int'],
'mb_strcut' => ['string', 'string'=>'string', 'start'=>'int', 'length='=>'?int', 'encoding='=>'string'],
'mb_strimwidth' => ['string|false', 'string'=>'string', 'start'=>'int', 'width'=>'int', 'trim_marker='=>'string', 'encoding='=>'string'],
'mb_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string'],
'mb_strlen' => ['int|false', 'string'=>'string', 'encoding='=>'string'],
'mb_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string'],
'mb_strrichr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string'],
'mb_strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string'],
'mb_strtolower' => ['lowercase-string|false', 'string'=>'string', 'encoding='=>'string'],
'mb_strtoupper' => ['string|false', 'string'=>'string', 'encoding='=>'string'],
'mb_strwidth' => ['int|false', 'string'=>'string', 'encoding='=>'string'],
'mb_substitute_character' => ['bool|int|string', 'substitute_character='=>'mixed'],
'mb_substr' => ['string|false', 'string'=>'string', 'start'=>'int', 'length='=>'?int', 'encoding='=>'string'],
'mb_substr_count' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'encoding='=>'string'],
'mcrypt_cbc' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_cfb' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_create_iv' => ['string|false', 'size'=>'int', 'source='=>'int'],
'mcrypt_decrypt' => ['string', 'cipher'=>'string', 'key'=>'string', 'data'=>'string', 'mode'=>'string', 'iv='=>'string'],
'mcrypt_ecb' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_enc_get_algorithms_name' => ['string', 'td'=>'resource'],
'mcrypt_enc_get_block_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_iv_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_key_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_modes_name' => ['string', 'td'=>'resource'],
'mcrypt_enc_get_supported_key_sizes' => ['array', 'td'=>'resource'],
'mcrypt_enc_is_block_algorithm' => ['bool', 'td'=>'resource'],
'mcrypt_enc_is_block_algorithm_mode' => ['bool', 'td'=>'resource'],
'mcrypt_enc_is_block_mode' => ['bool', 'td'=>'resource'],
'mcrypt_enc_self_test' => ['int|false', 'td'=>'resource'],
'mcrypt_encrypt' => ['string', 'cipher'=>'string', 'key'=>'string', 'data'=>'string', 'mode'=>'string', 'iv='=>'string'],
'mcrypt_generic' => ['string', 'td'=>'resource', 'data'=>'string'],
'mcrypt_generic_deinit' => ['bool', 'td'=>'resource'],
'mcrypt_generic_end' => ['bool', 'td'=>'resource'],
'mcrypt_generic_init' => ['int|false', 'td'=>'resource', 'key'=>'string', 'iv'=>'string'],
'mcrypt_get_block_size' => ['int', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_get_cipher_name' => ['string|false', 'cipher'=>'int|string'],
'mcrypt_get_iv_size' => ['int|false', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_get_key_size' => ['int', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_list_algorithms' => ['array', 'lib_dir='=>'string'],
'mcrypt_list_modes' => ['array', 'lib_dir='=>'string'],
'mcrypt_module_close' => ['bool', 'td'=>'resource'],
'mcrypt_module_get_algo_block_size' => ['int', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_get_algo_key_size' => ['int', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_get_supported_key_sizes' => ['array', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_algorithm' => ['bool', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_algorithm_mode' => ['bool', 'mode'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_mode' => ['bool', 'mode'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_open' => ['resource|false', 'cipher'=>'string', 'cipher_directory'=>'string', 'mode'=>'string', 'mode_directory'=>'string'],
'mcrypt_module_self_test' => ['bool', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_ofb' => ['string', 'cipher'=>'int|string', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'md5' => ['string', 'string'=>'string', 'binary='=>'bool'],
'md5_file' => ['string|false', 'filename'=>'string', 'binary='=>'bool'],
'mdecrypt_generic' => ['string', 'td'=>'resource', 'data'=>'string'],
'Memcache::add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::addServer' => ['bool', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable', 'timeoutms='=>'int'],
'Memcache::append' => [''],
'Memcache::cas' => [''],
'Memcache::close' => ['bool'],
'Memcache::connect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'Memcache::decrement' => ['int', 'key'=>'string', 'value='=>'int'],
'Memcache::delete' => ['bool', 'key'=>'string', 'timeout='=>'int'],
'Memcache::findServer' => [''],
'Memcache::flush' => ['bool'],
'Memcache::get' => ['string|array|false', 'key'=>'string', 'flags='=>'array', 'keys='=>'array'],
'Memcache::get\'1' => ['array', 'key'=>'string[]', 'flags='=>'int[]'],
'Memcache::getExtendedStats' => ['array', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'Memcache::getServerStatus' => ['int', 'host'=>'string', 'port='=>'int'],
'Memcache::getStats' => ['array', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'Memcache::getVersion' => ['string'],
'Memcache::increment' => ['int', 'key'=>'string', 'value='=>'int'],
'Memcache::pconnect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'Memcache::prepend' => ['string'],
'Memcache::replace' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::set' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::setCompressThreshold' => ['bool', 'threshold'=>'int', 'min_savings='=>'float'],
'Memcache::setFailureCallback' => [''],
'Memcache::setServerParams' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable'],
'memcache_add' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_add_server' => ['bool', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable', 'timeoutms='=>'int'],
'memcache_append' => ['', 'memcache_obj'=>'Memcache'],
'memcache_cas' => ['', 'memcache_obj'=>'Memcache'],
'memcache_close' => ['bool', 'memcache_obj'=>'Memcache'],
'memcache_connect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'memcache_debug' => ['bool', 'on_off'=>'bool'],
'memcache_decrement' => ['int', 'memcache_obj'=>'Memcache', 'key'=>'string', 'value='=>'int'],
'memcache_delete' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'timeout='=>'int'],
'memcache_flush' => ['bool', 'memcache_obj'=>'Memcache'],
'memcache_get' => ['string', 'memcache_obj'=>'Memcache', 'key'=>'string', 'flags='=>'int'],
'memcache_get\'1' => ['array', 'memcache_obj'=>'Memcache', 'key'=>'string[]', 'flags='=>'int[]'],
'memcache_get_extended_stats' => ['array', 'memcache_obj'=>'Memcache', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'memcache_get_server_status' => ['int', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int'],
'memcache_get_stats' => ['array', 'memcache_obj'=>'Memcache', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'memcache_get_version' => ['string', 'memcache_obj'=>'Memcache'],
'memcache_increment' => ['int', 'memcache_obj'=>'Memcache', 'key'=>'string', 'value='=>'int'],
'memcache_pconnect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'memcache_prepend' => ['string', 'memcache_obj'=>'Memcache'],
'memcache_replace' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_set' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_set_compress_threshold' => ['bool', 'memcache_obj'=>'Memcache', 'threshold'=>'int', 'min_savings='=>'float'],
'memcache_set_failure_callback' => ['', 'memcache_obj'=>'Memcache'],
'memcache_set_server_params' => ['bool', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable'],
'Memcached::__construct' => ['void', 'persistent_id='=>'mixed|string', 'on_new_object_cb='=>'mixed'],
'Memcached::add' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::addByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::addServer' => ['bool', 'host'=>'string', 'port'=>'int', 'weight='=>'int'],
'Memcached::addServers' => ['bool', 'servers'=>'array'],
'Memcached::append' => ['bool', 'key'=>'string', 'value'=>'string'],
'Memcached::appendByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'string'],
'Memcached::cas' => ['bool', 'cas_token'=>'float', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::casByKey' => ['bool', 'cas_token'=>'float', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::decrement' => ['int|false', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::decrementByKey' => ['int|false', 'server_key'=>'string', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::delete' => ['bool', 'key'=>'string', 'time='=>'int'],
'Memcached::deleteByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'time='=>'int'],
'Memcached::deleteMulti' => ['array', 'keys'=>'array', 'time='=>'int'],
'Memcached::deleteMultiByKey' => ['bool', 'server_key'=>'string', 'keys'=>'array', 'time='=>'int'],
'Memcached::fetch' => ['array|false'],
'Memcached::fetchAll' => ['array|false'],
'Memcached::flush' => ['bool', 'delay='=>'int'],
'Memcached::flushBuffers' => [''],
'Memcached::get' => ['mixed|false', 'key'=>'string', 'cache_cb='=>'?callable', 'flags='=>'int'],
'Memcached::getAllKeys' => ['array|false'],
'Memcached::getByKey' => ['mixed|false', 'server_key'=>'string', 'key'=>'string', 'value_cb='=>'?callable', 'flags='=>'int'],
'Memcached::getDelayed' => ['bool', 'keys'=>'array', 'with_cas='=>'bool', 'value_cb='=>'callable'],
'Memcached::getDelayedByKey' => ['bool', 'server_key'=>'string', 'keys'=>'array', 'with_cas='=>'bool', 'value_cb='=>'?callable'],
'Memcached::getLastDisconnectedServer' => [''],
'Memcached::getLastErrorCode' => [''],
'Memcached::getLastErrorErrno' => [''],
'Memcached::getLastErrorMessage' => [''],
'Memcached::getMulti' => ['array|false', 'keys'=>'array', 'flags='=>'int'],
'Memcached::getMultiByKey' => ['array|false', 'server_key'=>'string', 'keys'=>'array', 'flags='=>'int'],
'Memcached::getOption' => ['mixed|false', 'option'=>'int'],
'Memcached::getResultCode' => ['int'],
'Memcached::getResultMessage' => ['string'],
'Memcached::getServerByKey' => ['array', 'server_key'=>'string'],
'Memcached::getServerList' => ['array'],
'Memcached::getStats' => ['array', 'type='=>'?string'],
'Memcached::getVersion' => ['array'],
'Memcached::increment' => ['int|false', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::incrementByKey' => ['int|false', 'server_key'=>'string', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::isPersistent' => ['bool'],
'Memcached::isPristine' => ['bool'],
'Memcached::prepend' => ['bool', 'key'=>'string', 'value'=>'string'],
'Memcached::prependByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'string'],
'Memcached::quit' => ['bool'],
'Memcached::replace' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::replaceByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::resetServerList' => ['bool'],
'Memcached::set' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::setBucket' => ['', 'host_map'=>'array', 'forward_map'=>'array', 'replicas'=>''],
'Memcached::setByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::setEncodingKey' => ['', 'key'=>''],
'Memcached::setMulti' => ['bool', 'items'=>'array', 'expiration='=>'int'],
'Memcached::setMultiByKey' => ['bool', 'server_key'=>'string', 'items'=>'array', 'expiration='=>'int'],
'Memcached::setOption' => ['bool', 'option'=>'int', 'value'=>'mixed'],
'Memcached::setOptions' => ['bool', 'options'=>'array'],
'Memcached::setSaslAuthData' => ['void', 'username'=>'string', 'password'=>'string'],
'Memcached::touch' => ['bool', 'key'=>'string', 'expiration'=>'int'],
'Memcached::touchByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'expiration'=>'int'],
'MemcachePool::add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::addServer' => ['bool', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'?callable', 'timeoutms='=>'int'],
'MemcachePool::append' => [''],
'MemcachePool::cas' => [''],
'MemcachePool::close' => ['bool'],
'MemcachePool::connect' => ['bool', 'host'=>'string', 'port'=>'int', 'timeout='=>'int'],
'MemcachePool::decrement' => ['int|false', 'key'=>'', 'value='=>'int|mixed'],
'MemcachePool::delete' => ['bool', 'key'=>'', 'timeout='=>'int|mixed'],
'MemcachePool::findServer' => [''],
'MemcachePool::flush' => ['bool'],
'MemcachePool::get' => ['array|string|false', 'key'=>'array|string', '&flags='=>'array|int'],
'MemcachePool::getExtendedStats' => ['array|false', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'MemcachePool::getServerStatus' => ['int', 'host'=>'string', 'port='=>'int'],
'MemcachePool::getStats' => ['array|false', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'MemcachePool::getVersion' => ['string|false'],
'MemcachePool::increment' => ['int|false', 'key'=>'', 'value='=>'int|mixed'],
'MemcachePool::prepend' => ['string'],
'MemcachePool::replace' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::set' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::setCompressThreshold' => ['bool', 'thresold'=>'int', 'min_saving='=>'float'],
'MemcachePool::setFailureCallback' => [''],
'MemcachePool::setServerParams' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'?callable'],
'memory_get_peak_usage' => ['int', 'real_usage='=>'bool'],
'memory_get_usage' => ['int', 'real_usage='=>'bool'],
'MessageFormatter::__construct' => ['void', 'locale'=>'string', 'pattern'=>'string'],
'MessageFormatter::create' => ['MessageFormatter', 'locale'=>'string', 'pattern'=>'string'],
'MessageFormatter::format' => ['false|string', 'args'=>'array'],
'MessageFormatter::formatMessage' => ['false|string', 'locale'=>'string', 'pattern'=>'string', 'args'=>'array'],
'MessageFormatter::getErrorCode' => ['int'],
'MessageFormatter::getErrorMessage' => ['string'],
'MessageFormatter::getLocale' => ['string'],
'MessageFormatter::getPattern' => ['string'],
'MessageFormatter::parse' => ['array|false', 'value'=>'string'],
'MessageFormatter::parseMessage' => ['array|false', 'locale'=>'string', 'pattern'=>'string', 'source'=>'string'],
'MessageFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'metaphone' => ['string|false', 'string'=>'string', 'max_phonemes='=>'int'],
'method_exists' => ['bool', 'object_or_class'=>'object|class-string', 'method'=>'string'],
'mhash' => ['string', 'algo'=>'int', 'data'=>'string', 'key='=>'string'],
'mhash_count' => ['int'],
'mhash_get_block_size' => ['int|false', 'algo'=>'int'],
'mhash_get_hash_name' => ['string|false', 'algo'=>'int'],
'mhash_keygen_s2k' => ['string|false', 'algo'=>'int', 'password'=>'string', 'salt'=>'string', 'length'=>'int'],
'microtime' => ['string', 'as_float='=>'false'],
'microtime\'1' => ['float', 'as_float='=>'true'],
'mime_content_type' => ['string|false', 'filename'=>'string|resource'],
'min' => ['mixed', 'value'=>'non-empty-array'],
'min\'1' => ['mixed', 'value'=>'', 'values'=>'', '...args='=>''],
'ming_keypress' => ['int', 'char'=>'string'],
'ming_setcubicthreshold' => ['void', 'threshold'=>'int'],
'ming_setscale' => ['void', 'scale'=>'float'],
'ming_setswfcompression' => ['void', 'level'=>'int'],
'ming_useconstants' => ['void', 'use'=>'int'],
'ming_useswfversion' => ['void', 'version'=>'int'],
'mkdir' => ['bool', 'directory'=>'string', 'permissions='=>'int', 'recursive='=>'bool', 'context='=>'resource'],
'mktime' => ['int|false', 'hour='=>'int', 'minute='=>'int', 'second='=>'int', 'month='=>'int', 'day='=>'int', 'year='=>'int'],
'money_format' => ['string', 'format'=>'string', 'value'=>'float'],
'Mongo::__construct' => ['void', 'server='=>'string', 'options='=>'array', 'driver_options='=>'array'],
'Mongo::__get' => ['MongoDB', 'dbname'=>'string'],
'Mongo::__toString' => ['string'],
'Mongo::close' => ['bool'],
'Mongo::connect' => ['bool'],
'Mongo::connectUtil' => ['bool'],
'Mongo::dropDB' => ['array', 'db'=>'mixed'],
'Mongo::forceError' => ['bool'],
'Mongo::getConnections' => ['array'],
'Mongo::getHosts' => ['array'],
'Mongo::getPoolSize' => ['int'],
'Mongo::getReadPreference' => ['array'],
'Mongo::getSlave' => ['?string'],
'Mongo::getSlaveOkay' => ['bool'],
'Mongo::getWriteConcern' => ['array'],
'Mongo::killCursor' => ['', 'server_hash'=>'string', 'id'=>'MongoInt64|int'],
'Mongo::lastError' => ['?array'],
'Mongo::listDBs' => ['array'],
'Mongo::pairConnect' => ['bool'],
'Mongo::pairPersistConnect' => ['bool', 'username='=>'string', 'password='=>'string'],
'Mongo::persistConnect' => ['bool', 'username='=>'string', 'password='=>'string'],
'Mongo::poolDebug' => ['array'],
'Mongo::prevError' => ['array'],
'Mongo::resetError' => ['array'],
'Mongo::selectCollection' => ['MongoCollection', 'db'=>'string', 'collection'=>'string'],
'Mongo::selectDB' => ['MongoDB', 'name'=>'string'],
'Mongo::setPoolSize' => ['bool', 'size'=>'int'],
'Mongo::setReadPreference' => ['bool', 'readPreference'=>'string', 'tags='=>'array'],
'Mongo::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'Mongo::switchSlave' => ['string'],
'MongoBinData::__construct' => ['void', 'data'=>'string', 'type='=>'int'],
'MongoBinData::__toString' => ['string'],
'MongoClient::__construct' => ['void', 'server='=>'string', 'options='=>'array', 'driver_options='=>'array'],
'MongoClient::__get' => ['MongoDB', 'dbname'=>'string'],
'MongoClient::__toString' => ['string'],
'MongoClient::close' => ['bool', 'connection='=>'bool|string'],
'MongoClient::connect' => ['bool'],
'MongoClient::dropDB' => ['array', 'db'=>'mixed'],
'MongoClient::getConnections' => ['array'],
'MongoClient::getHosts' => ['array'],
'MongoClient::getReadPreference' => ['array'],
'MongoClient::getWriteConcern' => ['array'],
'MongoClient::killCursor' => ['bool', 'server_hash'=>'string', 'id'=>'int|MongoInt64'],
'MongoClient::listDBs' => ['array'],
'MongoClient::selectCollection' => ['MongoCollection', 'db'=>'string', 'collection'=>'string'],
'MongoClient::selectDB' => ['MongoDB', 'name'=>'string'],
'MongoClient::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoClient::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoClient::switchSlave' => ['string'],
'MongoCode::__construct' => ['void', 'code'=>'string', 'scope='=>'array'],
'MongoCode::__toString' => ['string'],
'MongoCollection::__construct' => ['void', 'db'=>'MongoDB', 'name'=>'string'],
'MongoCollection::__get' => ['MongoCollection', 'name'=>'string'],
'MongoCollection::__toString' => ['string'],
'MongoCollection::aggregate' => ['array', 'op'=>'array', 'op='=>'array', '...args='=>'array'],
'MongoCollection::aggregate\'1' => ['array', 'pipeline'=>'array', 'options='=>'array'],
'MongoCollection::aggregateCursor' => ['MongoCommandCursor', 'command'=>'array', 'options='=>'array'],
'MongoCollection::batchInsert' => ['array|bool', 'a'=>'array', 'options='=>'array'],
'MongoCollection::count' => ['int', 'query='=>'array', 'limit='=>'int', 'skip='=>'int'],
'MongoCollection::createDBRef' => ['array', 'a'=>'array'],
'MongoCollection::createIndex' => ['array', 'keys'=>'array', 'options='=>'array'],
'MongoCollection::deleteIndex' => ['array', 'keys'=>'string|array'],
'MongoCollection::deleteIndexes' => ['array'],
'MongoCollection::distinct' => ['array|false', 'key'=>'string', 'query='=>'array'],
'MongoCollection::drop' => ['array'],
'MongoCollection::ensureIndex' => ['bool', 'keys'=>'array', 'options='=>'array'],
'MongoCollection::find' => ['MongoCursor', 'query='=>'array', 'fields='=>'array'],
'MongoCollection::findAndModify' => ['array', 'query'=>'array', 'update='=>'array', 'fields='=>'array', 'options='=>'array'],
'MongoCollection::findOne' => ['?array', 'query='=>'array', 'fields='=>'array'],
'MongoCollection::getDBRef' => ['array', 'ref'=>'array'],
'MongoCollection::getIndexInfo' => ['array'],
'MongoCollection::getName' => ['string'],
'MongoCollection::getReadPreference' => ['array'],
'MongoCollection::getSlaveOkay' => ['bool'],
'MongoCollection::getWriteConcern' => ['array'],
'MongoCollection::group' => ['array', 'keys'=>'mixed', 'initial'=>'array', 'reduce'=>'MongoCode', 'options='=>'array'],
'MongoCollection::insert' => ['bool|array', 'a'=>'array|object', 'options='=>'array'],
'MongoCollection::parallelCollectionScan' => ['MongoCommandCursor[]', 'num_cursors'=>'int'],
'MongoCollection::remove' => ['bool|array', 'criteria='=>'array', 'options='=>'array'],
'MongoCollection::save' => ['bool|array', 'a'=>'array|object', 'options='=>'array'],
'MongoCollection::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCollection::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoCollection::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoCollection::toIndexString' => ['string', 'keys'=>'mixed'],
'MongoCollection::update' => ['bool', 'criteria'=>'array', 'newobj'=>'array', 'options='=>'array'],
'MongoCollection::validate' => ['array', 'scan_data='=>'bool'],
'MongoCommandCursor::__construct' => ['void', 'connection'=>'MongoClient', 'ns'=>'string', 'command'=>'array'],
'MongoCommandCursor::batchSize' => ['MongoCommandCursor', 'batchSize'=>'int'],
'MongoCommandCursor::createFromDocument' => ['MongoCommandCursor', 'connection'=>'MongoClient', 'hash'=>'string', 'document'=>'array'],
'MongoCommandCursor::current' => ['array'],
'MongoCommandCursor::dead' => ['bool'],
'MongoCommandCursor::getReadPreference' => ['array'],
'MongoCommandCursor::info' => ['array'],
'MongoCommandCursor::key' => ['int'],
'MongoCommandCursor::next' => ['void'],
'MongoCommandCursor::rewind' => ['array'],
'MongoCommandCursor::setReadPreference' => ['MongoCommandCursor', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCommandCursor::timeout' => ['MongoCommandCursor', 'ms'=>'int'],
'MongoCommandCursor::valid' => ['bool'],
'MongoCursor::__construct' => ['void', 'connection'=>'MongoClient', 'ns'=>'string', 'query='=>'array', 'fields='=>'array'],
'MongoCursor::addOption' => ['MongoCursor', 'key'=>'string', 'value'=>'mixed'],
'MongoCursor::awaitData' => ['MongoCursor', 'wait='=>'bool'],
'MongoCursor::batchSize' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::count' => ['int', 'foundonly='=>'bool'],
'MongoCursor::current' => ['array'],
'MongoCursor::dead' => ['bool'],
'MongoCursor::doQuery' => ['void'],
'MongoCursor::explain' => ['array'],
'MongoCursor::fields' => ['MongoCursor', 'f'=>'array'],
'MongoCursor::getNext' => ['array'],
'MongoCursor::getReadPreference' => ['array'],
'MongoCursor::hasNext' => ['bool'],
'MongoCursor::hint' => ['MongoCursor', 'key_pattern'=>'string|array|object'],
'MongoCursor::immortal' => ['MongoCursor', 'liveforever='=>'bool'],
'MongoCursor::info' => ['array'],
'MongoCursor::key' => ['string'],
'MongoCursor::limit' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::maxTimeMS' => ['MongoCursor', 'ms'=>'int'],
'MongoCursor::next' => ['array'],
'MongoCursor::partial' => ['MongoCursor', 'okay='=>'bool'],
'MongoCursor::reset' => ['void'],
'MongoCursor::rewind' => ['void'],
'MongoCursor::setFlag' => ['MongoCursor', 'flag'=>'int', 'set='=>'bool'],
'MongoCursor::setReadPreference' => ['MongoCursor', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCursor::skip' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::slaveOkay' => ['MongoCursor', 'okay='=>'bool'],
'MongoCursor::snapshot' => ['MongoCursor'],
'MongoCursor::sort' => ['MongoCursor', 'fields'=>'array'],
'MongoCursor::tailable' => ['MongoCursor', 'tail='=>'bool'],
'MongoCursor::timeout' => ['MongoCursor', 'ms'=>'int'],
'MongoCursor::valid' => ['bool'],
'MongoCursorException::__clone' => ['void'],
'MongoCursorException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoCursorException::__toString' => ['string'],
'MongoCursorException::__wakeup' => ['void'],
'MongoCursorException::getCode' => ['int'],
'MongoCursorException::getFile' => ['string'],
'MongoCursorException::getHost' => ['string'],
'MongoCursorException::getLine' => ['int'],
'MongoCursorException::getMessage' => ['string'],
'MongoCursorException::getPrevious' => ['Exception|Throwable'],
'MongoCursorException::getTrace' => ['list<array<string,mixed>>'],
'MongoCursorException::getTraceAsString' => ['string'],
'MongoCursorInterface::__construct' => ['void'],
'MongoCursorInterface::batchSize' => ['MongoCursorInterface', 'batchSize'=>'int'],
'MongoCursorInterface::current' => ['mixed'],
'MongoCursorInterface::dead' => ['bool'],
'MongoCursorInterface::getReadPreference' => ['array'],
'MongoCursorInterface::info' => ['array'],
'MongoCursorInterface::key' => ['int|string'],
'MongoCursorInterface::next' => ['void'],
'MongoCursorInterface::rewind' => ['void'],
'MongoCursorInterface::setReadPreference' => ['MongoCursorInterface', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCursorInterface::timeout' => ['MongoCursorInterface', 'ms'=>'int'],
'MongoCursorInterface::valid' => ['bool'],
'MongoDate::__construct' => ['void', 'second='=>'int', 'usecond='=>'int'],
'MongoDate::__toString' => ['string'],
'MongoDate::toDateTime' => ['DateTime'],
'MongoDB::__construct' => ['void', 'conn'=>'MongoClient', 'name'=>'string'],
'MongoDB::__get' => ['MongoCollection', 'name'=>'string'],
'MongoDB::__toString' => ['string'],
'MongoDB::authenticate' => ['array', 'username'=>'string', 'password'=>'string'],
'MongoDB::command' => ['array', 'command'=>'array'],
'MongoDB::createCollection' => ['MongoCollection', 'name'=>'string', 'capped='=>'bool', 'size='=>'int', 'max='=>'int'],
'MongoDB::createDBRef' => ['array', 'collection'=>'string', 'a'=>'mixed'],
'MongoDB::drop' => ['array'],
'MongoDB::dropCollection' => ['array', 'coll'=>'MongoCollection|string'],
'MongoDB::execute' => ['array', 'code'=>'MongoCode|string', 'args='=>'array'],
'MongoDB::forceError' => ['bool'],
'MongoDB::getCollectionInfo' => ['array', 'options='=>'array'],
'MongoDB::getCollectionNames' => ['array', 'options='=>'array'],
'MongoDB::getDBRef' => ['array', 'ref'=>'array'],
'MongoDB::getGridFS' => ['MongoGridFS', 'prefix='=>'string'],
'MongoDB::getProfilingLevel' => ['int'],
'MongoDB::getReadPreference' => ['array'],
'MongoDB::getSlaveOkay' => ['bool'],
'MongoDB::getWriteConcern' => ['array'],
'MongoDB::lastError' => ['array'],
'MongoDB::listCollections' => ['array'],
'MongoDB::prevError' => ['array'],
'MongoDB::repair' => ['array', 'preserve_cloned_files='=>'bool', 'backup_original_files='=>'bool'],
'MongoDB::resetError' => ['array'],
'MongoDB::selectCollection' => ['MongoCollection', 'name'=>'string'],
'MongoDB::setProfilingLevel' => ['int', 'level'=>'int'],
'MongoDB::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoDB::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoDB::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoDB\BSON\Binary::__construct' => ['void', 'data'=>'string', 'type'=>'int'],
'MongoDB\BSON\Binary::__toString' => ['string'],
'MongoDB\BSON\Binary::getData' => ['string'],
'MongoDB\BSON\Binary::getType' => ['int'],
'MongoDB\BSON\binary::jsonSerialize' => ['mixed'],
'MongoDB\BSON\binary::serialize' => ['string'],
'MongoDB\BSON\binary::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\binaryinterface::__toString' => ['string'],
'MongoDB\BSON\binaryinterface::getData' => ['string'],
'MongoDB\BSON\binaryinterface::getType' => ['int'],
'MongoDB\BSON\dbpointer::__construct' => ['void'],
'MongoDB\BSON\dbpointer::__toString' => ['string'],
'MongoDB\BSON\dbpointer::jsonSerialize' => ['mixed'],
'MongoDB\BSON\dbpointer::serialize' => ['string'],
'MongoDB\BSON\dbpointer::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Decimal128::__construct' => ['void', 'value='=>'string'],
'MongoDB\BSON\Decimal128::__toString' => ['string'],
'MongoDB\BSON\decimal128::jsonSerialize' => ['mixed'],
'MongoDB\BSON\decimal128::serialize' => ['string'],
'MongoDB\BSON\decimal128::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\decimal128interface::__toString' => ['string'],
'MongoDB\BSON\fromJSON' => ['string', 'json'=>'string'],
'MongoDB\BSON\fromPHP' => ['string', 'value'=>'array|object'],
'MongoDB\BSON\int64::__construct' => ['void'],
'MongoDB\BSON\int64::__toString' => ['string'],
'MongoDB\BSON\int64::jsonSerialize' => ['mixed'],
'MongoDB\BSON\int64::serialize' => ['string'],
'MongoDB\BSON\int64::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Javascript::__construct' => ['void', 'code'=>'string', 'scope='=>'array|object'],
'MongoDB\BSON\javascript::__toString' => ['string'],
'MongoDB\BSON\javascript::getCode' => ['string'],
'MongoDB\BSON\javascript::getScope' => ['?object'],
'MongoDB\BSON\javascript::jsonSerialize' => ['mixed'],
'MongoDB\BSON\javascript::serialize' => ['string'],
'MongoDB\BSON\javascript::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\javascriptinterface::__toString' => ['string'],
'MongoDB\BSON\javascriptinterface::getCode' => ['string'],
'MongoDB\BSON\javascriptinterface::getScope' => ['?object'],
'MongoDB\BSON\maxkey::__construct' => ['void'],
'MongoDB\BSON\maxkey::jsonSerialize' => ['mixed'],
'MongoDB\BSON\maxkey::serialize' => ['string'],
'MongoDB\BSON\maxkey::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\minkey::__construct' => ['void'],
'MongoDB\BSON\minkey::jsonSerialize' => ['mixed'],
'MongoDB\BSON\minkey::serialize' => ['string'],
'MongoDB\BSON\minkey::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\ObjectId::__construct' => ['void', 'id='=>'string'],
'MongoDB\BSON\ObjectId::__toString' => ['string'],
'MongoDB\BSON\objectid::getTimestamp' => ['int'],
'MongoDB\BSON\objectid::jsonSerialize' => ['mixed'],
'MongoDB\BSON\objectid::serialize' => ['string'],
'MongoDB\BSON\objectid::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\objectidinterface::__toString' => ['string'],
'MongoDB\BSON\objectidinterface::getTimestamp' => ['int'],
'MongoDB\BSON\Regex::__construct' => ['void', 'pattern'=>'string', 'flags='=>'string'],
'MongoDB\BSON\Regex::__toString' => ['string'],
'MongoDB\BSON\Regex::getFlags' => ['string'],
'MongoDB\BSON\Regex::getPattern' => ['string'],
'MongoDB\BSON\regex::jsonSerialize' => ['mixed'],
'MongoDB\BSON\regex::serialize' => ['string'],
'MongoDB\BSON\regex::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\regexinterface::__toString' => ['string'],
'MongoDB\BSON\regexinterface::getFlags' => ['string'],
'MongoDB\BSON\regexinterface::getPattern' => ['string'],
'MongoDB\BSON\Serializable::bsonSerialize' => ['array|object'],
'MongoDB\BSON\symbol::__construct' => ['void'],
'MongoDB\BSON\symbol::__toString' => ['string'],
'MongoDB\BSON\symbol::jsonSerialize' => ['mixed'],
'MongoDB\BSON\symbol::serialize' => ['string'],
'MongoDB\BSON\symbol::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Timestamp::__construct' => ['void', 'increment'=>'int', 'timestamp'=>'int'],
'MongoDB\BSON\Timestamp::__toString' => ['string'],
'MongoDB\BSON\timestamp::getIncrement' => ['int'],
'MongoDB\BSON\timestamp::getTimestamp' => ['int'],
'MongoDB\BSON\timestamp::jsonSerialize' => ['mixed'],
'MongoDB\BSON\timestamp::serialize' => ['string'],
'MongoDB\BSON\timestamp::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\timestampinterface::__toString' => ['string'],
'MongoDB\BSON\timestampinterface::getIncrement' => ['int'],
'MongoDB\BSON\timestampinterface::getTimestamp' => ['int'],
'MongoDB\BSON\toJSON' => ['string', 'bson'=>'string'],
'MongoDB\BSON\toPHP' => ['object', 'bson'=>'string', 'typeMap'=>'array'],
'MongoDB\BSON\undefined::__construct' => ['void'],
'MongoDB\BSON\undefined::__toString' => ['string'],
'MongoDB\BSON\undefined::jsonSerialize' => ['mixed'],
'MongoDB\BSON\undefined::serialize' => ['string'],
'MongoDB\BSON\undefined::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Unserializable::bsonUnserialize' => ['void', 'data'=>'array'],
'MongoDB\BSON\UTCDateTime::__construct' => ['void', 'milliseconds='=>'int|DateTimeInterface'],
'MongoDB\BSON\UTCDateTime::__toString' => ['string'],
'MongoDB\BSON\utcdatetime::jsonSerialize' => ['mixed'],
'MongoDB\BSON\utcdatetime::serialize' => ['string'],
'MongoDB\BSON\UTCDateTime::toDateTime' => ['DateTime'],
'MongoDB\BSON\utcdatetime::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\utcdatetimeinterface::__toString' => ['string'],
'MongoDB\BSON\utcdatetimeinterface::toDateTime' => ['DateTime'],
'MongoDB\Driver\BulkWrite::__construct' => ['void', 'ordered='=>'bool'],
'MongoDB\Driver\BulkWrite::count' => ['int'],
'MongoDB\Driver\BulkWrite::delete' => ['void', 'filter'=>'array|object', 'deleteOptions='=>'array'],
'MongoDB\Driver\BulkWrite::insert' => ['void|MongoDB\BSON\ObjectId', 'document'=>'array|object'],
'MongoDB\Driver\BulkWrite::update' => ['void', 'filter'=>'array|object', 'newObj'=>'array|object', 'updateOptions='=>'array'],
'MongoDB\Driver\Command::__construct' => ['void', 'document'=>'array|object'],
'MongoDB\Driver\Cursor::__construct' => ['void', 'server'=>'Server', 'responseDocument'=>'string'],
'MongoDB\Driver\Cursor::getId' => ['MongoDB\Driver\CursorId'],
'MongoDB\Driver\Cursor::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\Cursor::isDead' => ['bool'],
'MongoDB\Driver\Cursor::setTypeMap' => ['void', 'typemap'=>'array'],
'MongoDB\Driver\Cursor::toArray' => ['array'],
'MongoDB\Driver\CursorId::__construct' => ['void', 'id'=>'string'],
'MongoDB\Driver\CursorId::__toString' => ['string'],
'MongoDB\Driver\CursorId::serialize' => ['string'],
'MongoDB\Driver\CursorId::unserialize' => ['void', 'serialized'=>'string'],
'mongodb\driver\exception\commandexception::getResultDocument' => ['object'],
'MongoDB\Driver\Exception\RuntimeException::__clone' => ['void'],
'MongoDB\Driver\Exception\RuntimeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?RuntimeException|?Throwable'],
'MongoDB\Driver\Exception\RuntimeException::__toString' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::__wakeup' => ['void'],
'MongoDB\Driver\Exception\RuntimeException::getCode' => ['int'],
'MongoDB\Driver\Exception\RuntimeException::getFile' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::getLine' => ['int'],
'MongoDB\Driver\Exception\RuntimeException::getMessage' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::getPrevious' => ['RuntimeException|Throwable'],
'MongoDB\Driver\Exception\RuntimeException::getTrace' => ['list<array<string,mixed>>'],
'MongoDB\Driver\Exception\RuntimeException::getTraceAsString' => ['string'],
'mongodb\driver\exception\runtimeexception::hasErrorLabel' => ['bool', 'errorLabel'=>'string'],
'MongoDB\Driver\Exception\WriteException::__clone' => ['void'],
'MongoDB\Driver\Exception\WriteException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?RuntimeException|?Throwable'],
'MongoDB\Driver\Exception\WriteException::__toString' => ['string'],
'MongoDB\Driver\Exception\WriteException::__wakeup' => ['void'],
'MongoDB\Driver\Exception\WriteException::getCode' => ['int'],
'MongoDB\Driver\Exception\WriteException::getFile' => ['string'],
'MongoDB\Driver\Exception\WriteException::getLine' => ['int'],
'MongoDB\Driver\Exception\WriteException::getMessage' => ['string'],
'MongoDB\Driver\Exception\WriteException::getPrevious' => ['RuntimeException|Throwable'],
'MongoDB\Driver\Exception\WriteException::getTrace' => ['list<array<string,mixed>>'],
'MongoDB\Driver\Exception\WriteException::getTraceAsString' => ['string'],
'MongoDB\Driver\Exception\WriteException::getWriteResult' => ['MongoDB\Driver\WriteResult'],
'MongoDB\Driver\Manager::__construct' => ['void', 'uri'=>'string', 'options='=>'array', 'driverOptions='=>'array'],
'MongoDB\Driver\Manager::executeBulkWrite' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'bulk'=>'MongoDB\Driver\BulkWrite', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'readPreference='=>'MongoDB\Driver\ReadPreference'],
'MongoDB\Driver\Manager::executeDelete' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'filter'=>'array|object', 'deleteOptions='=>'array', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeInsert' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'document'=>'array|object', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeQuery' => ['MongoDB\Driver\Cursor', 'namespace'=>'string', 'query'=>'MongoDB\Driver\Query', 'readPreference='=>'MongoDB\Driver\ReadPreference'],
'mongodb\driver\manager::executeReadCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\manager::executeReadWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Manager::executeUpdate' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'filter'=>'array|object', 'newObj'=>'array|object', 'updateOptions='=>'array', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'mongodb\driver\manager::executeWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Manager::getReadConcern' => ['MongoDB\Driver\ReadConcern'],
'MongoDB\Driver\Manager::getReadPreference' => ['MongoDB\Driver\ReadPreference'],
'MongoDB\Driver\Manager::getServers' => ['MongoDB\Driver\Server[]'],
'MongoDB\Driver\Manager::getWriteConcern' => ['MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::selectServer' => ['MongoDB\Driver\Server', 'readPreference'=>'MongoDB\Driver\ReadPreference'],
'mongodb\driver\manager::startSession' => ['MongoDB\Driver\Session', 'options='=>'array'],
'mongodb\driver\monitoring\commandfailedevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getDurationMicros' => ['int'],
'mongodb\driver\monitoring\commandfailedevent::getError' => ['Exception'],
'mongodb\driver\monitoring\commandfailedevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getReply' => ['object'],
'mongodb\driver\monitoring\commandfailedevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getServer' => ['MongoDB\Driver\Server'],
'mongodb\driver\monitoring\commandstartedevent::getCommand' => ['object'],
'mongodb\driver\monitoring\commandstartedevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getDatabaseName' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getServer' => ['MongoDB\Driver\Server'],
'mongodb\driver\monitoring\commandsubscriber::commandFailed' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandFailedEvent'],
'mongodb\driver\monitoring\commandsubscriber::commandStarted' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandStartedEvent'],
'mongodb\driver\monitoring\commandsubscriber::commandSucceeded' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandSucceededEvent'],
'mongodb\driver\monitoring\commandsucceededevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getDurationMicros' => ['int'],
'mongodb\driver\monitoring\commandsucceededevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getReply' => ['object'],
'mongodb\driver\monitoring\commandsucceededevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\Query::__construct' => ['void', 'filter'=>'array|object', 'queryOptions='=>'array'],
'MongoDB\Driver\ReadConcern::__construct' => ['void', 'level='=>'string'],
'MongoDB\Driver\ReadConcern::bsonSerialize' => ['object'],
'MongoDB\Driver\ReadConcern::getLevel' => ['?string'],
'MongoDB\Driver\ReadConcern::isDefault' => ['bool'],
'MongoDB\Driver\ReadConcern::serialize' => ['string'],
'MongoDB\Driver\ReadConcern::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\Driver\ReadPreference::__construct' => ['void', 'mode'=>'string|int', 'tagSets='=>'array', 'options='=>'array'],
'MongoDB\Driver\ReadPreference::bsonSerialize' => ['object'],
'MongoDB\Driver\ReadPreference::getHedge' => ['object|null'],
'MongoDB\Driver\ReadPreference::getMaxStalenessSeconds' => ['int'],
'MongoDB\Driver\ReadPreference::getMode' => ['int'],
'MongoDB\Driver\ReadPreference::getModeString' => ['string'],
'MongoDB\Driver\ReadPreference::getTagSets' => ['array'],
'MongoDB\Driver\ReadPreference::serialize' => ['string'],
'MongoDB\Driver\ReadPreference::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\Driver\Server::__construct' => ['void', 'host'=>'string', 'port'=>'string', 'options='=>'array', 'driverOptions='=>'array'],
'MongoDB\Driver\Server::executeBulkWrite' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'zwrite'=>'BulkWrite'],
'MongoDB\Driver\Server::executeCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command'],
'MongoDB\Driver\Server::executeQuery' => ['MongoDB\Driver\Cursor', 'namespace'=>'string', 'zquery'=>'Query'],
'mongodb\driver\server::executeReadCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\server::executeReadWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\server::executeWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Server::getHost' => ['string'],
'MongoDB\Driver\Server::getInfo' => ['array'],
'MongoDB\Driver\Server::getLatency' => ['int'],
'MongoDB\Driver\Server::getPort' => ['int'],
'MongoDB\Driver\Server::getState' => [''],
'MongoDB\Driver\Server::getTags' => ['array'],
'MongoDB\Driver\Server::getType' => ['int'],
'MongoDB\Driver\Server::isArbiter' => ['bool'],
'MongoDB\Driver\Server::isDelayed' => [''],
'MongoDB\Driver\Server::isHidden' => ['bool'],
'MongoDB\Driver\Server::isPassive' => ['bool'],
'MongoDB\Driver\Server::isPrimary' => ['bool'],
'MongoDB\Driver\Server::isSecondary' => ['bool'],
'mongodb\driver\session::__construct' => ['void'],
'mongodb\driver\session::abortTransaction' => ['void'],
'mongodb\driver\session::advanceClusterTime' => ['void', 'clusterTime'=>'array|object'],
'mongodb\driver\session::advanceOperationTime' => ['void', 'operationTime'=>'MongoDB\BSON\TimestampInterface'],
'mongodb\driver\session::commitTransaction' => ['void'],
'mongodb\driver\session::endSession' => ['void'],
'mongodb\driver\session::getClusterTime' => ['?object'],
'mongodb\driver\session::getLogicalSessionId' => ['object'],
'mongodb\driver\session::getOperationTime' => ['MongoDB\BSON\Timestamp|null'],
'mongodb\driver\session::getTransactionOptions' => ['array|null'],
'mongodb\driver\session::getTransactionState' => ['string'],
'mongodb\driver\session::startTransaction' => ['void', 'options'=>'array|object'],
'MongoDB\Driver\WriteConcern::__construct' => ['void', 'wstring'=>'string', 'wtimeout='=>'int', 'journal='=>'bool', 'fsync='=>'bool'],
'MongoDB\Driver\WriteConcern::bsonSerialize' => ['object'],
'MongoDB\Driver\WriteConcern::getJournal' => ['?bool'],
'MongoDB\Driver\WriteConcern::getJurnal' => ['?bool'],
'MongoDB\Driver\WriteConcern::getW' => ['int|null|string'],
'MongoDB\Driver\WriteConcern::getWtimeout' => ['int'],
'MongoDB\Driver\WriteConcern::isDefault' => ['bool'],
'MongoDB\Driver\WriteConcern::serialize' => ['string'],
'MongoDB\Driver\WriteConcern::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\Driver\WriteConcernError::getCode' => ['int'],
'MongoDB\Driver\WriteConcernError::getInfo' => ['mixed'],
'MongoDB\Driver\WriteConcernError::getMessage' => ['string'],
'MongoDB\Driver\WriteError::getCode' => ['int'],
'MongoDB\Driver\WriteError::getIndex' => ['int'],
'MongoDB\Driver\WriteError::getInfo' => ['mixed'],
'MongoDB\Driver\WriteError::getMessage' => ['string'],
'MongoDB\Driver\WriteException::getWriteResult' => [''],
'MongoDB\Driver\WriteResult::getDeletedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getInfo' => [''],
'MongoDB\Driver\WriteResult::getInsertedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getMatchedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getModifiedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\WriteResult::getUpsertedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getUpsertedIds' => ['array'],
'MongoDB\Driver\WriteResult::getWriteConcernError' => ['MongoDB\Driver\WriteConcernError|null'],
'MongoDB\Driver\WriteResult::getWriteErrors' => ['MongoDB\Driver\WriteError[]'],
'MongoDB\Driver\WriteResult::isAcknowledged' => ['bool'],
'MongoDBRef::create' => ['array', 'collection'=>'string', 'id'=>'mixed', 'database='=>'string'],
'MongoDBRef::get' => ['?array', 'db'=>'MongoDB', 'ref'=>'array'],
'MongoDBRef::isRef' => ['bool', 'ref'=>'mixed'],
'MongoDeleteBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoException::__clone' => ['void'],
'MongoException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoException::__toString' => ['string'],
'MongoException::__wakeup' => ['void'],
'MongoException::getCode' => ['int'],
'MongoException::getFile' => ['string'],
'MongoException::getLine' => ['int'],
'MongoException::getMessage' => ['string'],
'MongoException::getPrevious' => ['Exception|Throwable'],
'MongoException::getTrace' => ['list<array<string,mixed>>'],
'MongoException::getTraceAsString' => ['string'],
'MongoGridFS::__construct' => ['void', 'db'=>'MongoDB', 'prefix='=>'string', 'chunks='=>'mixed'],
'MongoGridFS::__get' => ['MongoCollection', 'name'=>'string'],
'MongoGridFS::__toString' => ['string'],
'MongoGridFS::aggregate' => ['array', 'pipeline'=>'array', 'op'=>'array', 'pipelineOperators'=>'array'],
'MongoGridFS::aggregateCursor' => ['MongoCommandCursor', 'pipeline'=>'array', 'options'=>'array'],
'MongoGridFS::batchInsert' => ['mixed', 'a'=>'array', 'options='=>'array'],
'MongoGridFS::count' => ['int', 'query='=>'stdClass|array'],
'MongoGridFS::createDBRef' => ['array', 'a'=>'array'],
'MongoGridFS::createIndex' => ['array', 'keys'=>'array', 'options='=>'array'],
'MongoGridFS::delete' => ['bool', 'id'=>'mixed'],
'MongoGridFS::deleteIndex' => ['array', 'keys'=>'array|string'],
'MongoGridFS::deleteIndexes' => ['array'],
'MongoGridFS::distinct' => ['array|bool', 'key'=>'string', 'query='=>'?array'],
'MongoGridFS::drop' => ['array'],
'MongoGridFS::ensureIndex' => ['bool', 'keys'=>'array', 'options='=>'array'],
'MongoGridFS::find' => ['MongoGridFSCursor', 'query='=>'array', 'fields='=>'array'],
'MongoGridFS::findAndModify' => ['array', 'query'=>'array', 'update='=>'?array', 'fields='=>'?array', 'options='=>'?array'],
'MongoGridFS::findOne' => ['?MongoGridFSFile', 'query='=>'mixed', 'fields='=>'mixed'],
'MongoGridFS::get' => ['?MongoGridFSFile', 'id'=>'mixed'],
'MongoGridFS::getDBRef' => ['array', 'ref'=>'array'],
'MongoGridFS::getIndexInfo' => ['array'],
'MongoGridFS::getName' => ['string'],
'MongoGridFS::getReadPreference' => ['array'],
'MongoGridFS::getSlaveOkay' => ['bool'],
'MongoGridFS::group' => ['array', 'keys'=>'mixed', 'initial'=>'array', 'reduce'=>'MongoCode', 'condition='=>'array'],
'MongoGridFS::insert' => ['array|bool', 'a'=>'array|object', 'options='=>'array'],
'MongoGridFS::put' => ['mixed', 'filename'=>'string', 'extra='=>'array'],
'MongoGridFS::remove' => ['bool', 'criteria='=>'array', 'options='=>'array'],
'MongoGridFS::save' => ['array|bool', 'a'=>'array|object', 'options='=>'array'],
'MongoGridFS::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags'=>'array'],
'MongoGridFS::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoGridFS::storeBytes' => ['mixed', 'bytes'=>'string', 'extra='=>'array', 'options='=>'array'],
'MongoGridFS::storeFile' => ['mixed', 'filename'=>'string', 'extra='=>'array', 'options='=>'array'],
'MongoGridFS::storeUpload' => ['mixed', 'name'=>'string', 'filename='=>'string'],
'MongoGridFS::toIndexString' => ['string', 'keys'=>'mixed'],
'MongoGridFS::update' => ['bool', 'criteria'=>'array', 'newobj'=>'array', 'options='=>'array'],
'MongoGridFS::validate' => ['array', 'scan_data='=>'bool'],
'MongoGridFSCursor::__construct' => ['void', 'gridfs'=>'MongoGridFS', 'connection'=>'resource', 'ns'=>'string', 'query'=>'array', 'fields'=>'array'],
'MongoGridFSCursor::addOption' => ['MongoCursor', 'key'=>'string', 'value'=>'mixed'],
'MongoGridFSCursor::awaitData' => ['MongoCursor', 'wait='=>'bool'],
'MongoGridFSCursor::batchSize' => ['MongoCursor', 'batchSize'=>'int'],
'MongoGridFSCursor::count' => ['int', 'all='=>'bool'],
'MongoGridFSCursor::current' => ['MongoGridFSFile'],
'MongoGridFSCursor::dead' => ['bool'],
'MongoGridFSCursor::doQuery' => ['void'],
'MongoGridFSCursor::explain' => ['array'],
'MongoGridFSCursor::fields' => ['MongoCursor', 'f'=>'array'],
'MongoGridFSCursor::getNext' => ['MongoGridFSFile'],
'MongoGridFSCursor::getReadPreference' => ['array'],
'MongoGridFSCursor::hasNext' => ['bool'],
'MongoGridFSCursor::hint' => ['MongoCursor', 'key_pattern'=>'mixed'],
'MongoGridFSCursor::immortal' => ['MongoCursor', 'liveForever='=>'bool'],
'MongoGridFSCursor::info' => ['array'],
'MongoGridFSCursor::key' => ['string'],
'MongoGridFSCursor::limit' => ['MongoCursor', 'num'=>'int'],
'MongoGridFSCursor::maxTimeMS' => ['MongoCursor', 'ms'=>'int'],
'MongoGridFSCursor::next' => ['void'],
'MongoGridFSCursor::partial' => ['MongoCursor', 'okay='=>'bool'],
'MongoGridFSCursor::reset' => ['void'],
'MongoGridFSCursor::rewind' => ['void'],
'MongoGridFSCursor::setFlag' => ['MongoCursor', 'flag'=>'int', 'set='=>'bool'],
'MongoGridFSCursor::setReadPreference' => ['MongoCursor', 'read_preference'=>'string', 'tags'=>'array'],
'MongoGridFSCursor::skip' => ['MongoCursor', 'num'=>'int'],
'MongoGridFSCursor::slaveOkay' => ['MongoCursor', 'okay='=>'bool'],
'MongoGridFSCursor::snapshot' => ['MongoCursor'],
'MongoGridFSCursor::sort' => ['MongoCursor', 'fields'=>'array'],
'MongoGridFSCursor::tailable' => ['MongoCursor', 'tail='=>'bool'],
'MongoGridFSCursor::timeout' => ['MongoCursor', 'ms'=>'int'],
'MongoGridFSCursor::valid' => ['bool'],
'MongoGridfsFile::__construct' => ['void', 'gridfs'=>'MongoGridFS', 'file'=>'array'],
'MongoGridFSFile::getBytes' => ['string'],
'MongoGridFSFile::getFilename' => ['string'],
'MongoGridFSFile::getResource' => ['resource'],
'MongoGridFSFile::getSize' => ['int'],
'MongoGridFSFile::write' => ['int', 'filename='=>'string'],
'MongoId::__construct' => ['void', 'id='=>'string|MongoId'],
'MongoId::__set_state' => ['MongoId', 'props'=>'array'],
'MongoId::__toString' => ['string'],
'MongoId::getHostname' => ['string'],
'MongoId::getInc' => ['int'],
'MongoId::getPID' => ['int'],
'MongoId::getTimestamp' => ['int'],
'MongoId::isValid' => ['bool', 'value'=>'mixed'],
'MongoInsertBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoInt32::__construct' => ['void', 'value'=>'string'],
'MongoInt32::__toString' => ['string'],
'MongoInt64::__construct' => ['void', 'value'=>'string'],
'MongoInt64::__toString' => ['string'],
'MongoLog::getCallback' => ['callable'],
'MongoLog::getLevel' => ['int'],
'MongoLog::getModule' => ['int'],
'MongoLog::setCallback' => ['void', 'log_function'=>'callable'],
'MongoLog::setLevel' => ['void', 'level'=>'int'],
'MongoLog::setModule' => ['void', 'module'=>'int'],
'MongoPool::getSize' => ['int'],
'MongoPool::info' => ['array'],
'MongoPool::setSize' => ['bool', 'size'=>'int'],
'MongoRegex::__construct' => ['void', 'regex'=>'string'],
'MongoRegex::__toString' => ['string'],
'MongoResultException::__clone' => ['void'],
'MongoResultException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoResultException::__toString' => ['string'],
'MongoResultException::__wakeup' => ['void'],
'MongoResultException::getCode' => ['int'],
'MongoResultException::getDocument' => ['array'],
'MongoResultException::getFile' => ['string'],
'MongoResultException::getLine' => ['int'],
'MongoResultException::getMessage' => ['string'],
'MongoResultException::getPrevious' => ['Exception|Throwable'],
'MongoResultException::getTrace' => ['list<array<string,mixed>>'],
'MongoResultException::getTraceAsString' => ['string'],
'MongoTimestamp::__construct' => ['void', 'second='=>'int', 'inc='=>'int'],
'MongoTimestamp::__toString' => ['string'],
'MongoUpdateBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoUpdateBatch::add' => ['bool', 'item'=>'array'],
'MongoUpdateBatch::execute' => ['array', 'write_options'=>'array'],
'MongoWriteBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'batch_type'=>'string', 'write_options'=>'array'],
'MongoWriteBatch::add' => ['bool', 'item'=>'array'],
'MongoWriteBatch::execute' => ['array', 'write_options'=>'array'],
'MongoWriteConcernException::__clone' => ['void'],
'MongoWriteConcernException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoWriteConcernException::__toString' => ['string'],
'MongoWriteConcernException::__wakeup' => ['void'],
'MongoWriteConcernException::getCode' => ['int'],
'MongoWriteConcernException::getDocument' => ['array'],
'MongoWriteConcernException::getFile' => ['string'],
'MongoWriteConcernException::getLine' => ['int'],
'MongoWriteConcernException::getMessage' => ['string'],
'MongoWriteConcernException::getPrevious' => ['Exception|Throwable'],
'MongoWriteConcernException::getTrace' => ['list<array<string,mixed>>'],
'MongoWriteConcernException::getTraceAsString' => ['string'],
'monitor_custom_event' => ['void', 'class'=>'string', 'text'=>'string', 'severe='=>'int', 'user_data='=>'mixed'],
'monitor_httperror_event' => ['void', 'error_code'=>'int', 'url'=>'string', 'severe='=>'int'],
'monitor_license_info' => ['array'],
'monitor_pass_error' => ['void', 'errno'=>'int', 'errstr'=>'string', 'errfile'=>'string', 'errline'=>'int'],
'monitor_set_aggregation_hint' => ['void', 'hint'=>'string'],
'move_uploaded_file' => ['bool', 'from'=>'string', 'to'=>'string'],
'mqseries_back' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_begin' => ['void', 'hconn'=>'resource', 'beginoptions'=>'array', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_close' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'options'=>'int', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_cmit' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_conn' => ['void', 'qmanagername'=>'string', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_connx' => ['void', 'qmanagername'=>'string', 'connoptions'=>'array', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_disc' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_get' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'md'=>'array', 'gmo'=>'array', 'bufferlength'=>'int', 'msg'=>'string', 'data_length'=>'int', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_inq' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'selectorcount'=>'int', 'selectors'=>'array', 'intattrcount'=>'int', 'intattr'=>'resource', 'charattrlength'=>'int', 'charattr'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_open' => ['void', 'hconn'=>'resource', 'objdesc'=>'array', 'option'=>'int', 'hobj'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_put' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'md'=>'array', 'pmo'=>'array', 'message'=>'string', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_put1' => ['void', 'hconn'=>'resource', 'objdesc'=>'resource', 'msgdesc'=>'resource', 'pmo'=>'resource', 'buffer'=>'string', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_set' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'selectorcount'=>'int', 'selectors'=>'array', 'intattrcount'=>'int', 'intattrs'=>'array', 'charattrlength'=>'int', 'charattrs'=>'array', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_strerror' => ['string', 'reason'=>'int'],
'ms_GetErrorObj' => ['errorObj'],
'ms_GetVersion' => ['string'],
'ms_GetVersionInt' => ['int'],
'ms_iogetStdoutBufferBytes' => ['int'],
'ms_iogetstdoutbufferstring' => ['void'],
'ms_ioinstallstdinfrombuffer' => ['void'],
'ms_ioinstallstdouttobuffer' => ['void'],
'ms_ioresethandlers' => ['void'],
'ms_iostripstdoutbuffercontentheaders' => ['void'],
'ms_iostripstdoutbuffercontenttype' => ['string'],
'ms_ResetErrorList' => ['void'],
'ms_TokenizeMap' => ['array', 'map_file_name'=>'string'],
'msession_connect' => ['bool', 'host'=>'string', 'port'=>'string'],
'msession_count' => ['int'],
'msession_create' => ['bool', 'session'=>'string', 'classname='=>'string', 'data='=>'string'],
'msession_destroy' => ['bool', 'name'=>'string'],
'msession_disconnect' => ['void'],
'msession_find' => ['array', 'name'=>'string', 'value'=>'string'],
'msession_get' => ['string', 'session'=>'string', 'name'=>'string', 'value'=>'string'],
'msession_get_array' => ['array', 'session'=>'string'],
'msession_get_data' => ['string', 'session'=>'string'],
'msession_inc' => ['string', 'session'=>'string', 'name'=>'string'],
'msession_list' => ['array'],
'msession_listvar' => ['array', 'name'=>'string'],
'msession_lock' => ['int', 'name'=>'string'],
'msession_plugin' => ['string', 'session'=>'string', 'value'=>'string', 'param='=>'string'],
'msession_randstr' => ['string', 'param'=>'int'],
'msession_set' => ['bool', 'session'=>'string', 'name'=>'string', 'value'=>'string'],
'msession_set_array' => ['void', 'session'=>'string', 'tuples'=>'array'],
'msession_set_data' => ['bool', 'session'=>'string', 'value'=>'string'],
'msession_timeout' => ['int', 'session'=>'string', 'param='=>'int'],
'msession_uniq' => ['string', 'param'=>'int', 'classname='=>'string', 'data='=>'string'],
'msession_unlock' => ['int', 'session'=>'string', 'key'=>'int'],
'msg_get_queue' => ['resource', 'key'=>'int', 'permissions='=>'int'],
'msg_queue_exists' => ['bool', 'key'=>'int'],
'msg_receive' => ['bool', 'queue'=>'resource', 'desired_message_type'=>'int', '&w_received_message_type'=>'int', 'max_message_size'=>'int', '&w_message'=>'mixed', 'unserialize='=>'bool', 'flags='=>'int', '&w_error_code='=>'int'],
'msg_remove_queue' => ['bool', 'queue'=>'resource'],
'msg_send' => ['bool', 'queue'=>'resource', 'message_type'=>'int', 'message'=>'mixed', 'serialize='=>'bool', 'blocking='=>'bool', '&w_error_code='=>'int'],
'msg_set_queue' => ['bool', 'queue'=>'resource', 'data'=>'array'],
'msg_stat_queue' => ['array', 'queue'=>'resource'],
'msgfmt_create' => ['MessageFormatter', 'locale'=>'string', 'pattern'=>'string'],
'msgfmt_format' => ['string|false', 'formatter'=>'MessageFormatter', 'values'=>'array'],
'msgfmt_format_message' => ['string|false', 'locale'=>'string', 'pattern'=>'string', 'values'=>'array'],
'msgfmt_get_error_code' => ['int', 'formatter'=>'MessageFormatter'],
'msgfmt_get_error_message' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_get_locale' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_get_pattern' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_parse' => ['array|false', 'formatter'=>'MessageFormatter', 'string'=>'string'],
'msgfmt_parse_message' => ['array|false', 'locale'=>'string', 'pattern'=>'string', 'message'=>'string'],
'msgfmt_set_pattern' => ['bool', 'formatter'=>'MessageFormatter', 'pattern'=>'string'],
'msql_affected_rows' => ['int', 'result'=>'resource'],
'msql_close' => ['bool', 'link_identifier='=>'?resource'],
'msql_connect' => ['resource', 'hostname='=>'string'],
'msql_create_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'msql_data_seek' => ['bool', 'result'=>'resource', 'row_number'=>'int'],
'msql_db_query' => ['resource', 'database'=>'string', 'query'=>'string', 'link_identifier='=>'?resource'],
'msql_drop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'msql_error' => ['string'],
'msql_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'msql_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'msql_fetch_object' => ['object', 'result'=>'resource'],
'msql_fetch_row' => ['array', 'result'=>'resource'],
'msql_field_flags' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_len' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_name' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_seek' => ['bool', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_table' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_type' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_free_result' => ['bool', 'result'=>'resource'],
'msql_list_dbs' => ['resource', 'link_identifier='=>'?resource'],
'msql_list_fields' => ['resource', 'database'=>'string', 'tablename'=>'string', 'link_identifier='=>'?resource'],
'msql_list_tables' => ['resource', 'database'=>'string', 'link_identifier='=>'?resource'],
'msql_num_fields' => ['int', 'result'=>'resource'],
'msql_num_rows' => ['int', 'query_identifier'=>'resource'],
'msql_pconnect' => ['resource', 'hostname='=>'string'],
'msql_query' => ['resource', 'query'=>'string', 'link_identifier='=>'?resource'],
'msql_result' => ['string', 'result'=>'resource', 'row'=>'int', 'field='=>'mixed'],
'msql_select_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'mt_getrandmax' => ['int'],
'mt_rand' => ['int', 'min'=>'int', 'max'=>'int'],
'mt_rand\'1' => ['int'],
'mt_srand' => ['void', 'seed='=>'int', 'mode='=>'int'],
'MultipleIterator::__construct' => ['void', 'flags='=>'int'],
'MultipleIterator::attachIterator' => ['void', 'iterator'=>'Iterator', 'infos='=>'string'],
'MultipleIterator::containsIterator' => ['bool', 'iterator'=>'Iterator'],
'MultipleIterator::countIterators' => ['int'],
'MultipleIterator::current' => ['array|false'],
'MultipleIterator::detachIterator' => ['void', 'iterator'=>'Iterator'],
'MultipleIterator::getFlags' => ['int'],
'MultipleIterator::key' => ['array'],
'MultipleIterator::next' => ['void'],
'MultipleIterator::rewind' => ['void'],
'MultipleIterator::setFlags' => ['int', 'flags'=>'int'],
'MultipleIterator::valid' => ['bool'],
'Mutex::create' => ['long', 'lock='=>'bool'],
'Mutex::destroy' => ['bool', 'mutex'=>'long'],
'Mutex::lock' => ['bool', 'mutex'=>'long'],
'Mutex::trylock' => ['bool', 'mutex'=>'long'],
'Mutex::unlock' => ['bool', 'mutex'=>'long', 'destroy='=>'bool'],
'mysql_xdevapi\baseresult::getWarnings' => ['array'],
'mysql_xdevapi\baseresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\collection::add' => ['mysql_xdevapi\CollectionAdd', 'document'=>'mixed'],
'mysql_xdevapi\collection::addOrReplaceOne' => ['mysql_xdevapi\Result', 'id'=>'string', 'doc'=>'string'],
'mysql_xdevapi\collection::count' => ['integer'],
'mysql_xdevapi\collection::createIndex' => ['void', 'index_name'=>'string', 'index_desc_json'=>'string'],
'mysql_xdevapi\collection::dropIndex' => ['bool', 'index_name'=>'string'],
'mysql_xdevapi\collection::existsInDatabase' => ['bool'],
'mysql_xdevapi\collection::find' => ['mysql_xdevapi\CollectionFind', 'search_condition='=>'string'],
'mysql_xdevapi\collection::getName' => ['string'],
'mysql_xdevapi\collection::getOne' => ['Document', 'id'=>'string'],
'mysql_xdevapi\collection::getSchema' => ['mysql_xdevapi\schema'],
'mysql_xdevapi\collection::getSession' => ['Session'],
'mysql_xdevapi\collection::modify' => ['mysql_xdevapi\CollectionModify', 'search_condition'=>'string'],
'mysql_xdevapi\collection::remove' => ['mysql_xdevapi\CollectionRemove', 'search_condition'=>'string'],
'mysql_xdevapi\collection::removeOne' => ['mysql_xdevapi\Result', 'id'=>'string'],
'mysql_xdevapi\collection::replaceOne' => ['mysql_xdevapi\Result', 'id'=>'string', 'doc'=>'string'],
'mysql_xdevapi\collectionadd::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionfind::bind' => ['mysql_xdevapi\CollectionFind', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionfind::execute' => ['mysql_xdevapi\DocResult'],
'mysql_xdevapi\collectionfind::fields' => ['mysql_xdevapi\CollectionFind', 'projection'=>'string'],
'mysql_xdevapi\collectionfind::groupBy' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionfind::having' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionfind::limit' => ['mysql_xdevapi\CollectionFind', 'rows'=>'integer'],
'mysql_xdevapi\collectionfind::lockExclusive' => ['mysql_xdevapi\CollectionFind', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\collectionfind::lockShared' => ['mysql_xdevapi\CollectionFind', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\collectionfind::offset' => ['mysql_xdevapi\CollectionFind', 'position'=>'integer'],
'mysql_xdevapi\collectionfind::sort' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionmodify::arrayAppend' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::arrayInsert' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::bind' => ['mysql_xdevapi\CollectionModify', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionmodify::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionmodify::limit' => ['mysql_xdevapi\CollectionModify', 'rows'=>'integer'],
'mysql_xdevapi\collectionmodify::patch' => ['mysql_xdevapi\CollectionModify', 'document'=>'string'],
'mysql_xdevapi\collectionmodify::replace' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::set' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::skip' => ['mysql_xdevapi\CollectionModify', 'position'=>'integer'],
'mysql_xdevapi\collectionmodify::sort' => ['mysql_xdevapi\CollectionModify', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionmodify::unset' => ['mysql_xdevapi\CollectionModify', 'fields'=>'array'],
'mysql_xdevapi\collectionremove::bind' => ['mysql_xdevapi\CollectionRemove', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionremove::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionremove::limit' => ['mysql_xdevapi\CollectionRemove', 'rows'=>'integer'],
'mysql_xdevapi\collectionremove::sort' => ['mysql_xdevapi\CollectionRemove', 'sort_expr'=>'string'],
'mysql_xdevapi\columnresult::getCharacterSetName' => ['string'],
'mysql_xdevapi\columnresult::getCollationName' => ['string'],
'mysql_xdevapi\columnresult::getColumnLabel' => ['string'],
'mysql_xdevapi\columnresult::getColumnName' => ['string'],
'mysql_xdevapi\columnresult::getFractionalDigits' => ['integer'],
'mysql_xdevapi\columnresult::getLength' => ['integer'],
'mysql_xdevapi\columnresult::getSchemaName' => ['string'],
'mysql_xdevapi\columnresult::getTableLabel' => ['string'],
'mysql_xdevapi\columnresult::getTableName' => ['string'],
'mysql_xdevapi\columnresult::getType' => ['integer'],
'mysql_xdevapi\columnresult::isNumberSigned' => ['integer'],
'mysql_xdevapi\columnresult::isPadded' => ['integer'],
'mysql_xdevapi\crudoperationbindable::bind' => ['mysql_xdevapi\CrudOperationBindable', 'placeholder_values'=>'array'],
'mysql_xdevapi\crudoperationlimitable::limit' => ['mysql_xdevapi\CrudOperationLimitable', 'rows'=>'integer'],
'mysql_xdevapi\crudoperationskippable::skip' => ['mysql_xdevapi\CrudOperationSkippable', 'skip'=>'integer'],
'mysql_xdevapi\crudoperationsortable::sort' => ['mysql_xdevapi\CrudOperationSortable', 'sort_expr'=>'string'],
'mysql_xdevapi\databaseobject::existsInDatabase' => ['bool'],
'mysql_xdevapi\databaseobject::getName' => ['string'],
'mysql_xdevapi\databaseobject::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\docresult::fetchAll' => ['Array'],
'mysql_xdevapi\docresult::fetchOne' => ['Object'],
'mysql_xdevapi\docresult::getWarnings' => ['Array'],
'mysql_xdevapi\docresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\executable::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\getsession' => ['mysql_xdevapi\Session', 'uri'=>'string'],
'mysql_xdevapi\result::getAutoIncrementValue' => ['int'],
'mysql_xdevapi\result::getGeneratedIds' => ['ArrayOfInt'],
'mysql_xdevapi\result::getWarnings' => ['array'],
'mysql_xdevapi\result::getWarningsCount' => ['integer'],
'mysql_xdevapi\rowresult::fetchAll' => ['array'],
'mysql_xdevapi\rowresult::fetchOne' => ['object'],
'mysql_xdevapi\rowresult::getColumnCount' => ['integer'],
'mysql_xdevapi\rowresult::getColumnNames' => ['array'],
'mysql_xdevapi\rowresult::getColumns' => ['array'],
'mysql_xdevapi\rowresult::getWarnings' => ['array'],
'mysql_xdevapi\rowresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\schema::createCollection' => ['mysql_xdevapi\Collection', 'name'=>'string'],
'mysql_xdevapi\schema::dropCollection' => ['bool', 'collection_name'=>'string'],
'mysql_xdevapi\schema::existsInDatabase' => ['bool'],
'mysql_xdevapi\schema::getCollection' => ['mysql_xdevapi\Collection', 'name'=>'string'],
'mysql_xdevapi\schema::getCollectionAsTable' => ['mysql_xdevapi\Table', 'name'=>'string'],
'mysql_xdevapi\schema::getCollections' => ['array'],
'mysql_xdevapi\schema::getName' => ['string'],
'mysql_xdevapi\schema::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\schema::getTable' => ['mysql_xdevapi\Table', 'name'=>'string'],
'mysql_xdevapi\schema::getTables' => ['array'],
'mysql_xdevapi\schemaobject::getSchema' => ['mysql_xdevapi\Schema'],
'mysql_xdevapi\session::close' => ['bool'],
'mysql_xdevapi\session::commit' => ['Object'],
'mysql_xdevapi\session::createSchema' => ['mysql_xdevapi\Schema', 'schema_name'=>'string'],
'mysql_xdevapi\session::dropSchema' => ['bool', 'schema_name'=>'string'],
'mysql_xdevapi\session::executeSql' => ['Object', 'statement'=>'string'],
'mysql_xdevapi\session::generateUUID' => ['string'],
'mysql_xdevapi\session::getClientId' => ['integer'],
'mysql_xdevapi\session::getSchema' => ['mysql_xdevapi\Schema', 'schema_name'=>'string'],
'mysql_xdevapi\session::getSchemas' => ['array'],
'mysql_xdevapi\session::getServerVersion' => ['integer'],
'mysql_xdevapi\session::killClient' => ['object', 'client_id'=>'integer'],
'mysql_xdevapi\session::listClients' => ['array'],
'mysql_xdevapi\session::quoteName' => ['string', 'name'=>'string'],
'mysql_xdevapi\session::releaseSavepoint' => ['void', 'name'=>'string'],
'mysql_xdevapi\session::rollback' => ['void'],
'mysql_xdevapi\session::rollbackTo' => ['void', 'name'=>'string'],
'mysql_xdevapi\session::setSavepoint' => ['string', 'name='=>'string'],
'mysql_xdevapi\session::sql' => ['mysql_xdevapi\SqlStatement', 'query'=>'string'],
'mysql_xdevapi\session::startTransaction' => ['void'],
'mysql_xdevapi\sqlstatement::bind' => ['mysql_xdevapi\SqlStatement', 'param'=>'string'],
'mysql_xdevapi\sqlstatement::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::getNextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::getResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::hasMoreResults' => ['bool'],
'mysql_xdevapi\sqlstatementresult::fetchAll' => ['array'],
'mysql_xdevapi\sqlstatementresult::fetchOne' => ['object'],
'mysql_xdevapi\sqlstatementresult::getAffectedItemsCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::getColumnCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::getColumnNames' => ['array'],
'mysql_xdevapi\sqlstatementresult::getColumns' => ['Array'],
'mysql_xdevapi\sqlstatementresult::getGeneratedIds' => ['array'],
'mysql_xdevapi\sqlstatementresult::getLastInsertId' => ['String'],
'mysql_xdevapi\sqlstatementresult::getWarnings' => ['array'],
'mysql_xdevapi\sqlstatementresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::hasData' => ['bool'],
'mysql_xdevapi\sqlstatementresult::nextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::getNextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::getResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::hasMoreResults' => ['bool'],
'mysql_xdevapi\table::count' => ['integer'],
'mysql_xdevapi\table::delete' => ['mysql_xdevapi\TableDelete'],
'mysql_xdevapi\table::existsInDatabase' => ['bool'],
'mysql_xdevapi\table::getName' => ['string'],
'mysql_xdevapi\table::getSchema' => ['mysql_xdevapi\Schema'],
'mysql_xdevapi\table::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\table::insert' => ['mysql_xdevapi\TableInsert', 'columns'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\table::isView' => ['bool'],
'mysql_xdevapi\table::select' => ['mysql_xdevapi\TableSelect', 'columns'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\table::update' => ['mysql_xdevapi\TableUpdate'],
'mysql_xdevapi\tabledelete::bind' => ['mysql_xdevapi\TableDelete', 'placeholder_values'=>'array'],
'mysql_xdevapi\tabledelete::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\tabledelete::limit' => ['mysql_xdevapi\TableDelete', 'rows'=>'integer'],
'mysql_xdevapi\tabledelete::offset' => ['mysql_xdevapi\TableDelete', 'position'=>'integer'],
'mysql_xdevapi\tabledelete::orderby' => ['mysql_xdevapi\TableDelete', 'orderby_expr'=>'string'],
'mysql_xdevapi\tabledelete::where' => ['mysql_xdevapi\TableDelete', 'where_expr'=>'string'],
'mysql_xdevapi\tableinsert::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\tableinsert::values' => ['mysql_xdevapi\TableInsert', 'row_values'=>'array'],
'mysql_xdevapi\tableselect::bind' => ['mysql_xdevapi\TableSelect', 'placeholder_values'=>'array'],
'mysql_xdevapi\tableselect::execute' => ['mysql_xdevapi\RowResult'],
'mysql_xdevapi\tableselect::groupBy' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'mixed'],
'mysql_xdevapi\tableselect::having' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'string'],
'mysql_xdevapi\tableselect::limit' => ['mysql_xdevapi\TableSelect', 'rows'=>'integer'],
'mysql_xdevapi\tableselect::lockExclusive' => ['mysql_xdevapi\TableSelect', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\tableselect::lockShared' => ['mysql_xdevapi\TableSelect', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\tableselect::offset' => ['mysql_xdevapi\TableSelect', 'position'=>'integer'],
'mysql_xdevapi\tableselect::orderby' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\tableselect::where' => ['mysql_xdevapi\TableSelect', 'where_expr'=>'string'],
'mysql_xdevapi\tableupdate::bind' => ['mysql_xdevapi\TableUpdate', 'placeholder_values'=>'array'],
'mysql_xdevapi\tableupdate::execute' => ['mysql_xdevapi\TableUpdate'],
'mysql_xdevapi\tableupdate::limit' => ['mysql_xdevapi\TableUpdate', 'rows'=>'integer'],
'mysql_xdevapi\tableupdate::orderby' => ['mysql_xdevapi\TableUpdate', 'orderby_expr'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\tableupdate::set' => ['mysql_xdevapi\TableUpdate', 'table_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\tableupdate::where' => ['mysql_xdevapi\TableUpdate', 'where_expr'=>'string'],
'mysqli::__construct' => ['void', 'hostname='=>'string', 'username='=>'string', 'password='=>'string', 'database='=>'string', 'port='=>'int', 'socket='=>'string'],
'mysqli::autocommit' => ['bool', 'enable'=>'bool'],
'mysqli::begin_transaction' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::change_user' => ['bool', 'username'=>'string', 'password'=>'string', 'database'=>'string'],
'mysqli::character_set_name' => ['string'],
'mysqli::close' => ['bool'],
'mysqli::commit' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::debug' => ['bool', 'options'=>'string'],
'mysqli::disable_reads_from_master' => ['bool'],
'mysqli::dump_debug_info' => ['bool'],
'mysqli::escape_string' => ['string', 'string'=>'string'],
'mysqli::get_charset' => ['object'],
'mysqli::get_client_info' => ['string'],
'mysqli::get_connection_stats' => ['array|false'],
'mysqli::get_warnings' => ['mysqli_warning'],
'mysqli::init' => ['mysqli'],
'mysqli::kill' => ['bool', 'process_id'=>'int'],
'mysqli::more_results' => ['bool'],
'mysqli::multi_query' => ['bool', 'query'=>'string'],
'mysqli::next_result' => ['bool'],
'mysqli::options' => ['bool', 'option'=>'int', 'value'=>'mixed'],
'mysqli::ping' => ['bool'],
'mysqli::poll' => ['int|false', '&w_read'=>'array', '&w_write'=>'array', '&w_error'=>'array', 'seconds'=>'int', 'microseconds='=>'int'],
'mysqli::prepare' => ['mysqli_stmt|false', 'query'=>'string'],
'mysqli::query' => ['bool|mysqli_result', 'query'=>'string', 'result_mode='=>'int'],
'mysqli::real_connect' => ['bool', 'hostname='=>'string|null', 'username='=>'string', 'password='=>'string|null', 'database='=>'string', 'port='=>'int', 'socket='=>'string', 'flags='=>'int'],
'mysqli::real_escape_string' => ['string', 'string'=>'string'],
'mysqli::real_query' => ['bool', 'query'=>'string'],
'mysqli::reap_async_query' => ['mysqli_result|false'],
'mysqli::refresh' => ['bool', 'flags'=>'int'],
'mysqli::release_savepoint' => ['bool', 'name'=>'string'],
'mysqli::rollback' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::rpl_query_type' => ['int', 'query'=>'string'],
'mysqli::savepoint' => ['bool', 'name'=>'string'],
'mysqli::select_db' => ['bool', 'database'=>'string'],
'mysqli::send_query' => ['bool', 'query'=>'string'],
'mysqli::set_charset' => ['bool', 'charset'=>'string'],
'mysqli::set_local_infile_default' => ['void'],
'mysqli::set_local_infile_handler' => ['bool', 'read_func='=>'callable'],
'mysqli::ssl_set' => ['bool', 'key'=>'string', 'certificate'=>'string', 'ca_certificate'=>'string', 'ca_path'=>'string', 'cipher_algos'=>'string'],
'mysqli::stat' => ['string|false'],
'mysqli::stmt_init' => ['mysqli_stmt'],
'mysqli::store_result' => ['mysqli_result|false', 'mode='=>'int'],
'mysqli::thread_safe' => ['bool'],
'mysqli::use_result' => ['mysqli_result|false'],
'mysqli_affected_rows' => ['int', 'mysql'=>'mysqli'],
'mysqli_autocommit' => ['bool', 'mysql'=>'mysqli', 'enable'=>'bool'],
'mysqli_begin_transaction' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_change_user' => ['bool', 'mysql'=>'mysqli', 'username'=>'string', 'password'=>'string', 'database'=>'?string'],
'mysqli_character_set_name' => ['string', 'mysql'=>'mysqli'],
'mysqli_close' => ['bool', 'mysql'=>'mysqli'],
'mysqli_commit' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_connect' => ['mysqli|false', 'hostname='=>'string', 'username='=>'string', 'password='=>'string', 'database='=>'string', 'port='=>'int', 'socket='=>'string'],
'mysqli_connect_errno' => ['int'],
'mysqli_connect_error' => ['string'],
'mysqli_data_seek' => ['bool', 'result'=>'mysqli_result', 'offset'=>'int'],
'mysqli_debug' => ['bool', 'options'=>'string'],
'mysqli_disable_reads_from_master' => ['bool', 'link'=>'mysqli'],
'mysqli_disable_rpl_parse' => ['bool', 'link'=>'mysqli'],
'mysqli_driver::embedded_server_end' => ['void'],
'mysqli_driver::embedded_server_start' => ['bool', 'start'=>'int', 'arguments'=>'array', 'groups'=>'array'],
'mysqli_dump_debug_info' => ['bool', 'mysql'=>'mysqli'],
'mysqli_embedded_server_end' => ['void'],
'mysqli_embedded_server_start' => ['bool', 'start'=>'int', 'arguments'=>'array', 'groups'=>'array'],
'mysqli_enable_reads_from_master' => ['bool', 'link'=>'mysqli'],
'mysqli_enable_rpl_parse' => ['bool', 'link'=>'mysqli'],
'mysqli_errno' => ['int', 'mysql'=>'mysqli'],
'mysqli_error' => ['string', 'mysql'=>'mysqli'],
'mysqli_error_list' => ['array', 'mysql'=>'mysqli'],
'mysqli_escape_string' => ['string', 'mysql'=>'mysqli', 'string'=>'string'],
'mysqli_execute' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_fetch_all' => ['array', 'result'=>'mysqli_result', 'mode='=>'int'],
'mysqli_fetch_array' => ['?array', 'result'=>'mysqli_result', 'mode='=>'int'],
'mysqli_fetch_assoc' => ['array<string,string>|null', 'result'=>'mysqli_result'],
'mysqli_fetch_field' => ['object|false', 'result'=>'mysqli_result'],
'mysqli_fetch_field_direct' => ['object|false', 'result'=>'mysqli_result', 'index'=>'int'],
'mysqli_fetch_fields' => ['array|false', 'result'=>'mysqli_result'],
'mysqli_fetch_lengths' => ['array|false', 'result'=>'mysqli_result'],
'mysqli_fetch_object' => ['?object', 'result'=>'mysqli_result', 'class='=>'string', 'constructor_args='=>'?array'],
'mysqli_fetch_row' => ['?array', 'result'=>'mysqli_result'],
'mysqli_field_count' => ['int', 'mysql'=>'mysqli'],
'mysqli_field_seek' => ['bool', 'result'=>'mysqli_result', 'index'=>'int'],
'mysqli_field_tell' => ['int', 'result'=>'mysqli_result'],
'mysqli_free_result' => ['void', 'result'=>'mysqli_result'],
'mysqli_get_cache_stats' => ['array|false'],
'mysqli_get_charset' => ['object', 'mysql'=>'mysqli'],
'mysqli_get_client_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_client_stats' => ['array|false'],
'mysqli_get_client_version' => ['int', 'link'=>'mysqli'],
'mysqli_get_connection_stats' => ['array|false', 'mysql'=>'mysqli'],
'mysqli_get_host_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_links_stats' => ['array'],
'mysqli_get_proto_info' => ['int', 'mysql'=>'mysqli'],
'mysqli_get_server_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_server_version' => ['int', 'mysql'=>'mysqli'],
'mysqli_get_warnings' => ['mysqli_warning', 'mysql'=>'mysqli'],
'mysqli_info' => ['?string', 'mysql'=>'mysqli'],
'mysqli_init' => ['mysqli'],
'mysqli_insert_id' => ['int|string', 'mysql'=>'mysqli'],
'mysqli_kill' => ['bool', 'mysql'=>'mysqli', 'process_id'=>'int'],
'mysqli_link_construct' => ['object'],
'mysqli_master_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_more_results' => ['bool', 'mysql'=>'mysqli'],
'mysqli_multi_query' => ['bool', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_next_result' => ['bool', 'mysql'=>'mysqli'],
'mysqli_num_fields' => ['int', 'result'=>'mysqli_result'],
'mysqli_num_rows' => ['int', 'result'=>'mysqli_result'],
'mysqli_options' => ['bool', 'mysql'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_ping' => ['bool', 'mysql'=>'mysqli'],
'mysqli_poll' => ['int|false', 'read'=>'array', 'write'=>'array', 'error'=>'array', 'seconds'=>'int', 'microseconds='=>'int'],
'mysqli_prepare' => ['mysqli_stmt|false', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_query' => ['mysqli_result|bool', 'mysql'=>'mysqli', 'query'=>'string', 'result_mode='=>'int'],
'mysqli_real_connect' => ['bool', 'mysql='=>'mysqli', 'hostname='=>'string|null', 'username='=>'string', 'password='=>'string|null', 'database='=>'string', 'port='=>'int', 'socket='=>'string', 'flags='=>'int'],
'mysqli_real_escape_string' => ['string', 'mysql'=>'mysqli', 'string'=>'string'],
'mysqli_real_query' => ['bool', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_reap_async_query' => ['mysqli_result|false', 'mysql'=>'mysqli'],
'mysqli_refresh' => ['bool', 'mysql'=>'mysqli', 'flags'=>'int'],
'mysqli_release_savepoint' => ['bool', 'mysql'=>'mysqli', 'name'=>'string'],
'mysqli_report' => ['bool', 'flags'=>'int'],
'mysqli_result::__construct' => ['void', 'mysql'=>'mysqli', 'result_mode='=>'int'],
'mysqli_result::close' => ['void'],
'mysqli_result::data_seek' => ['bool', 'offset'=>'int'],
'mysqli_result::fetch_all' => ['array', 'mode='=>'int'],
'mysqli_result::fetch_array' => ['?array', 'mode='=>'int'],
'mysqli_result::fetch_assoc' => ['array<string,string>|null'],
'mysqli_result::fetch_field' => ['object|false'],
'mysqli_result::fetch_field_direct' => ['object|false', 'index'=>'int'],
'mysqli_result::fetch_fields' => ['array|false'],
'mysqli_result::fetch_object' => ['object|stdClass|null', 'class='=>'string', 'constructor_args='=>'array'],
'mysqli_result::fetch_row' => ['?array'],
'mysqli_result::field_seek' => ['bool', 'index'=>'int'],
'mysqli_result::free' => ['void'],
'mysqli_result::free_result' => ['void'],
'mysqli_rollback' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_rpl_parse_enabled' => ['int', 'link'=>'mysqli'],
'mysqli_rpl_probe' => ['bool', 'link'=>'mysqli'],
'mysqli_rpl_query_type' => ['int', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_savepoint' => ['bool', 'mysql'=>'mysqli', 'name'=>'string'],
'mysqli_savepoint_libmysql' => ['bool'],
'mysqli_select_db' => ['bool', 'mysql'=>'mysqli', 'database'=>'string'],
'mysqli_send_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_set_charset' => ['bool', 'mysql'=>'mysqli', 'charset'=>'string'],
'mysqli_set_local_infile_default' => ['void', 'link'=>'mysqli'],
'mysqli_set_local_infile_handler' => ['bool', 'link'=>'mysqli', 'read_func'=>'callable'],
'mysqli_set_opt' => ['bool', 'mysql'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_slave_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_sqlstate' => ['string', 'mysql'=>'mysqli'],
'mysqli_ssl_set' => ['bool', 'mysql'=>'mysqli', 'key'=>'string', 'certificate'=>'string', 'ca_certificate'=>'string', 'ca_path'=>'string', 'cipher_algos'=>'string'],
'mysqli_stat' => ['string|false', 'mysql'=>'mysqli'],
'mysqli_stmt::__construct' => ['void', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_stmt::attr_get' => ['false|int', 'attribute'=>'int'],
'mysqli_stmt::attr_set' => ['bool', 'attribute'=>'int', 'value'=>'int'],
'mysqli_stmt::bind_param' => ['bool', 'types'=>'string', '&vars'=>'mixed', '&...args='=>'mixed'],
'mysqli_stmt::bind_result' => ['bool', '&w_var1'=>'', '&...w_vars='=>''],
'mysqli_stmt::close' => ['bool'],
'mysqli_stmt::data_seek' => ['void', 'offset'=>'int'],
'mysqli_stmt::execute' => ['bool'],
'mysqli_stmt::fetch' => ['bool|null'],
'mysqli_stmt::free_result' => ['void'],
'mysqli_stmt::get_result' => ['mysqli_result|false'],
'mysqli_stmt::get_warnings' => ['object'],
'mysqli_stmt::more_results' => ['bool'],
'mysqli_stmt::next_result' => ['bool'],
'mysqli_stmt::num_rows' => ['int'],
'mysqli_stmt::prepare' => ['bool', 'query'=>'string'],
'mysqli_stmt::reset' => ['bool'],
'mysqli_stmt::result_metadata' => ['mysqli_result|false'],
'mysqli_stmt::send_long_data' => ['bool', 'param_num'=>'int', 'data'=>'string'],
'mysqli_stmt::store_result' => ['bool'],
'mysqli_stmt_affected_rows' => ['int|string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_attr_get' => ['int|false', 'statement'=>'mysqli_stmt', 'attribute'=>'int'],
'mysqli_stmt_attr_set' => ['bool', 'statement'=>'mysqli_stmt', 'attribute'=>'int', 'value'=>'int'],
'mysqli_stmt_bind_param' => ['bool', 'statement'=>'mysqli_stmt', 'types'=>'string', '&vars'=>'mixed', '&...args='=>'mixed'],
'mysqli_stmt_bind_result' => ['bool', 'statement'=>'mysqli_stmt', '&w_var1'=>'', '&...w_vars='=>''],
'mysqli_stmt_close' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_data_seek' => ['void', 'statement'=>'mysqli_stmt', 'offset'=>'int'],
'mysqli_stmt_errno' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_error' => ['string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_error_list' => ['array', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_execute' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_fetch' => ['bool|null', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_field_count' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_free_result' => ['void', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_get_result' => ['mysqli_result|false', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_get_warnings' => ['object', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_init' => ['mysqli_stmt', 'mysql'=>'mysqli'],
'mysqli_stmt_insert_id' => ['mixed', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_more_results' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_next_result' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_num_rows' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_param_count' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_prepare' => ['bool', 'statement'=>'mysqli_stmt', 'query'=>'string'],
'mysqli_stmt_reset' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_result_metadata' => ['mysqli_result|false', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_send_long_data' => ['bool', 'statement'=>'mysqli_stmt', 'param_num'=>'int', 'data'=>'string'],
'mysqli_stmt_sqlstate' => ['string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_store_result' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_store_result' => ['mysqli_result|false', 'mysql'=>'mysqli', 'mode='=>'int'],
'mysqli_thread_id' => ['int', 'mysql'=>'mysqli'],
'mysqli_thread_safe' => ['bool'],
'mysqli_use_result' => ['mysqli_result|false', 'mysql'=>'mysqli'],
'mysqli_warning::__construct' => ['void'],
'mysqli_warning::next' => ['bool'],
'mysqli_warning_count' => ['int', 'mysql'=>'mysqli'],
'mysqlnd_memcache_get_config' => ['array', 'connection'=>'mixed'],
'mysqlnd_memcache_set' => ['bool', 'mysql_connection'=>'mixed', 'memcache_connection='=>'Memcached', 'pattern='=>'string', 'callback='=>'callable'],
'mysqlnd_ms_dump_servers' => ['array', 'connection'=>'mixed'],
'mysqlnd_ms_fabric_select_global' => ['array', 'connection'=>'mixed', 'table_name'=>'mixed'],
'mysqlnd_ms_fabric_select_shard' => ['array', 'connection'=>'mixed', 'table_name'=>'mixed', 'shard_key'=>'mixed'],
'mysqlnd_ms_get_last_gtid' => ['string', 'connection'=>'mixed'],
'mysqlnd_ms_get_last_used_connection' => ['array', 'connection'=>'mixed'],
'mysqlnd_ms_get_stats' => ['array'],
'mysqlnd_ms_match_wild' => ['bool', 'table_name'=>'string', 'wildcard'=>'string'],
'mysqlnd_ms_query_is_select' => ['int', 'query'=>'string'],
'mysqlnd_ms_set_qos' => ['bool', 'connection'=>'mixed', 'service_level'=>'int', 'service_level_option='=>'int', 'option_value='=>'mixed'],
'mysqlnd_ms_set_user_pick_server' => ['bool', 'function'=>'string'],
'mysqlnd_ms_xa_begin' => ['int', 'connection'=>'mixed', 'gtrid'=>'string', 'timeout='=>'int'],
'mysqlnd_ms_xa_commit' => ['int', 'connection'=>'mixed', 'gtrid'=>'string'],
'mysqlnd_ms_xa_gc' => ['int', 'connection'=>'mixed', 'gtrid='=>'string', 'ignore_max_retries='=>'bool'],
'mysqlnd_ms_xa_rollback' => ['int', 'connection'=>'mixed', 'gtrid'=>'string'],
'mysqlnd_qc_change_handler' => ['bool', 'handler'=>''],
'mysqlnd_qc_clear_cache' => ['bool'],
'mysqlnd_qc_get_available_handlers' => ['array'],
'mysqlnd_qc_get_cache_info' => ['array'],
'mysqlnd_qc_get_core_stats' => ['array'],
'mysqlnd_qc_get_handler' => ['array'],
'mysqlnd_qc_get_normalized_query_trace_log' => ['array'],
'mysqlnd_qc_get_query_trace_log' => ['array'],
'mysqlnd_qc_set_cache_condition' => ['bool', 'condition_type'=>'int', 'condition'=>'mixed', 'condition_option'=>'mixed'],
'mysqlnd_qc_set_is_select' => ['mixed', 'callback'=>'string'],
'mysqlnd_qc_set_storage_handler' => ['bool', 'handler'=>'string'],
'mysqlnd_qc_set_user_handlers' => ['bool', 'get_hash'=>'string', 'find_query_in_cache'=>'string', 'return_to_cache'=>'string', 'add_query_to_cache_if_not_exists'=>'string', 'query_is_select'=>'string', 'update_query_run_time_stats'=>'string', 'get_stats'=>'string', 'clear_cache'=>'string'],
'mysqlnd_uh_convert_to_mysqlnd' => ['resource', '&rw_mysql_connection'=>'mysqli'],
'mysqlnd_uh_set_connection_proxy' => ['bool', '&rw_connection_proxy'=>'MysqlndUhConnection', '&rw_mysqli_connection='=>'mysqli'],
'mysqlnd_uh_set_statement_proxy' => ['bool', '&rw_statement_proxy'=>'MysqlndUhStatement'],
'MysqlndUhConnection::__construct' => ['void'],
'MysqlndUhConnection::changeUser' => ['bool', 'connection'=>'mysqlnd_connection', 'user'=>'string', 'password'=>'string', 'database'=>'string', 'silent'=>'bool', 'passwd_len'=>'int'],
'MysqlndUhConnection::charsetName' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::close' => ['bool', 'connection'=>'mysqlnd_connection', 'close_type'=>'int'],
'MysqlndUhConnection::connect' => ['bool', 'connection'=>'mysqlnd_connection', 'host'=>'string', 'use'=>'string', 'password'=>'string', 'database'=>'string', 'port'=>'int', 'socket'=>'string', 'mysql_flags'=>'int'],
'MysqlndUhConnection::endPSession' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::escapeString' => ['string', 'connection'=>'mysqlnd_connection', 'escape_string'=>'string'],
'MysqlndUhConnection::getAffectedRows' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getErrorNumber' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getErrorString' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getFieldCount' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getHostInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getLastInsertId' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getLastMessage' => ['void', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getProtocolInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerStatistics' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerVersion' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getSqlstate' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getStatistics' => ['array', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getThreadId' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getWarningCount' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::init' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::killConnection' => ['bool', 'connection'=>'mysqlnd_connection', 'pid'=>'int'],
'MysqlndUhConnection::listFields' => ['array', 'connection'=>'mysqlnd_connection', 'table'=>'string', 'achtung_wild'=>'string'],
'MysqlndUhConnection::listMethod' => ['void', 'connection'=>'mysqlnd_connection', 'query'=>'string', 'achtung_wild'=>'string', 'par1'=>'string'],
'MysqlndUhConnection::moreResults' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::nextResult' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::ping' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::query' => ['bool', 'connection'=>'mysqlnd_connection', 'query'=>'string'],
'MysqlndUhConnection::queryReadResultsetHeader' => ['bool', 'connection'=>'mysqlnd_connection', 'mysqlnd_stmt'=>'mysqlnd_statement'],
'MysqlndUhConnection::reapQuery' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::refreshServer' => ['bool', 'connection'=>'mysqlnd_connection', 'options'=>'int'],
'MysqlndUhConnection::restartPSession' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::selectDb' => ['bool', 'connection'=>'mysqlnd_connection', 'database'=>'string'],
'MysqlndUhConnection::sendClose' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::sendQuery' => ['bool', 'connection'=>'mysqlnd_connection', 'query'=>'string'],
'MysqlndUhConnection::serverDumpDebugInformation' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::setAutocommit' => ['bool', 'connection'=>'mysqlnd_connection', 'mode'=>'int'],
'MysqlndUhConnection::setCharset' => ['bool', 'connection'=>'mysqlnd_connection', 'charset'=>'string'],
'MysqlndUhConnection::setClientOption' => ['bool', 'connection'=>'mysqlnd_connection', 'option'=>'int', 'value'=>'int'],
'MysqlndUhConnection::setServerOption' => ['void', 'connection'=>'mysqlnd_connection', 'option'=>'int'],
'MysqlndUhConnection::shutdownServer' => ['void', 'MYSQLND_UH_RES_MYSQLND_NAME'=>'string', 'level'=>'string'],
'MysqlndUhConnection::simpleCommand' => ['bool', 'connection'=>'mysqlnd_connection', 'command'=>'int', 'arg'=>'string', 'ok_packet'=>'int', 'silent'=>'bool', 'ignore_upsert_status'=>'bool'],
'MysqlndUhConnection::simpleCommandHandleResponse' => ['bool', 'connection'=>'mysqlnd_connection', 'ok_packet'=>'int', 'silent'=>'bool', 'command'=>'int', 'ignore_upsert_status'=>'bool'],
'MysqlndUhConnection::sslSet' => ['bool', 'connection'=>'mysqlnd_connection', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'MysqlndUhConnection::stmtInit' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::storeResult' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::txCommit' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::txRollback' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::useResult' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhPreparedStatement::__construct' => ['void'],
'MysqlndUhPreparedStatement::execute' => ['bool', 'statement'=>'mysqlnd_prepared_statement'],
'MysqlndUhPreparedStatement::prepare' => ['bool', 'statement'=>'mysqlnd_prepared_statement', 'query'=>'string'],
'natcasesort' => ['bool', '&rw_array'=>'array'],
'natsort' => ['bool', '&rw_array'=>'array'],
'ncurses_addch' => ['int', 'ch'=>'int'],
'ncurses_addchnstr' => ['int', 's'=>'string', 'n'=>'int'],
'ncurses_addchstr' => ['int', 's'=>'string'],
'ncurses_addnstr' => ['int', 's'=>'string', 'n'=>'int'],
'ncurses_addstr' => ['int', 'text'=>'string'],
'ncurses_assume_default_colors' => ['int', 'fg'=>'int', 'bg'=>'int'],
'ncurses_attroff' => ['int', 'attributes'=>'int'],
'ncurses_attron' => ['int', 'attributes'=>'int'],
'ncurses_attrset' => ['int', 'attributes'=>'int'],
'ncurses_baudrate' => ['int'],
'ncurses_beep' => ['int'],
'ncurses_bkgd' => ['int', 'attrchar'=>'int'],
'ncurses_bkgdset' => ['void', 'attrchar'=>'int'],
'ncurses_border' => ['int', 'left'=>'int', 'right'=>'int', 'top'=>'int', 'bottom'=>'int', 'tl_corner'=>'int', 'tr_corner'=>'int', 'bl_corner'=>'int', 'br_corner'=>'int'],
'ncurses_bottom_panel' => ['int', 'panel'=>'resource'],
'ncurses_can_change_color' => ['bool'],
'ncurses_cbreak' => ['bool'],
'ncurses_clear' => ['bool'],
'ncurses_clrtobot' => ['bool'],
'ncurses_clrtoeol' => ['bool'],
'ncurses_color_content' => ['int', 'color'=>'int', 'r'=>'int', 'g'=>'int', 'b'=>'int'],
'ncurses_color_set' => ['int', 'pair'=>'int'],
'ncurses_curs_set' => ['int', 'visibility'=>'int'],
'ncurses_def_prog_mode' => ['bool'],
'ncurses_def_shell_mode' => ['bool'],
'ncurses_define_key' => ['int', 'definition'=>'string', 'keycode'=>'int'],
'ncurses_del_panel' => ['bool', 'panel'=>'resource'],
'ncurses_delay_output' => ['int', 'milliseconds'=>'int'],
'ncurses_delch' => ['bool'],
'ncurses_deleteln' => ['bool'],
'ncurses_delwin' => ['bool', 'window'=>'resource'],
'ncurses_doupdate' => ['bool'],
'ncurses_echo' => ['bool'],
'ncurses_echochar' => ['int', 'character'=>'int'],
'ncurses_end' => ['int'],
'ncurses_erase' => ['bool'],
'ncurses_erasechar' => ['string'],
'ncurses_filter' => ['void'],
'ncurses_flash' => ['bool'],
'ncurses_flushinp' => ['bool'],
'ncurses_getch' => ['int'],
'ncurses_getmaxyx' => ['void', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_getmouse' => ['bool', 'mevent'=>'array'],
'ncurses_getyx' => ['void', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_halfdelay' => ['int', 'tenth'=>'int'],
'ncurses_has_colors' => ['bool'],
'ncurses_has_ic' => ['bool'],
'ncurses_has_il' => ['bool'],
'ncurses_has_key' => ['int', 'keycode'=>'int'],
'ncurses_hide_panel' => ['int', 'panel'=>'resource'],
'ncurses_hline' => ['int', 'charattr'=>'int', 'n'=>'int'],
'ncurses_inch' => ['string'],
'ncurses_init' => ['void'],
'ncurses_init_color' => ['int', 'color'=>'int', 'r'=>'int', 'g'=>'int', 'b'=>'int'],
'ncurses_init_pair' => ['int', 'pair'=>'int', 'fg'=>'int', 'bg'=>'int'],
'ncurses_insch' => ['int', 'character'=>'int'],
'ncurses_insdelln' => ['int', 'count'=>'int'],
'ncurses_insertln' => ['int'],
'ncurses_insstr' => ['int', 'text'=>'string'],
'ncurses_instr' => ['int', 'buffer'=>'string'],
'ncurses_isendwin' => ['bool'],
'ncurses_keyok' => ['int', 'keycode'=>'int', 'enable'=>'bool'],
'ncurses_keypad' => ['int', 'window'=>'resource', 'bf'=>'bool'],
'ncurses_killchar' => ['string'],
'ncurses_longname' => ['string'],
'ncurses_meta' => ['int', 'window'=>'resource', '_8bit'=>'bool'],
'ncurses_mouse_trafo' => ['bool', 'y'=>'int', 'x'=>'int', 'toscreen'=>'bool'],
'ncurses_mouseinterval' => ['int', 'milliseconds'=>'int'],
'ncurses_mousemask' => ['int', 'newmask'=>'int', 'oldmask'=>'int'],
'ncurses_move' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_move_panel' => ['int', 'panel'=>'resource', 'startx'=>'int', 'starty'=>'int'],
'ncurses_mvaddch' => ['int', 'y'=>'int', 'x'=>'int', 'c'=>'int'],
'ncurses_mvaddchnstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string', 'n'=>'int'],
'ncurses_mvaddchstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string'],
'ncurses_mvaddnstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string', 'n'=>'int'],
'ncurses_mvaddstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string'],
'ncurses_mvcur' => ['int', 'old_y'=>'int', 'old_x'=>'int', 'new_y'=>'int', 'new_x'=>'int'],
'ncurses_mvdelch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvgetch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvhline' => ['int', 'y'=>'int', 'x'=>'int', 'attrchar'=>'int', 'n'=>'int'],
'ncurses_mvinch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvvline' => ['int', 'y'=>'int', 'x'=>'int', 'attrchar'=>'int', 'n'=>'int'],
'ncurses_mvwaddstr' => ['int', 'window'=>'resource', 'y'=>'int', 'x'=>'int', 'text'=>'string'],
'ncurses_napms' => ['int', 'milliseconds'=>'int'],
'ncurses_new_panel' => ['resource', 'window'=>'resource'],
'ncurses_newpad' => ['resource', 'rows'=>'int', 'cols'=>'int'],
'ncurses_newwin' => ['resource', 'rows'=>'int', 'cols'=>'int', 'y'=>'int', 'x'=>'int'],
'ncurses_nl' => ['bool'],
'ncurses_nocbreak' => ['bool'],
'ncurses_noecho' => ['bool'],
'ncurses_nonl' => ['bool'],
'ncurses_noqiflush' => ['void'],
'ncurses_noraw' => ['bool'],
'ncurses_pair_content' => ['int', 'pair'=>'int', 'f'=>'int', 'b'=>'int'],
'ncurses_panel_above' => ['resource', 'panel'=>'resource'],
'ncurses_panel_below' => ['resource', 'panel'=>'resource'],
'ncurses_panel_window' => ['resource', 'panel'=>'resource'],
'ncurses_pnoutrefresh' => ['int', 'pad'=>'resource', 'pminrow'=>'int', 'pmincol'=>'int', 'sminrow'=>'int', 'smincol'=>'int', 'smaxrow'=>'int', 'smaxcol'=>'int'],
'ncurses_prefresh' => ['int', 'pad'=>'resource', 'pminrow'=>'int', 'pmincol'=>'int', 'sminrow'=>'int', 'smincol'=>'int', 'smaxrow'=>'int', 'smaxcol'=>'int'],
'ncurses_putp' => ['int', 'text'=>'string'],
'ncurses_qiflush' => ['void'],
'ncurses_raw' => ['bool'],
'ncurses_refresh' => ['int', 'ch'=>'int'],
'ncurses_replace_panel' => ['int', 'panel'=>'resource', 'window'=>'resource'],
'ncurses_reset_prog_mode' => ['int'],
'ncurses_reset_shell_mode' => ['int'],
'ncurses_resetty' => ['bool'],
'ncurses_savetty' => ['bool'],
'ncurses_scr_dump' => ['int', 'filename'=>'string'],
'ncurses_scr_init' => ['int', 'filename'=>'string'],
'ncurses_scr_restore' => ['int', 'filename'=>'string'],
'ncurses_scr_set' => ['int', 'filename'=>'string'],
'ncurses_scrl' => ['int', 'count'=>'int'],
'ncurses_show_panel' => ['int', 'panel'=>'resource'],
'ncurses_slk_attr' => ['int'],
'ncurses_slk_attroff' => ['int', 'intarg'=>'int'],
'ncurses_slk_attron' => ['int', 'intarg'=>'int'],
'ncurses_slk_attrset' => ['int', 'intarg'=>'int'],
'ncurses_slk_clear' => ['bool'],
'ncurses_slk_color' => ['int', 'intarg'=>'int'],
'ncurses_slk_init' => ['bool', 'format'=>'int'],
'ncurses_slk_noutrefresh' => ['bool'],
'ncurses_slk_refresh' => ['int'],
'ncurses_slk_restore' => ['int'],
'ncurses_slk_set' => ['bool', 'labelnr'=>'int', 'label'=>'string', 'format'=>'int'],
'ncurses_slk_touch' => ['int'],
'ncurses_standend' => ['int'],
'ncurses_standout' => ['int'],
'ncurses_start_color' => ['int'],
'ncurses_termattrs' => ['bool'],
'ncurses_termname' => ['string'],
'ncurses_timeout' => ['void', 'millisec'=>'int'],
'ncurses_top_panel' => ['int', 'panel'=>'resource'],
'ncurses_typeahead' => ['int', 'fd'=>'int'],
'ncurses_ungetch' => ['int', 'keycode'=>'int'],
'ncurses_ungetmouse' => ['bool', 'mevent'=>'array'],
'ncurses_update_panels' => ['void'],
'ncurses_use_default_colors' => ['bool'],
'ncurses_use_env' => ['void', 'flag'=>'bool'],
'ncurses_use_extended_names' => ['int', 'flag'=>'bool'],
'ncurses_vidattr' => ['int', 'intarg'=>'int'],
'ncurses_vline' => ['int', 'charattr'=>'int', 'n'=>'int'],
'ncurses_waddch' => ['int', 'window'=>'resource', 'ch'=>'int'],
'ncurses_waddstr' => ['int', 'window'=>'resource', 'string'=>'string', 'n='=>'int'],
'ncurses_wattroff' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wattron' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wattrset' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wborder' => ['int', 'window'=>'resource', 'left'=>'int', 'right'=>'int', 'top'=>'int', 'bottom'=>'int', 'tl_corner'=>'int', 'tr_corner'=>'int', 'bl_corner'=>'int', 'br_corner'=>'int'],
'ncurses_wclear' => ['int', 'window'=>'resource'],
'ncurses_wcolor_set' => ['int', 'window'=>'resource', 'color_pair'=>'int'],
'ncurses_werase' => ['int', 'window'=>'resource'],
'ncurses_wgetch' => ['int', 'window'=>'resource'],
'ncurses_whline' => ['int', 'window'=>'resource', 'charattr'=>'int', 'n'=>'int'],
'ncurses_wmouse_trafo' => ['bool', 'window'=>'resource', 'y'=>'int', 'x'=>'int', 'toscreen'=>'bool'],
'ncurses_wmove' => ['int', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_wnoutrefresh' => ['int', 'window'=>'resource'],
'ncurses_wrefresh' => ['int', 'window'=>'resource'],
'ncurses_wstandend' => ['int', 'window'=>'resource'],
'ncurses_wstandout' => ['int', 'window'=>'resource'],
'ncurses_wvline' => ['int', 'window'=>'resource', 'charattr'=>'int', 'n'=>'int'],
'net_get_interfaces' => ['array<string,array<string,mixed>>|false'],
'newrelic_add_custom_parameter' => ['bool', 'key'=>'string', 'value'=>'bool|float|int|string'],
'newrelic_add_custom_tracer' => ['bool', 'function_name'=>'string'],
'newrelic_background_job' => ['void', 'flag='=>'bool'],
'newrelic_capture_params' => ['void', 'enable='=>'bool'],
'newrelic_custom_metric' => ['bool', 'metric_name'=>'string', 'value'=>'float'],
'newrelic_disable_autorum' => ['true'],
'newrelic_end_of_transaction' => ['void'],
'newrelic_end_transaction' => ['bool', 'ignore='=>'bool'],
'newrelic_get_browser_timing_footer' => ['string', 'include_tags='=>'bool'],
'newrelic_get_browser_timing_header' => ['string', 'include_tags='=>'bool'],
'newrelic_ignore_apdex' => ['void'],
'newrelic_ignore_transaction' => ['void'],
'newrelic_name_transaction' => ['bool', 'name'=>'string'],
'newrelic_notice_error' => ['void', 'message'=>'string', 'exception='=>'Exception|Throwable'],
'newrelic_notice_error\'1' => ['void', 'unused_1'=>'string', 'message'=>'string', 'unused_2'=>'string', 'unused_3'=>'int', 'unused_4='=>''],
'newrelic_record_custom_event' => ['void', 'name'=>'string', 'attributes'=>'array'],
'newrelic_record_datastore_segment' => ['mixed', 'func'=>'callable', 'parameters'=>'array'],
'newrelic_set_appname' => ['bool', 'name'=>'string', 'license='=>'string', 'xmit='=>'bool'],
'newrelic_set_user_attributes' => ['bool', 'user'=>'string', 'account'=>'string', 'product'=>'string'],
'newrelic_start_transaction' => ['bool', 'appname'=>'string', 'license='=>'string'],
'newt_bell' => ['void'],
'newt_button' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_button_bar' => ['resource', 'buttons'=>'array'],
'newt_centered_window' => ['int', 'width'=>'int', 'height'=>'int', 'title='=>'string'],
'newt_checkbox' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'def_value'=>'string', 'seq='=>'string'],
'newt_checkbox_get_value' => ['string', 'checkbox'=>'resource'],
'newt_checkbox_set_flags' => ['void', 'checkbox'=>'resource', 'flags'=>'int', 'sense'=>'int'],
'newt_checkbox_set_value' => ['void', 'checkbox'=>'resource', 'value'=>'string'],
'newt_checkbox_tree' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_checkbox_tree_add_item' => ['void', 'checkboxtree'=>'resource', 'text'=>'string', 'data'=>'mixed', 'flags'=>'int', 'index'=>'int', '...args='=>'int'],
'newt_checkbox_tree_find_item' => ['array', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_get_current' => ['mixed', 'checkboxtree'=>'resource'],
'newt_checkbox_tree_get_entry_value' => ['string', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_get_multi_selection' => ['array', 'checkboxtree'=>'resource', 'seqnum'=>'string'],
'newt_checkbox_tree_get_selection' => ['array', 'checkboxtree'=>'resource'],
'newt_checkbox_tree_multi' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'seq'=>'string', 'flags='=>'int'],
'newt_checkbox_tree_set_current' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_set_entry' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed', 'text'=>'string'],
'newt_checkbox_tree_set_entry_value' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed', 'value'=>'string'],
'newt_checkbox_tree_set_width' => ['void', 'checkbox_tree'=>'resource', 'width'=>'int'],
'newt_clear_key_buffer' => ['void'],
'newt_cls' => ['void'],
'newt_compact_button' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_component_add_callback' => ['void', 'component'=>'resource', 'func_name'=>'mixed', 'data'=>'mixed'],
'newt_component_takes_focus' => ['void', 'component'=>'resource', 'takes_focus'=>'bool'],
'newt_create_grid' => ['resource', 'cols'=>'int', 'rows'=>'int'],
'newt_cursor_off' => ['void'],
'newt_cursor_on' => ['void'],
'newt_delay' => ['void', 'microseconds'=>'int'],
'newt_draw_form' => ['void', 'form'=>'resource'],
'newt_draw_root_text' => ['void', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_entry' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'init_value='=>'string', 'flags='=>'int'],
'newt_entry_get_value' => ['string', 'entry'=>'resource'],
'newt_entry_set' => ['void', 'entry'=>'resource', 'value'=>'string', 'cursor_at_end='=>'bool'],
'newt_entry_set_filter' => ['void', 'entry'=>'resource', 'filter'=>'callable', 'data'=>'mixed'],
'newt_entry_set_flags' => ['void', 'entry'=>'resource', 'flags'=>'int', 'sense'=>'int'],
'newt_finished' => ['int'],
'newt_form' => ['resource', 'vert_bar='=>'resource', 'help='=>'string', 'flags='=>'int'],
'newt_form_add_component' => ['void', 'form'=>'resource', 'component'=>'resource'],
'newt_form_add_components' => ['void', 'form'=>'resource', 'components'=>'array'],
'newt_form_add_hot_key' => ['void', 'form'=>'resource', 'key'=>'int'],
'newt_form_destroy' => ['void', 'form'=>'resource'],
'newt_form_get_current' => ['resource', 'form'=>'resource'],
'newt_form_run' => ['void', 'form'=>'resource', 'exit_struct'=>'array'],
'newt_form_set_background' => ['void', 'from'=>'resource', 'background'=>'int'],
'newt_form_set_height' => ['void', 'form'=>'resource', 'height'=>'int'],
'newt_form_set_size' => ['void', 'form'=>'resource'],
'newt_form_set_timer' => ['void', 'form'=>'resource', 'milliseconds'=>'int'],
'newt_form_set_width' => ['void', 'form'=>'resource', 'width'=>'int'],
'newt_form_watch_fd' => ['void', 'form'=>'resource', 'stream'=>'resource', 'flags='=>'int'],
'newt_get_screen_size' => ['void', 'cols'=>'int', 'rows'=>'int'],
'newt_grid_add_components_to_form' => ['void', 'grid'=>'resource', 'form'=>'resource', 'recurse'=>'bool'],
'newt_grid_basic_window' => ['resource', 'text'=>'resource', 'middle'=>'resource', 'buttons'=>'resource'],
'newt_grid_free' => ['void', 'grid'=>'resource', 'recurse'=>'bool'],
'newt_grid_get_size' => ['void', 'grid'=>'resource', 'width'=>'int', 'height'=>'int'],
'newt_grid_h_close_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_h_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_place' => ['void', 'grid'=>'resource', 'left'=>'int', 'top'=>'int'],
'newt_grid_set_field' => ['void', 'grid'=>'resource', 'col'=>'int', 'row'=>'int', 'type'=>'int', 'value'=>'resource', 'pad_left'=>'int', 'pad_top'=>'int', 'pad_right'=>'int', 'pad_bottom'=>'int', 'anchor'=>'int', 'flags='=>'int'],
'newt_grid_simple_window' => ['resource', 'text'=>'resource', 'middle'=>'resource', 'buttons'=>'resource'],
'newt_grid_v_close_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_v_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_wrapped_window' => ['void', 'grid'=>'resource', 'title'=>'string'],
'newt_grid_wrapped_window_at' => ['void', 'grid'=>'resource', 'title'=>'string', 'left'=>'int', 'top'=>'int'],
'newt_init' => ['int'],
'newt_label' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_label_set_text' => ['void', 'label'=>'resource', 'text'=>'string'],
'newt_listbox' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_listbox_append_entry' => ['void', 'listbox'=>'resource', 'text'=>'string', 'data'=>'mixed'],
'newt_listbox_clear' => ['void', 'listobx'=>'resource'],
'newt_listbox_clear_selection' => ['void', 'listbox'=>'resource'],
'newt_listbox_delete_entry' => ['void', 'listbox'=>'resource', 'key'=>'mixed'],
'newt_listbox_get_current' => ['string', 'listbox'=>'resource'],
'newt_listbox_get_selection' => ['array', 'listbox'=>'resource'],
'newt_listbox_insert_entry' => ['void', 'listbox'=>'resource', 'text'=>'string', 'data'=>'mixed', 'key'=>'mixed'],
'newt_listbox_item_count' => ['int', 'listbox'=>'resource'],
'newt_listbox_select_item' => ['void', 'listbox'=>'resource', 'key'=>'mixed', 'sense'=>'int'],
'newt_listbox_set_current' => ['void', 'listbox'=>'resource', 'num'=>'int'],
'newt_listbox_set_current_by_key' => ['void', 'listbox'=>'resource', 'key'=>'mixed'],
'newt_listbox_set_data' => ['void', 'listbox'=>'resource', 'num'=>'int', 'data'=>'mixed'],
'newt_listbox_set_entry' => ['void', 'listbox'=>'resource', 'num'=>'int', 'text'=>'string'],
'newt_listbox_set_width' => ['void', 'listbox'=>'resource', 'width'=>'int'],
'newt_listitem' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'is_default'=>'bool', 'prev_item'=>'resource', 'data'=>'mixed', 'flags='=>'int'],
'newt_listitem_get_data' => ['mixed', 'item'=>'resource'],
'newt_listitem_set' => ['void', 'item'=>'resource', 'text'=>'string'],
'newt_open_window' => ['int', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'height'=>'int', 'title='=>'string'],
'newt_pop_help_line' => ['void'],
'newt_pop_window' => ['void'],
'newt_push_help_line' => ['void', 'text='=>'string'],
'newt_radio_get_current' => ['resource', 'set_member'=>'resource'],
'newt_radiobutton' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'is_default'=>'bool', 'prev_button='=>'resource'],
'newt_redraw_help_line' => ['void'],
'newt_reflow_text' => ['string', 'text'=>'string', 'width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'actual_width'=>'int', 'actual_height'=>'int'],
'newt_refresh' => ['void'],
'newt_resize_screen' => ['void', 'redraw='=>'bool'],
'newt_resume' => ['void'],
'newt_run_form' => ['resource', 'form'=>'resource'],
'newt_scale' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'full_value'=>'int'],
'newt_scale_set' => ['void', 'scale'=>'resource', 'amount'=>'int'],
'newt_scrollbar_set' => ['void', 'scrollbar'=>'resource', 'where'=>'int', 'total'=>'int'],
'newt_set_help_callback' => ['void', 'function'=>'mixed'],
'newt_set_suspend_callback' => ['void', 'function'=>'callable', 'data'=>'mixed'],
'newt_suspend' => ['void'],
'newt_textbox' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_textbox_get_num_lines' => ['int', 'textbox'=>'resource'],
'newt_textbox_reflowed' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'char', 'width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'flags='=>'int'],
'newt_textbox_set_height' => ['void', 'textbox'=>'resource', 'height'=>'int'],
'newt_textbox_set_text' => ['void', 'textbox'=>'resource', 'text'=>'string'],
'newt_vertical_scrollbar' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'normal_colorset='=>'int', 'thumb_colorset='=>'int'],
'newt_wait_for_key' => ['void'],
'newt_win_choice' => ['int', 'title'=>'string', 'button1_text'=>'string', 'button2_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'newt_win_entries' => ['int', 'title'=>'string', 'text'=>'string', 'suggested_width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'data_width'=>'int', 'items'=>'array', 'button1'=>'string', '...args='=>'string'],
'newt_win_menu' => ['int', 'title'=>'string', 'text'=>'string', 'suggestedwidth'=>'int', 'flexdown'=>'int', 'flexup'=>'int', 'maxlistheight'=>'int', 'items'=>'array', 'listitem'=>'int', 'button1='=>'string', '...args='=>'string'],
'newt_win_message' => ['void', 'title'=>'string', 'button_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'newt_win_messagev' => ['void', 'title'=>'string', 'button_text'=>'string', 'format'=>'string', 'args'=>'array'],
'newt_win_ternary' => ['int', 'title'=>'string', 'button1_text'=>'string', 'button2_text'=>'string', 'button3_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'next' => ['mixed', '&r_array'=>'array|object'],
'ngettext' => ['string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int'],
'nl2br' => ['string', 'string'=>'string', 'use_xhtml='=>'bool'],
'nl_langinfo' => ['string|false', 'item'=>'int'],
'NoRewindIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'NoRewindIterator::current' => ['mixed'],
'NoRewindIterator::getInnerIterator' => ['Iterator'],
'NoRewindIterator::key' => ['mixed'],
'NoRewindIterator::next' => ['void'],
'NoRewindIterator::rewind' => ['void'],
'NoRewindIterator::valid' => ['bool'],
'Normalizer::getRawDecomposition' => ['string|null', 'input'=>'string'],
'Normalizer::isNormalized' => ['bool', 'input'=>'string', 'form='=>'int'],
'Normalizer::normalize' => ['string', 'input'=>'string', 'form='=>'int'],
'normalizer_get_raw_decomposition' => ['string|null', 'string'=>'string'],
'normalizer_is_normalized' => ['bool', 'string'=>'string', 'form='=>'int'],
'normalizer_normalize' => ['string', 'string'=>'string', 'form='=>'int'],
'notes_body' => ['array', 'server'=>'string', 'mailbox'=>'string', 'msg_number'=>'int'],
'notes_copy_db' => ['bool', 'from_database_name'=>'string', 'to_database_name'=>'string'],
'notes_create_db' => ['bool', 'database_name'=>'string'],
'notes_create_note' => ['bool', 'database_name'=>'string', 'form_name'=>'string'],
'notes_drop_db' => ['bool', 'database_name'=>'string'],
'notes_find_note' => ['int', 'database_name'=>'string', 'name'=>'string', 'type='=>'string'],
'notes_header_info' => ['object', 'server'=>'string', 'mailbox'=>'string', 'msg_number'=>'int'],
'notes_list_msgs' => ['bool', 'db'=>'string'],
'notes_mark_read' => ['bool', 'database_name'=>'string', 'user_name'=>'string', 'note_id'=>'string'],
'notes_mark_unread' => ['bool', 'database_name'=>'string', 'user_name'=>'string', 'note_id'=>'string'],
'notes_nav_create' => ['bool', 'database_name'=>'string', 'name'=>'string'],
'notes_search' => ['array', 'database_name'=>'string', 'keywords'=>'string'],
'notes_unread' => ['array', 'database_name'=>'string', 'user_name'=>'string'],
'notes_version' => ['float', 'database_name'=>'string'],
'nsapi_request_headers' => ['array'],
'nsapi_response_headers' => ['array'],
'nsapi_virtual' => ['bool', 'uri'=>'string'],
'nthmac' => ['string', 'clent'=>'string', 'data'=>'string'],
'number_format' => ['string', 'num'=>'float|int', 'decimals='=>'int'],
'number_format\'1' => ['string', 'num'=>'float|int', 'decimals'=>'int', 'decimal_separator'=>'string', 'thousands_separator'=>'string'],
'NumberFormatter::__construct' => ['void', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'NumberFormatter::create' => ['NumberFormatter|false', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'NumberFormatter::format' => ['string|false', 'num'=>'', 'type='=>'int'],
'NumberFormatter::formatCurrency' => ['string', 'num'=>'float', 'currency'=>'string'],
'NumberFormatter::getAttribute' => ['int|false', 'attr'=>'int'],
'NumberFormatter::getErrorCode' => ['int'],
'NumberFormatter::getErrorMessage' => ['string'],
'NumberFormatter::getLocale' => ['string', 'type='=>'int'],
'NumberFormatter::getPattern' => ['string|false'],
'NumberFormatter::getSymbol' => ['string|false', 'attr'=>'int'],
'NumberFormatter::getTextAttribute' => ['string|false', 'attr'=>'int'],
'NumberFormatter::parse' => ['float|false', 'string'=>'string', 'type='=>'int', '&rw_position='=>'int'],
'NumberFormatter::parseCurrency' => ['float|false', 'string'=>'string', '&w_currency'=>'string', '&rw_position='=>'int'],
'NumberFormatter::setAttribute' => ['bool', 'attr'=>'int', 'value'=>''],
'NumberFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'NumberFormatter::setSymbol' => ['bool', 'attr'=>'int', 'symbol'=>'string'],
'NumberFormatter::setTextAttribute' => ['bool', 'attr'=>'int', 'value'=>'string'],
'numfmt_create' => ['NumberFormatter|false', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'numfmt_format' => ['string|false', 'formatter'=>'NumberFormatter', 'num'=>'int|float', 'type='=>'int'],
'numfmt_format_currency' => ['string|false', 'formatter'=>'NumberFormatter', 'amount'=>'float', 'currency'=>'string'],
'numfmt_get_attribute' => ['int|false', 'formatter'=>'NumberFormatter', 'attribute'=>'int'],
'numfmt_get_error_code' => ['int', 'formatter'=>'NumberFormatter'],
'numfmt_get_error_message' => ['string', 'formatter'=>'NumberFormatter'],
'numfmt_get_locale' => ['string', 'formatter'=>'NumberFormatter', 'type='=>'int'],
'numfmt_get_pattern' => ['string|false', 'formatter'=>'NumberFormatter'],
'numfmt_get_symbol' => ['string|false', 'formatter'=>'NumberFormatter', 'symbol'=>'int'],
'numfmt_get_text_attribute' => ['string|false', 'formatter'=>'NumberFormatter', 'attribute'=>'int'],
'numfmt_parse' => ['float|int|false', 'formatter'=>'NumberFormatter', 'string'=>'string', 'type='=>'int', '&rw_offset='=>'int'],
'numfmt_parse_currency' => ['float|false', 'formatter'=>'NumberFormatter', 'string'=>'string', '&w_currency'=>'string', '&rw_offset='=>'int'],
'numfmt_set_attribute' => ['bool', 'formatter'=>'NumberFormatter', 'attribute'=>'int', 'value'=>'int'],
'numfmt_set_pattern' => ['bool', 'formatter'=>'NumberFormatter', 'pattern'=>'string'],
'numfmt_set_symbol' => ['bool', 'formatter'=>'NumberFormatter', 'symbol'=>'int', 'value'=>'string'],
'numfmt_set_text_attribute' => ['bool', 'formatter'=>'NumberFormatter', 'attribute'=>'int', 'value'=>'string'],
'OAuth::__construct' => ['void', 'consumer_key'=>'string', 'consumer_secret'=>'string', 'signature_method='=>'string', 'auth_type='=>'int'],
'OAuth::__destruct' => ['void'],
'OAuth::disableDebug' => ['bool'],
'OAuth::disableRedirects' => ['bool'],
'OAuth::disableSSLChecks' => ['bool'],
'OAuth::enableDebug' => ['bool'],
'OAuth::enableRedirects' => ['bool'],
'OAuth::enableSSLChecks' => ['bool'],
'OAuth::fetch' => ['mixed', 'protected_resource_url'=>'string', 'extra_parameters='=>'array', 'http_method='=>'string', 'http_headers='=>'array'],
'OAuth::generateSignature' => ['string', 'http_method'=>'string', 'url'=>'string', 'extra_parameters='=>'mixed'],
'OAuth::getAccessToken' => ['array|false', 'access_token_url'=>'string', 'auth_session_handle='=>'string', 'verifier_token='=>'string', 'http_method='=>'string'],
'OAuth::getCAPath' => ['array'],
'OAuth::getLastResponse' => ['string'],
'OAuth::getLastResponseHeaders' => ['string|false'],
'OAuth::getLastResponseInfo' => ['array'],
'OAuth::getRequestHeader' => ['string|false', 'http_method'=>'string', 'url'=>'string', 'extra_parameters='=>'mixed'],
'OAuth::getRequestToken' => ['array|false', 'request_token_url'=>'string', 'callback_url='=>'string', 'http_method='=>'string'],
'OAuth::setAuthType' => ['bool', 'auth_type'=>'int'],
'OAuth::setCAPath' => ['mixed', 'ca_path='=>'string', 'ca_info='=>'string'],
'OAuth::setNonce' => ['mixed', 'nonce'=>'string'],
'OAuth::setRequestEngine' => ['void', 'reqengine'=>'int'],
'OAuth::setRSACertificate' => ['mixed', 'cert'=>'string'],
'OAuth::setSSLChecks' => ['bool', 'sslcheck'=>'int'],
'OAuth::setTimeout' => ['void', 'timeout'=>'int'],
'OAuth::setTimestamp' => ['mixed', 'timestamp'=>'string'],
'OAuth::setToken' => ['bool', 'token'=>'string', 'token_secret'=>'string'],
'OAuth::setVersion' => ['bool', 'version'=>'string'],
'oauth_get_sbs' => ['string', 'http_method'=>'string', 'uri'=>'string', 'request_parameters='=>'array'],
'oauth_urlencode' => ['string', 'uri'=>'string'],
'OAuthProvider::__construct' => ['void', 'params_array='=>'array'],
'OAuthProvider::addRequiredParameter' => ['bool', 'req_params'=>'string'],
'OAuthProvider::callconsumerHandler' => ['void'],
'OAuthProvider::callTimestampNonceHandler' => ['void'],
'OAuthProvider::calltokenHandler' => ['void'],
'OAuthProvider::checkOAuthRequest' => ['void', 'uri='=>'string', 'method='=>'string'],
'OAuthProvider::consumerHandler' => ['void', 'callback_function'=>'callable'],
'OAuthProvider::generateToken' => ['string', 'size'=>'int', 'strong='=>'bool'],
'OAuthProvider::is2LeggedEndpoint' => ['void', 'params_array'=>'mixed'],
'OAuthProvider::isRequestTokenEndpoint' => ['void', 'will_issue_request_token'=>'bool'],
'OAuthProvider::removeRequiredParameter' => ['bool', 'req_params'=>'string'],
'OAuthProvider::reportProblem' => ['string', 'oauthexception'=>'string', 'send_headers='=>'bool'],
'OAuthProvider::setParam' => ['bool', 'param_key'=>'string', 'param_val='=>'mixed'],
'OAuthProvider::setRequestTokenPath' => ['bool', 'path'=>'string'],
'OAuthProvider::timestampNonceHandler' => ['void', 'callback_function'=>'callable'],
'OAuthProvider::tokenHandler' => ['void', 'callback_function'=>'callable'],
'ob_clean' => ['bool'],
'ob_deflatehandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_end_clean' => ['bool'],
'ob_end_flush' => ['bool'],
'ob_etaghandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_flush' => ['bool'],
'ob_get_clean' => ['string|false'],
'ob_get_contents' => ['string|false'],
'ob_get_flush' => ['string|false'],
'ob_get_length' => ['int|false'],
'ob_get_level' => ['int'],
'ob_get_status' => ['array', 'full_status='=>'bool'],
'ob_gzhandler' => ['string|false', 'data'=>'string', 'flags'=>'int'],
'ob_iconv_handler' => ['string', 'contents'=>'string', 'status'=>'int'],
'ob_implicit_flush' => ['void', 'enable='=>'int'],
'ob_inflatehandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_list_handlers' => ['false|list<string>'],
'ob_start' => ['bool', 'callback='=>'string|array|?callable', 'chunk_size='=>'int', 'flags='=>'int'],
'ob_tidyhandler' => ['string', 'input'=>'string', 'mode='=>'int'],
'oci_bind_array_by_name' => ['bool', 'statement'=>'resource', 'param'=>'string', '&rw_var'=>'array', 'max_array_length'=>'int', 'max_item_length='=>'int', 'type='=>'int'],
'oci_bind_by_name' => ['bool', 'statement'=>'resource', 'param'=>'string', '&rw_var'=>'mixed', 'max_length='=>'int', 'type='=>'int'],
'oci_cancel' => ['bool', 'statement'=>'resource'],
'oci_client_version' => ['string'],
'oci_close' => ['bool', 'connection'=>'resource'],
'OCI_Collection::append' => ['bool', 'value'=>'mixed'],
'OCI_Collection::assign' => ['bool', 'from'=>'OCI_Collection'],
'OCI_Collection::assignElem' => ['bool', 'index'=>'int', 'value'=>'mixed'],
'OCI_Collection::free' => ['bool'],
'OCI_Collection::getElem' => ['mixed', 'index'=>'int'],
'OCI_Collection::max' => ['int|false'],
'OCI_Collection::size' => ['int|false'],
'OCI_Collection::trim' => ['bool', 'num'=>'int'],
'oci_collection_append' => ['bool', 'collection'=>'string'],
'oci_collection_assign' => ['bool', 'to'=>'object'],
'oci_collection_element_assign' => ['bool', 'collection'=>'int', 'index'=>'string'],
'oci_collection_element_get' => ['string', 'collection'=>'int'],
'oci_collection_max' => ['int'],
'oci_collection_size' => ['int'],
'oci_collection_trim' => ['bool', 'collection'=>'int'],
'oci_commit' => ['bool', 'connection'=>'resource'],
'oci_connect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_define_by_name' => ['bool', 'statement'=>'resource', 'column'=>'string', '&w_var'=>'mixed', 'type='=>'int'],
'oci_error' => ['array|false', 'connection_or_statement='=>'resource'],
'oci_execute' => ['bool', 'statement'=>'resource', 'mode='=>'int'],
'oci_fetch' => ['bool', 'statement'=>'resource'],
'oci_fetch_all' => ['int|false', 'statement'=>'resource', '&w_output'=>'array', 'offset='=>'int', 'limit='=>'int', 'flags='=>'int'],
'oci_fetch_array' => ['array|false', 'statement'=>'resource', 'mode='=>'int'],
'oci_fetch_assoc' => ['array|false', 'statement'=>'resource'],
'oci_fetch_object' => ['object|false', 'statement'=>'resource'],
'oci_fetch_row' => ['array|false', 'statement'=>'resource'],
'oci_field_is_null' => ['bool', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_name' => ['string|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_precision' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_scale' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_size' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_type' => ['mixed|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_type_raw' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_free_collection' => ['bool'],
'oci_free_cursor' => ['bool', 'statement'=>'resource'],
'oci_free_descriptor' => ['bool'],
'oci_free_statement' => ['bool', 'statement'=>'resource'],
'oci_get_implicit' => ['bool', 'stmt'=>''],
'oci_get_implicit_resultset' => ['resource|false', 'statement'=>'resource'],
'oci_internal_debug' => ['void', 'onoff'=>'bool'],
'OCI_Lob::append' => ['bool', 'lob_from'=>'OCI_Lob'],
'OCI_Lob::close' => ['bool'],
'OCI_Lob::eof' => ['bool'],
'OCI_Lob::erase' => ['int|false', 'offset='=>'int', 'length='=>'int'],
'OCI_Lob::export' => ['bool', 'filename'=>'string', 'start='=>'int', 'length='=>'int'],
'OCI_Lob::flush' => ['bool', 'flag='=>'int'],
'OCI_Lob::free' => ['bool'],
'OCI_Lob::getbuffering' => ['bool'],
'OCI_Lob::import' => ['bool', 'filename'=>'string'],
'OCI_Lob::load' => ['string|false'],
'OCI_Lob::read' => ['string|false', 'length'=>'int'],
'OCI_Lob::rewind' => ['bool'],
'OCI_Lob::save' => ['bool', 'data'=>'string', 'offset='=>'int'],
'OCI_Lob::savefile' => ['bool', 'filename'=>''],
'OCI_Lob::seek' => ['bool', 'offset'=>'int', 'whence='=>'int'],
'OCI_Lob::setbuffering' => ['bool', 'on_off'=>'bool'],
'OCI_Lob::size' => ['int|false'],
'OCI_Lob::tell' => ['int|false'],
'OCI_Lob::truncate' => ['bool', 'length='=>'int'],
'OCI_Lob::write' => ['int|false', 'data'=>'string', 'length='=>'int'],
'OCI_Lob::writeTemporary' => ['bool', 'data'=>'string', 'lob_type='=>'int'],
'OCI_Lob::writetofile' => ['bool', 'filename'=>'', 'start'=>'', 'length'=>''],
'oci_lob_append' => ['bool', 'to'=>'object'],
'oci_lob_close' => ['bool'],
'oci_lob_copy' => ['bool', 'to'=>'OCI_Lob', 'from'=>'OCI_Lob', 'length='=>'int'],
'oci_lob_eof' => ['bool'],
'oci_lob_erase' => ['int', 'lob'=>'int', 'offset'=>'int'],
'oci_lob_export' => ['bool', 'lob'=>'string', 'filename'=>'int', 'offset'=>'int'],
'oci_lob_flush' => ['bool', 'lob'=>'int'],
'oci_lob_import' => ['bool', 'lob'=>'string'],
'oci_lob_is_equal' => ['bool', 'lob1'=>'OCI_Lob', 'lob2'=>'OCI_Lob'],
'oci_lob_load' => ['string'],
'oci_lob_read' => ['string', 'lob'=>'int'],
'oci_lob_rewind' => ['bool'],
'oci_lob_save' => ['bool', 'lob'=>'string', 'data'=>'int'],
'oci_lob_seek' => ['bool', 'lob'=>'int', 'offset'=>'int'],
'oci_lob_size' => ['int'],
'oci_lob_tell' => ['int'],
'oci_lob_truncate' => ['bool', 'lob'=>'int'],
'oci_lob_write' => ['int', 'lob'=>'string', 'data'=>'int'],
'oci_lob_write_temporary' => ['bool', 'value'=>'string', 'lob_type'=>'int'],
'oci_new_collection' => ['OCI_Collection|false', 'connection'=>'resource', 'type_name'=>'string', 'schema='=>'string'],
'oci_new_connect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_new_cursor' => ['resource|false', 'connection'=>'resource'],
'oci_new_descriptor' => ['OCI_Lob|false', 'connection'=>'resource', 'type='=>'int'],
'oci_num_fields' => ['int|false', 'statement'=>'resource'],
'oci_num_rows' => ['int|false', 'statement'=>'resource'],
'oci_parse' => ['resource|false', 'connection'=>'resource', 'sql'=>'string'],
'oci_password_change' => ['bool', 'connection'=>'resource', 'username'=>'string', 'old_password'=>'string', 'new_password'=>'string'],
'oci_pconnect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_register_taf_callback' => ['bool', 'connection'=>'resource', 'callback='=>'callable'],
'oci_result' => ['mixed|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_rollback' => ['bool', 'connection'=>'resource'],
'oci_server_version' => ['string|false', 'connection'=>'resource'],
'oci_set_action' => ['bool', 'connection'=>'resource', 'action'=>'string'],
'oci_set_call_timeout' => ['bool', 'connection'=>'resource', 'timeout'=>'int'],
'oci_set_client_identifier' => ['bool', 'connection'=>'resource', 'client_id'=>'string'],
'oci_set_client_info' => ['bool', 'connection'=>'resource', 'client_info'=>'string'],
'oci_set_db_operation' => ['bool', 'connection'=>'resource', 'action'=>'string'],
'oci_set_edition' => ['bool', 'edition'=>'string'],
'oci_set_module_name' => ['bool', 'connection'=>'resource', 'name'=>'string'],
'oci_set_prefetch' => ['bool', 'statement'=>'resource', 'rows'=>'int'],
'oci_statement_type' => ['string|false', 'statement'=>'resource'],
'oci_unregister_taf_callback' => ['bool', 'connection'=>'resource'],
'ocifetchinto' => ['int|bool', 'statement'=>'resource', '&w_result'=>'array', 'mode='=>'int'],
'ocigetbufferinglob' => ['bool'],
'ocisetbufferinglob' => ['bool', 'lob'=>'bool'],
'octdec' => ['int|float', 'octal_string'=>'string'],
'odbc_autocommit' => ['mixed', 'odbc'=>'resource', 'enable='=>'bool'],
'odbc_binmode' => ['bool', 'statement'=>'resource', 'mode'=>'int'],
'odbc_close' => ['void', 'odbc'=>'resource'],
'odbc_close_all' => ['void'],
'odbc_columnprivileges' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'column'=>'string'],
'odbc_columns' => ['resource|false', 'odbc'=>'resource', 'catalog='=>'string', 'schema='=>'string', 'table='=>'string', 'column='=>'string'],
'odbc_commit' => ['bool', 'odbc'=>'resource'],
'odbc_connect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_cursor' => ['string', 'statement'=>'resource'],
'odbc_data_source' => ['array|false', 'odbc'=>'resource', 'fetch_type'=>'int'],
'odbc_do' => ['resource', 'odbc'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_error' => ['string', 'odbc='=>'resource'],
'odbc_errormsg' => ['string', 'odbc='=>'resource'],
'odbc_exec' => ['resource', 'odbc'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_execute' => ['bool', 'statement'=>'resource', 'params='=>'array'],
'odbc_fetch_array' => ['array|false', 'statement'=>'resource', 'row='=>'int'],
'odbc_fetch_into' => ['int', 'statement'=>'resource', '&w_array'=>'array', 'row='=>'int'],
'odbc_fetch_object' => ['object|false', 'statement'=>'resource', 'row='=>'int'],
'odbc_fetch_row' => ['bool', 'statement'=>'resource', 'row='=>'int'],
'odbc_field_len' => ['int|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_name' => ['string|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_num' => ['int|false', 'statement'=>'resource', 'field'=>'string'],
'odbc_field_precision' => ['int', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_scale' => ['int|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_type' => ['string|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_foreignkeys' => ['resource|false', 'odbc'=>'resource', 'pk_catalog'=>'string', 'pk_schema'=>'string', 'pk_table'=>'string', 'fk_catalog'=>'string', 'fk_schema'=>'string', 'fk_table'=>'string'],
'odbc_free_result' => ['bool', 'statement'=>'resource'],
'odbc_gettypeinfo' => ['resource', 'odbc'=>'resource', 'data_type='=>'int'],
'odbc_longreadlen' => ['bool', 'statement'=>'resource', 'length'=>'int'],
'odbc_next_result' => ['bool', 'statement'=>'resource'],
'odbc_num_fields' => ['int', 'statement'=>'resource'],
'odbc_num_rows' => ['int', 'statement'=>'resource'],
'odbc_pconnect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_prepare' => ['resource|false', 'odbc'=>'resource', 'query'=>'string'],
'odbc_primarykeys' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string'],
'odbc_procedurecolumns' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'procedure'=>'string', 'column'=>'string'],
'odbc_procedures' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'procedure'=>'string'],
'odbc_result' => ['mixed|false', 'statement'=>'resource', 'field'=>'mixed'],
'odbc_result_all' => ['int|false', 'statement'=>'resource', 'format='=>'string'],
'odbc_rollback' => ['bool', 'odbc'=>'resource'],
'odbc_setoption' => ['bool', 'odbc'=>'resource', 'which'=>'int', 'option'=>'int', 'value'=>'int'],
'odbc_specialcolumns' => ['resource|false', 'odbc'=>'resource', 'type'=>'int', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'scope'=>'int', 'nullable'=>'int'],
'odbc_statistics' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'unique'=>'int', 'accuracy'=>'int'],
'odbc_tableprivileges' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string'],
'odbc_tables' => ['resource|false', 'odbc'=>'resource', 'catalog='=>'string', 'schema='=>'string', 'table='=>'string', 'types='=>'string'],
'opcache_compile_file' => ['bool', 'filename'=>'string'],
'opcache_get_configuration' => ['array'],
'opcache_get_status' => ['array|false', 'include_scripts='=>'bool'],
'opcache_invalidate' => ['bool', 'filename'=>'string', 'force='=>'bool'],
'opcache_is_script_cached' => ['bool', 'filename'=>'string'],
'opcache_reset' => ['bool'],
'openal_buffer_create' => ['resource'],
'openal_buffer_data' => ['bool', 'buffer'=>'resource', 'format'=>'int', 'data'=>'string', 'freq'=>'int'],
'openal_buffer_destroy' => ['bool', 'buffer'=>'resource'],
'openal_buffer_get' => ['int', 'buffer'=>'resource', 'property'=>'int'],
'openal_buffer_loadwav' => ['bool', 'buffer'=>'resource', 'wavfile'=>'string'],
'openal_context_create' => ['resource', 'device'=>'resource'],
'openal_context_current' => ['bool', 'context'=>'resource'],
'openal_context_destroy' => ['bool', 'context'=>'resource'],
'openal_context_process' => ['bool', 'context'=>'resource'],
'openal_context_suspend' => ['bool', 'context'=>'resource'],
'openal_device_close' => ['bool', 'device'=>'resource'],
'openal_device_open' => ['resource|false', 'device_desc='=>'string'],
'openal_listener_get' => ['mixed', 'property'=>'int'],
'openal_listener_set' => ['bool', 'property'=>'int', 'setting'=>'mixed'],
'openal_source_create' => ['resource'],
'openal_source_destroy' => ['bool', 'source'=>'resource'],
'openal_source_get' => ['mixed', 'source'=>'resource', 'property'=>'int'],
'openal_source_pause' => ['bool', 'source'=>'resource'],
'openal_source_play' => ['bool', 'source'=>'resource'],
'openal_source_rewind' => ['bool', 'source'=>'resource'],
'openal_source_set' => ['bool', 'source'=>'resource', 'property'=>'int', 'setting'=>'mixed'],
'openal_source_stop' => ['bool', 'source'=>'resource'],
'openal_stream' => ['resource', 'source'=>'resource', 'format'=>'int', 'rate'=>'int'],
'opendir' => ['resource|false', 'directory'=>'string', 'context='=>'resource'],
'openlog' => ['bool', 'prefix'=>'string', 'flags'=>'int', 'facility'=>'int'],
'openssl_cipher_iv_length' => ['int|false', 'cipher_algo'=>'string'],
'openssl_csr_export' => ['bool', 'csr'=>'string|resource', '&w_output'=>'string', 'no_text='=>'bool'],
'openssl_csr_export_to_file' => ['bool', 'csr'=>'string|resource', 'output_filename'=>'string', 'no_text='=>'bool'],
'openssl_csr_get_public_key' => ['resource|false', 'csr'=>'string|resource', 'short_names='=>'bool'],
'openssl_csr_get_subject' => ['array|false', 'csr'=>'string|resource', 'short_names='=>'bool'],
'openssl_csr_new' => ['resource|false', 'distinguished_names'=>'array', '&w_private_key'=>'resource', 'options='=>'array', 'extra_attributes='=>'array'],
'openssl_csr_sign' => ['resource|false', 'csr'=>'string|resource', 'ca_certificate'=>'string|resource|null', 'private_key'=>'string|resource|array', 'days'=>'int', 'options='=>'array', 'serial='=>'int'],
'openssl_decrypt' => ['string|false', 'data'=>'string', 'cipher_algo'=>'string', 'passphrase'=>'string', 'options='=>'int', 'iv='=>'string', 'tag='=>'string', 'aad='=>'string'],
'openssl_dh_compute_key' => ['string|false', 'public_key'=>'string', 'private_key'=>'resource'],
'openssl_digest' => ['string|false', 'data'=>'string', 'digest_algo'=>'string', 'binary='=>'bool'],
'openssl_encrypt' => ['string|false', 'data'=>'string', 'cipher_algo'=>'string', 'passphrase'=>'string', 'options='=>'int', 'iv='=>'string', '&w_tag='=>'string', 'aad='=>'string', 'tag_length='=>'int'],
'openssl_error_string' => ['string|false'],
'openssl_free_key' => ['void', 'key'=>'resource'],
'openssl_get_cert_locations' => ['array'],
'openssl_get_cipher_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_curve_names' => ['list<string>'],
'openssl_get_md_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_privatekey' => ['resource|false', 'private_key'=>'string', 'passphrase='=>'string'],
'openssl_get_publickey' => ['resource|false', 'public_key'=>'resource|string'],
'openssl_open' => ['bool', 'data'=>'string', '&w_output'=>'string', 'encrypted_key'=>'string', 'private_key'=>'string|array|resource', 'cipher_algo='=>'string', 'iv='=>'string'],
'openssl_pbkdf2' => ['string|false', 'password'=>'string', 'salt'=>'string', 'key_length'=>'int', 'iterations'=>'int', 'digest_algo='=>'string'],
'openssl_pkcs12_export' => ['bool', 'certificate'=>'string|resource', '&w_output'=>'string', 'private_key'=>'string|array|resource', 'passphrase'=>'string', 'options='=>'array'],
'openssl_pkcs12_export_to_file' => ['bool', 'certificate'=>'string|resource', 'output_filename'=>'string', 'private_key'=>'string|array|resource', 'passphrase'=>'string', 'options='=>'array'],
'openssl_pkcs12_read' => ['bool', 'pkcs12'=>'string', '&w_certificates'=>'array', 'passphrase'=>'string'],
'openssl_pkcs7_decrypt' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource', 'private_key='=>'string|resource|array'],
'openssl_pkcs7_encrypt' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'cipher_algo='=>'int'],
'openssl_pkcs7_read' => ['bool', 'input_filename'=>'string', '&w_certificates'=>'array'],
'openssl_pkcs7_sign' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource', 'private_key'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'untrusted_certificates_filename='=>'string'],
'openssl_pkcs7_verify' => ['bool|int', 'input_filename'=>'string', 'flags'=>'int', 'signers_certificates_filename='=>'string', 'ca_info='=>'array', 'untrusted_certificates_filename='=>'string', 'content='=>'string', 'output_filename='=>'string'],
'openssl_pkey_derive' => ['string|false', 'public_key'=>'mixed', 'private_key'=>'mixed', 'key_length='=>'?int'],
'openssl_pkey_export' => ['bool', 'key'=>'resource', '&w_output'=>'string', 'passphrase='=>'string|null', 'options='=>'array'],
'openssl_pkey_export_to_file' => ['bool', 'key'=>'resource|string|array', 'output_filename'=>'string', 'passphrase='=>'string|null', 'options='=>'array'],
'openssl_pkey_free' => ['void', 'key'=>'resource'],
'openssl_pkey_get_details' => ['array|false', 'key'=>'resource'],
'openssl_pkey_get_private' => ['resource|false', 'private_key'=>'string', 'passphrase='=>'string'],
'openssl_pkey_get_public' => ['resource|false', 'public_key'=>'resource|string'],
'openssl_pkey_new' => ['resource|false', 'options='=>'array'],
'openssl_private_decrypt' => ['bool', 'data'=>'string', '&w_decrypted_data'=>'string', 'private_key'=>'string|resource|array', 'padding='=>'int'],
'openssl_private_encrypt' => ['bool', 'data'=>'string', '&w_encrypted_data'=>'string', 'private_key'=>'string|resource|array', 'padding='=>'int'],
'openssl_public_decrypt' => ['bool', 'data'=>'string', '&w_decrypted_data'=>'string', 'public_key'=>'string|resource', 'padding='=>'int'],
'openssl_public_encrypt' => ['bool', 'data'=>'string', '&w_encrypted_data'=>'string', 'public_key'=>'string|resource', 'padding='=>'int'],
'openssl_random_pseudo_bytes' => ['string|false', 'length'=>'int', '&w_strong_result='=>'bool'],
'openssl_seal' => ['int|false', 'data'=>'string', '&w_sealed_data'=>'string', '&w_encrypted_keys'=>'array', 'public_key'=>'array', 'cipher_algo='=>'string', '&rw_iv='=>'string'],
'openssl_sign' => ['bool', 'data'=>'string', '&w_signature'=>'string', 'private_key'=>'resource|string', 'algorithm='=>'int|string'],
'openssl_spki_export' => ['?string', 'spki'=>'string'],
'openssl_spki_export_challenge' => ['?string', 'spki'=>'string'],
'openssl_spki_new' => ['?string', 'private_key'=>'resource', 'challenge'=>'string', 'digest_algo='=>'int'],
'openssl_spki_verify' => ['bool', 'spki'=>'string'],
'openssl_verify' => ['-1|0|1', 'data'=>'string', 'signature'=>'string', 'public_key'=>'resource|string', 'algorithm='=>'int|string'],
'openssl_x509_check_private_key' => ['bool', 'certificate'=>'string|resource', 'private_key'=>'string|resource|array'],
'openssl_x509_checkpurpose' => ['bool|int', 'certificate'=>'string|resource', 'purpose'=>'int', 'ca_info='=>'array', 'untrusted_certificates_file='=>'string'],
'openssl_x509_export' => ['bool', 'certificate'=>'string|resource', '&w_output'=>'string', 'no_text='=>'bool'],
'openssl_x509_export_to_file' => ['bool', 'certificate'=>'string|resource', 'output_filename'=>'string', 'no_text='=>'bool'],
'openssl_x509_fingerprint' => ['string|false', 'certificate'=>'string|resource', 'digest_algo='=>'string', 'binary='=>'bool'],
'openssl_x509_free' => ['void', 'certificate'=>'resource'],
'openssl_x509_parse' => ['array|false', 'certificate'=>'string|resource', 'short_names='=>'bool'],
'openssl_x509_read' => ['resource|false', 'certificate'=>'string|resource'],
'ord' => ['int', 'character'=>'string'],
'OuterIterator::current' => ['mixed'],
'OuterIterator::getInnerIterator' => ['Iterator'],
'OuterIterator::key' => ['int|string'],
'OuterIterator::next' => ['void'],
'OuterIterator::rewind' => ['void'],
'OuterIterator::valid' => ['bool'],
'OutOfBoundsException::__clone' => ['void'],
'OutOfBoundsException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OutOfBoundsException'],
'OutOfBoundsException::__toString' => ['string'],
'OutOfBoundsException::getCode' => ['int'],
'OutOfBoundsException::getFile' => ['string'],
'OutOfBoundsException::getLine' => ['int'],
'OutOfBoundsException::getMessage' => ['string'],
'OutOfBoundsException::getPrevious' => ['Throwable|OutOfBoundsException|null'],
'OutOfBoundsException::getTrace' => ['list<array<string,mixed>>'],
'OutOfBoundsException::getTraceAsString' => ['string'],
'OutOfRangeException::__clone' => ['void'],
'OutOfRangeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OutOfRangeException'],
'OutOfRangeException::__toString' => ['string'],
'OutOfRangeException::getCode' => ['int'],
'OutOfRangeException::getFile' => ['string'],
'OutOfRangeException::getLine' => ['int'],
'OutOfRangeException::getMessage' => ['string'],
'OutOfRangeException::getPrevious' => ['Throwable|OutOfRangeException|null'],
'OutOfRangeException::getTrace' => ['list<array<string,mixed>>'],
'OutOfRangeException::getTraceAsString' => ['string'],
'output_add_rewrite_var' => ['bool', 'name'=>'string', 'value'=>'string'],
'output_cache_disable' => ['void'],
'output_cache_disable_compression' => ['void'],
'output_cache_exists' => ['bool', 'key'=>'string', 'lifetime'=>'int'],
'output_cache_fetch' => ['string', 'key'=>'string', 'function'=>'', 'lifetime'=>'int'],
'output_cache_get' => ['mixed|false', 'key'=>'string', 'lifetime'=>'int'],
'output_cache_output' => ['string', 'key'=>'string', 'function'=>'', 'lifetime'=>'int'],
'output_cache_put' => ['bool', 'key'=>'string', 'data'=>'mixed'],
'output_cache_remove' => ['bool', 'filename'=>''],
'output_cache_remove_key' => ['bool', 'key'=>'string'],
'output_cache_remove_url' => ['bool', 'url'=>'string'],
'output_cache_stop' => ['void'],
'output_reset_rewrite_vars' => ['bool'],
'outputformatObj::getOption' => ['string', 'property_name'=>'string'],
'outputformatObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'outputformatObj::setOption' => ['void', 'property_name'=>'string', 'new_value'=>'string'],
'outputformatObj::validate' => ['int'],
'OverflowException::__clone' => ['void'],
'OverflowException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OverflowException'],
'OverflowException::__toString' => ['string'],
'OverflowException::getCode' => ['int'],
'OverflowException::getFile' => ['string'],
'OverflowException::getLine' => ['int'],
'OverflowException::getMessage' => ['string'],
'OverflowException::getPrevious' => ['Throwable|OverflowException|null'],
'OverflowException::getTrace' => ['list<array<string,mixed>>'],
'OverflowException::getTraceAsString' => ['string'],
'overload' => ['', 'class_name'=>'string'],
'override_function' => ['bool', 'function_name'=>'string', 'function_args'=>'string', 'function_code'=>'string'],
'OwsrequestObj::__construct' => ['void'],
'OwsrequestObj::addParameter' => ['int', 'name'=>'string', 'value'=>'string'],
'OwsrequestObj::getName' => ['string', 'index'=>'int'],
'OwsrequestObj::getValue' => ['string', 'index'=>'int'],
'OwsrequestObj::getValueByName' => ['string', 'name'=>'string'],
'OwsrequestObj::loadParams' => ['int'],
'OwsrequestObj::setParameter' => ['int', 'name'=>'string', 'value'=>'string'],
'pack' => ['string|false', 'format'=>'string', '...values='=>'mixed'],
'parallel\Future::done' => ['bool'],
'parallel\Future::select' => ['mixed', '&resolving'=>'parallel\Future[]', '&w_resolved'=>'parallel\Future[]', '&w_errored'=>'parallel\Future[]', '&w_timedout='=>'parallel\Future[]', 'timeout='=>'int'],
'parallel\Future::value' => ['mixed', 'timeout='=>'int'],
'parallel\Runtime::__construct' => ['void', 'arg'=>'string|array'],
'parallel\Runtime::__construct\'1' => ['void', 'bootstrap'=>'string', 'configuration'=>'array<string,mixed>'],
'parallel\Runtime::close' => ['void'],
'parallel\Runtime::kill' => ['void'],
'parallel\Runtime::run' => ['?parallel\Future', 'closure'=>'Closure', 'args='=>'array'],
'ParentIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator'],
'ParentIterator::accept' => ['bool'],
'ParentIterator::getChildren' => ['ParentIterator'],
'ParentIterator::hasChildren' => ['bool'],
'ParentIterator::next' => ['void'],
'ParentIterator::rewind' => ['void'],
'ParentIterator::valid' => [''],
'Parle\Lexer::advance' => ['void'],
'Parle\Lexer::build' => ['void'],
'Parle\Lexer::callout' => ['void', 'id'=>'int', 'callback'=>'callable'],
'Parle\Lexer::consume' => ['void', 'data'=>'string'],
'Parle\Lexer::dump' => ['void'],
'Parle\Lexer::getToken' => ['Parle\Token'],
'Parle\Lexer::insertMacro' => ['void', 'name'=>'string', 'regex'=>'string'],
'Parle\Lexer::push' => ['void', 'regex'=>'string', 'id'=>'int'],
'Parle\Lexer::reset' => ['void', 'pos'=>'int'],
'Parle\Parser::advance' => ['void'],
'Parle\Parser::build' => ['void'],
'Parle\Parser::consume' => ['void', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\Parser::dump' => ['void'],
'Parle\Parser::errorInfo' => ['Parle\ErrorInfo'],
'Parle\Parser::left' => ['void', 'token'=>'string'],
'Parle\Parser::nonassoc' => ['void', 'token'=>'string'],
'Parle\Parser::precedence' => ['void', 'token'=>'string'],
'Parle\Parser::push' => ['int', 'name'=>'string', 'rule'=>'string'],
'Parle\Parser::reset' => ['void', 'tokenId'=>'int'],
'Parle\Parser::right' => ['void', 'token'=>'string'],
'Parle\Parser::sigil' => ['string', 'idx'=>'array'],
'Parle\Parser::token' => ['void', 'token'=>'string'],
'Parle\Parser::tokenId' => ['int', 'token'=>'string'],
'Parle\Parser::trace' => ['string'],
'Parle\Parser::validate' => ['bool', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\RLexer::advance' => ['void'],
'Parle\RLexer::build' => ['void'],
'Parle\RLexer::callout' => ['void', 'id'=>'int', 'callback'=>'callable'],
'Parle\RLexer::consume' => ['void', 'data'=>'string'],
'Parle\RLexer::dump' => ['void'],
'Parle\RLexer::getToken' => ['Parle\Token'],
'parle\rlexer::insertMacro' => ['void', 'name'=>'string', 'regex'=>'string'],
'Parle\RLexer::push' => ['void', 'state'=>'string', 'regex'=>'string', 'newState'=>'string'],
'Parle\RLexer::pushState' => ['int', 'state'=>'string'],
'Parle\RLexer::reset' => ['void', 'pos'=>'int'],
'Parle\RParser::advance' => ['void'],
'Parle\RParser::build' => ['void'],
'Parle\RParser::consume' => ['void', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\RParser::dump' => ['void'],
'Parle\RParser::errorInfo' => ['Parle\ErrorInfo'],
'Parle\RParser::left' => ['void', 'token'=>'string'],
'Parle\RParser::nonassoc' => ['void', 'token'=>'string'],
'Parle\RParser::precedence' => ['void', 'token'=>'string'],
'Parle\RParser::push' => ['int', 'name'=>'string', 'rule'=>'string'],
'Parle\RParser::reset' => ['void', 'tokenId'=>'int'],
'Parle\RParser::right' => ['void', 'token'=>'string'],
'Parle\RParser::sigil' => ['string', 'idx'=>'array'],
'Parle\RParser::token' => ['void', 'token'=>'string'],
'Parle\RParser::tokenId' => ['int', 'token'=>'string'],
'Parle\RParser::trace' => ['string'],
'Parle\RParser::validate' => ['bool', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\Stack::pop' => ['void'],
'Parle\Stack::push' => ['void', 'item'=>'mixed'],
'parse_ini_file' => ['array|false', 'filename'=>'string', 'process_sections='=>'bool', 'scanner_mode='=>'int'],
'parse_ini_string' => ['array|false', 'ini_string'=>'string', 'process_sections='=>'bool', 'scanner_mode='=>'int'],
'parse_str' => ['void', 'string'=>'string', '&w_result='=>'array'],
'parse_url' => ['mixed|false', 'url'=>'string', 'component='=>'int'],
'ParseError::__clone' => ['void'],
'ParseError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?ParseError'],
'ParseError::__toString' => ['string'],
'ParseError::getCode' => ['int'],
'ParseError::getFile' => ['string'],
'ParseError::getLine' => ['int'],
'ParseError::getMessage' => ['string'],
'ParseError::getPrevious' => ['Throwable|ParseError|null'],
'ParseError::getTrace' => ['list<array<string,mixed>>'],
'ParseError::getTraceAsString' => ['string'],
'parsekit_compile_file' => ['array', 'filename'=>'string', 'errors='=>'array', 'options='=>'int'],
'parsekit_compile_string' => ['array', 'phpcode'=>'string', 'errors='=>'array', 'options='=>'int'],
'parsekit_func_arginfo' => ['array', 'function'=>'mixed'],
'passthru' => ['void', 'command'=>'string', '&w_result_code='=>'int'],
'password_get_info' => ['array', 'hash'=>'string'],
'password_hash' => ['string|null', 'password'=>'string', 'algo'=>'int|string|null', 'options='=>'array'],
'password_make_salt' => ['bool', 'password'=>'string', 'hash'=>'string'],
'password_needs_rehash' => ['bool', 'hash'=>'string', 'algo'=>'int|string|null', 'options='=>'array'],
'password_verify' => ['bool', 'password'=>'string', 'hash'=>'string'],
'pathinfo' => ['array|string', 'path'=>'string', 'flags='=>'int'],
'pclose' => ['int', 'handle'=>'resource'],
'pcnlt_sigwaitinfo' => ['int', 'set'=>'array', '&w_siginfo'=>'array'],
'pcntl_alarm' => ['int', 'seconds'=>'int'],
'pcntl_async_signals' => ['bool', 'enable='=>'bool'],
'pcntl_errno' => ['int'],
'pcntl_exec' => ['null|false', 'path'=>'string', 'args='=>'array', 'env_vars='=>'array'],
'pcntl_fork' => ['int'],
'pcntl_get_last_error' => ['int'],
'pcntl_getpriority' => ['int', 'process_id='=>'int', 'mode='=>'int'],
'pcntl_setpriority' => ['bool', 'priority'=>'int', 'process_id='=>'int', 'mode='=>'int'],
'pcntl_signal' => ['bool', 'signal'=>'int', 'handler'=>'callable():void|callable(int):void|callable(int,array):void|int', 'restart_syscalls='=>'bool'],
'pcntl_signal_dispatch' => ['bool'],
'pcntl_signal_get_handler' => ['int|string', 'signal'=>'int'],
'pcntl_sigprocmask' => ['bool', 'mode'=>'int', 'signals'=>'array', '&w_old_signals='=>'array'],
'pcntl_sigtimedwait' => ['int', 'signals'=>'array', '&w_info='=>'array', 'seconds='=>'int', 'nanoseconds='=>'int'],
'pcntl_sigwaitinfo' => ['int', 'signals'=>'array', '&w_info='=>'array'],
'pcntl_strerror' => ['string|false', 'error_code'=>'int'],
'pcntl_wait' => ['int', '&w_status'=>'int', 'flags='=>'int', '&w_resource_usage='=>'array'],
'pcntl_waitpid' => ['int', 'process_id'=>'int', '&w_status'=>'int', 'flags='=>'int', '&w_resource_usage='=>'array'],
'pcntl_wexitstatus' => ['int', 'status'=>'int'],
'pcntl_wifcontinued' => ['bool', 'status'=>'int'],
'pcntl_wifexited' => ['bool', 'status'=>'int'],
'pcntl_wifsignaled' => ['bool', 'status'=>'int'],
'pcntl_wifstopped' => ['bool', 'status'=>'int'],
'pcntl_wstopsig' => ['int', 'status'=>'int'],
'pcntl_wtermsig' => ['int', 'status'=>'int'],
'PDF_activate_item' => ['bool', 'pdfdoc'=>'resource', 'id'=>'int'],
'PDF_add_launchlink' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'PDF_add_locallink' => ['bool', 'pdfdoc'=>'resource', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'page'=>'int', 'dest'=>'string'],
'PDF_add_nameddest' => ['bool', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_add_note' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'PDF_add_pdflink' => ['bool', 'pdfdoc'=>'resource', 'bottom_left_x'=>'float', 'bottom_left_y'=>'float', 'up_right_x'=>'float', 'up_right_y'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'PDF_add_table_cell' => ['int', 'pdfdoc'=>'resource', 'table'=>'int', 'column'=>'int', 'row'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDF_add_textflow' => ['int', 'pdfdoc'=>'resource', 'textflow'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDF_add_thumbnail' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int'],
'PDF_add_weblink' => ['bool', 'pdfdoc'=>'resource', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'url'=>'string'],
'PDF_arc' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDF_arcn' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDF_attach_file' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'description'=>'string', 'author'=>'string', 'mimetype'=>'string', 'icon'=>'string'],
'PDF_begin_document' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_begin_font' => ['bool', 'pdfdoc'=>'resource', 'filename'=>'string', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float', 'optlist'=>'string'],
'PDF_begin_glyph' => ['bool', 'pdfdoc'=>'resource', 'glyphname'=>'string', 'wx'=>'float', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float'],
'PDF_begin_item' => ['int', 'pdfdoc'=>'resource', 'tag'=>'string', 'optlist'=>'string'],
'PDF_begin_layer' => ['bool', 'pdfdoc'=>'resource', 'layer'=>'int'],
'PDF_begin_page' => ['bool', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'PDF_begin_page_ext' => ['bool', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDF_begin_pattern' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'PDF_begin_template' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'PDF_begin_template_ext' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDF_circle' => ['bool', 'pdfdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float'],
'PDF_clip' => ['bool', 'p'=>'resource'],
'PDF_close' => ['bool', 'p'=>'resource'],
'PDF_close_image' => ['bool', 'p'=>'resource', 'image'=>'int'],
'PDF_close_pdi' => ['bool', 'p'=>'resource', 'doc'=>'int'],
'PDF_close_pdi_page' => ['bool', 'p'=>'resource', 'page'=>'int'],
'PDF_closepath' => ['bool', 'p'=>'resource'],
'PDF_closepath_fill_stroke' => ['bool', 'p'=>'resource'],
'PDF_closepath_stroke' => ['bool', 'p'=>'resource'],
'PDF_concat' => ['bool', 'p'=>'resource', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDF_continue_text' => ['bool', 'p'=>'resource', 'text'=>'string'],
'PDF_create_3dview' => ['int', 'pdfdoc'=>'resource', 'username'=>'string', 'optlist'=>'string'],
'PDF_create_action' => ['int', 'pdfdoc'=>'resource', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_annotation' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_bookmark' => ['int', 'pdfdoc'=>'resource', 'text'=>'string', 'optlist'=>'string'],
'PDF_create_field' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'name'=>'string', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_fieldgroup' => ['bool', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_create_gstate' => ['int', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_create_pvf' => ['bool', 'pdfdoc'=>'resource', 'filename'=>'string', 'data'=>'string', 'optlist'=>'string'],
'PDF_create_textflow' => ['int', 'pdfdoc'=>'resource', 'text'=>'string', 'optlist'=>'string'],
'PDF_curveto' => ['bool', 'p'=>'resource', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'PDF_define_layer' => ['int', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_delete' => ['bool', 'pdfdoc'=>'resource'],
'PDF_delete_pvf' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string'],
'PDF_delete_table' => ['bool', 'pdfdoc'=>'resource', 'table'=>'int', 'optlist'=>'string'],
'PDF_delete_textflow' => ['bool', 'pdfdoc'=>'resource', 'textflow'=>'int'],
'PDF_encoding_set_char' => ['bool', 'pdfdoc'=>'resource', 'encoding'=>'string', 'slot'=>'int', 'glyphname'=>'string', 'uv'=>'int'],
'PDF_end_document' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_end_font' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_glyph' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_item' => ['bool', 'pdfdoc'=>'resource', 'id'=>'int'],
'PDF_end_layer' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_page' => ['bool', 'p'=>'resource'],
'PDF_end_page_ext' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_end_pattern' => ['bool', 'p'=>'resource'],
'PDF_end_template' => ['bool', 'p'=>'resource'],
'PDF_endpath' => ['bool', 'p'=>'resource'],
'PDF_fill' => ['bool', 'p'=>'resource'],
'PDF_fill_imageblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'image'=>'int', 'optlist'=>'string'],
'PDF_fill_pdfblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'contents'=>'int', 'optlist'=>'string'],
'PDF_fill_stroke' => ['bool', 'p'=>'resource'],
'PDF_fill_textblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'text'=>'string', 'optlist'=>'string'],
'PDF_findfont' => ['int', 'p'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'embed'=>'int'],
'PDF_fit_image' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_fit_pdi_page' => ['bool', 'pdfdoc'=>'resource', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_fit_table' => ['string', 'pdfdoc'=>'resource', 'table'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDF_fit_textflow' => ['string', 'pdfdoc'=>'resource', 'textflow'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDF_fit_textline' => ['bool', 'pdfdoc'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_get_apiname' => ['string', 'pdfdoc'=>'resource'],
'PDF_get_buffer' => ['string', 'p'=>'resource'],
'PDF_get_errmsg' => ['string', 'pdfdoc'=>'resource'],
'PDF_get_errnum' => ['int', 'pdfdoc'=>'resource'],
'PDF_get_majorversion' => ['int'],
'PDF_get_minorversion' => ['int'],
'PDF_get_parameter' => ['string', 'p'=>'resource', 'key'=>'string', 'modifier'=>'float'],
'PDF_get_pdi_parameter' => ['string', 'p'=>'resource', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDF_get_pdi_value' => ['float', 'p'=>'resource', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDF_get_value' => ['float', 'p'=>'resource', 'key'=>'string', 'modifier'=>'float'],
'PDF_info_font' => ['float', 'pdfdoc'=>'resource', 'font'=>'int', 'keyword'=>'string', 'optlist'=>'string'],
'PDF_info_matchbox' => ['float', 'pdfdoc'=>'resource', 'boxname'=>'string', 'num'=>'int', 'keyword'=>'string'],
'PDF_info_table' => ['float', 'pdfdoc'=>'resource', 'table'=>'int', 'keyword'=>'string'],
'PDF_info_textflow' => ['float', 'pdfdoc'=>'resource', 'textflow'=>'int', 'keyword'=>'string'],
'PDF_info_textline' => ['float', 'pdfdoc'=>'resource', 'text'=>'string', 'keyword'=>'string', 'optlist'=>'string'],
'PDF_initgraphics' => ['bool', 'p'=>'resource'],
'PDF_lineto' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_load_3ddata' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_load_font' => ['int', 'pdfdoc'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'optlist'=>'string'],
'PDF_load_iccprofile' => ['int', 'pdfdoc'=>'resource', 'profilename'=>'string', 'optlist'=>'string'],
'PDF_load_image' => ['int', 'pdfdoc'=>'resource', 'imagetype'=>'string', 'filename'=>'string', 'optlist'=>'string'],
'PDF_makespotcolor' => ['int', 'p'=>'resource', 'spotname'=>'string'],
'PDF_moveto' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_new' => ['resource'],
'PDF_open_ccitt' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'bitreverse'=>'int', 'k'=>'int', 'blackls1'=>'int'],
'PDF_open_file' => ['bool', 'p'=>'resource', 'filename'=>'string'],
'PDF_open_image' => ['int', 'p'=>'resource', 'imagetype'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'PDF_open_image_file' => ['int', 'p'=>'resource', 'imagetype'=>'string', 'filename'=>'string', 'stringparam'=>'string', 'intparam'=>'int'],
'PDF_open_memory_image' => ['int', 'p'=>'resource', 'image'=>'resource'],
'PDF_open_pdi' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string', 'length'=>'int'],
'PDF_open_pdi_document' => ['int', 'p'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_open_pdi_page' => ['int', 'p'=>'resource', 'doc'=>'int', 'pagenumber'=>'int', 'optlist'=>'string'],
'PDF_pcos_get_number' => ['float', 'p'=>'resource', 'doc'=>'int', 'path'=>'string'],
'PDF_pcos_get_stream' => ['string', 'p'=>'resource', 'doc'=>'int', 'optlist'=>'string', 'path'=>'string'],
'PDF_pcos_get_string' => ['string', 'p'=>'resource', 'doc'=>'int', 'path'=>'string'],
'PDF_place_image' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'PDF_place_pdi_page' => ['bool', 'pdfdoc'=>'resource', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'sx'=>'float', 'sy'=>'float'],
'PDF_process_pdi' => ['int', 'pdfdoc'=>'resource', 'doc'=>'int', 'page'=>'int', 'optlist'=>'string'],
'PDF_rect' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'PDF_restore' => ['bool', 'p'=>'resource'],
'PDF_resume_page' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_rotate' => ['bool', 'p'=>'resource', 'phi'=>'float'],
'PDF_save' => ['bool', 'p'=>'resource'],
'PDF_scale' => ['bool', 'p'=>'resource', 'sx'=>'float', 'sy'=>'float'],
'PDF_set_border_color' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_set_border_dash' => ['bool', 'pdfdoc'=>'resource', 'black'=>'float', 'white'=>'float'],
'PDF_set_border_style' => ['bool', 'pdfdoc'=>'resource', 'style'=>'string', 'width'=>'float'],
'PDF_set_gstate' => ['bool', 'pdfdoc'=>'resource', 'gstate'=>'int'],
'PDF_set_info' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'PDF_set_layer_dependency' => ['bool', 'pdfdoc'=>'resource', 'type'=>'string', 'optlist'=>'string'],
'PDF_set_parameter' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'PDF_set_text_pos' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_set_value' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'float'],
'PDF_setcolor' => ['bool', 'p'=>'resource', 'fstype'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'PDF_setdash' => ['bool', 'pdfdoc'=>'resource', 'b'=>'float', 'w'=>'float'],
'PDF_setdashpattern' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_setflat' => ['bool', 'pdfdoc'=>'resource', 'flatness'=>'float'],
'PDF_setfont' => ['bool', 'pdfdoc'=>'resource', 'font'=>'int', 'fontsize'=>'float'],
'PDF_setgray' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setgray_fill' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setgray_stroke' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setlinecap' => ['bool', 'p'=>'resource', 'linecap'=>'int'],
'PDF_setlinejoin' => ['bool', 'p'=>'resource', 'value'=>'int'],
'PDF_setlinewidth' => ['bool', 'p'=>'resource', 'width'=>'float'],
'PDF_setmatrix' => ['bool', 'p'=>'resource', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDF_setmiterlimit' => ['bool', 'pdfdoc'=>'resource', 'miter'=>'float'],
'PDF_setrgbcolor' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_setrgbcolor_fill' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_setrgbcolor_stroke' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_shading' => ['int', 'pdfdoc'=>'resource', 'shtype'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'PDF_shading_pattern' => ['int', 'pdfdoc'=>'resource', 'shading'=>'int', 'optlist'=>'string'],
'PDF_shfill' => ['bool', 'pdfdoc'=>'resource', 'shading'=>'int'],
'PDF_show' => ['bool', 'pdfdoc'=>'resource', 'text'=>'string'],
'PDF_show_boxed' => ['int', 'p'=>'resource', 'text'=>'string', 'left'=>'float', 'top'=>'float', 'width'=>'float', 'height'=>'float', 'mode'=>'string', 'feature'=>'string'],
'PDF_show_xy' => ['bool', 'p'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'PDF_skew' => ['bool', 'p'=>'resource', 'alpha'=>'float', 'beta'=>'float'],
'PDF_stringwidth' => ['float', 'p'=>'resource', 'text'=>'string', 'font'=>'int', 'fontsize'=>'float'],
'PDF_stroke' => ['bool', 'p'=>'resource'],
'PDF_suspend_page' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_translate' => ['bool', 'p'=>'resource', 'tx'=>'float', 'ty'=>'float'],
'PDF_utf16_to_utf8' => ['string', 'pdfdoc'=>'resource', 'utf16string'=>'string'],
'PDF_utf32_to_utf16' => ['string', 'pdfdoc'=>'resource', 'utf32string'=>'string', 'ordering'=>'string'],
'PDF_utf8_to_utf16' => ['string', 'pdfdoc'=>'resource', 'utf8string'=>'string', 'ordering'=>'string'],
'PDFlib::activate_item' => ['bool', 'id'=>''],
'PDFlib::add_launchlink' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'PDFlib::add_locallink' => ['bool', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'page'=>'int', 'dest'=>'string'],
'PDFlib::add_nameddest' => ['bool', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::add_note' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'PDFlib::add_pdflink' => ['bool', 'bottom_left_x'=>'float', 'bottom_left_y'=>'float', 'up_right_x'=>'float', 'up_right_y'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'PDFlib::add_table_cell' => ['int', 'table'=>'int', 'column'=>'int', 'row'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::add_textflow' => ['int', 'textflow'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::add_thumbnail' => ['bool', 'image'=>'int'],
'PDFlib::add_weblink' => ['bool', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'url'=>'string'],
'PDFlib::arc' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::arcn' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::attach_file' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'description'=>'string', 'author'=>'string', 'mimetype'=>'string', 'icon'=>'string'],
'PDFlib::begin_document' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::begin_font' => ['bool', 'filename'=>'string', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float', 'optlist'=>'string'],
'PDFlib::begin_glyph' => ['bool', 'glyphname'=>'string', 'wx'=>'float', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float'],
'PDFlib::begin_item' => ['int', 'tag'=>'string', 'optlist'=>'string'],
'PDFlib::begin_layer' => ['bool', 'layer'=>'int'],
'PDFlib::begin_page' => ['bool', 'width'=>'float', 'height'=>'float'],
'PDFlib::begin_page_ext' => ['bool', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDFlib::begin_pattern' => ['int', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'PDFlib::begin_template' => ['int', 'width'=>'float', 'height'=>'float'],
'PDFlib::begin_template_ext' => ['int', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDFlib::circle' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float'],
'PDFlib::clip' => ['bool'],
'PDFlib::close' => ['bool'],
'PDFlib::close_image' => ['bool', 'image'=>'int'],
'PDFlib::close_pdi' => ['bool', 'doc'=>'int'],
'PDFlib::close_pdi_page' => ['bool', 'page'=>'int'],
'PDFlib::closepath' => ['bool'],
'PDFlib::closepath_fill_stroke' => ['bool'],
'PDFlib::closepath_stroke' => ['bool'],
'PDFlib::concat' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDFlib::continue_text' => ['bool', 'text'=>'string'],
'PDFlib::create_3dview' => ['int', 'username'=>'string', 'optlist'=>'string'],
'PDFlib::create_action' => ['int', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_annotation' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_bookmark' => ['int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::create_field' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'name'=>'string', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_fieldgroup' => ['bool', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::create_gstate' => ['int', 'optlist'=>'string'],
'PDFlib::create_pvf' => ['bool', 'filename'=>'string', 'data'=>'string', 'optlist'=>'string'],
'PDFlib::create_textflow' => ['int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::curveto' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'PDFlib::define_layer' => ['int', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::delete' => ['bool'],
'PDFlib::delete_pvf' => ['int', 'filename'=>'string'],
'PDFlib::delete_table' => ['bool', 'table'=>'int', 'optlist'=>'string'],
'PDFlib::delete_textflow' => ['bool', 'textflow'=>'int'],
'PDFlib::encoding_set_char' => ['bool', 'encoding'=>'string', 'slot'=>'int', 'glyphname'=>'string', 'uv'=>'int'],
'PDFlib::end_document' => ['bool', 'optlist'=>'string'],
'PDFlib::end_font' => ['bool'],
'PDFlib::end_glyph' => ['bool'],
'PDFlib::end_item' => ['bool', 'id'=>'int'],
'PDFlib::end_layer' => ['bool'],
'PDFlib::end_page' => ['bool', 'p'=>''],
'PDFlib::end_page_ext' => ['bool', 'optlist'=>'string'],
'PDFlib::end_pattern' => ['bool', 'p'=>''],
'PDFlib::end_template' => ['bool', 'p'=>''],
'PDFlib::endpath' => ['bool', 'p'=>''],
'PDFlib::fill' => ['bool'],
'PDFlib::fill_imageblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'image'=>'int', 'optlist'=>'string'],
'PDFlib::fill_pdfblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'contents'=>'int', 'optlist'=>'string'],
'PDFlib::fill_stroke' => ['bool'],
'PDFlib::fill_textblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::findfont' => ['int', 'fontname'=>'string', 'encoding'=>'string', 'embed'=>'int'],
'PDFlib::fit_image' => ['bool', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::fit_pdi_page' => ['bool', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::fit_table' => ['string', 'table'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDFlib::fit_textflow' => ['string', 'textflow'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDFlib::fit_textline' => ['bool', 'text'=>'string', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::get_apiname' => ['string'],
'PDFlib::get_buffer' => ['string'],
'PDFlib::get_errmsg' => ['string'],
'PDFlib::get_errnum' => ['int'],
'PDFlib::get_majorversion' => ['int'],
'PDFlib::get_minorversion' => ['int'],
'PDFlib::get_parameter' => ['string', 'key'=>'string', 'modifier'=>'float'],
'PDFlib::get_pdi_parameter' => ['string', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDFlib::get_pdi_value' => ['float', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDFlib::get_value' => ['float', 'key'=>'string', 'modifier'=>'float'],
'PDFlib::info_font' => ['float', 'font'=>'int', 'keyword'=>'string', 'optlist'=>'string'],
'PDFlib::info_matchbox' => ['float', 'boxname'=>'string', 'num'=>'int', 'keyword'=>'string'],
'PDFlib::info_table' => ['float', 'table'=>'int', 'keyword'=>'string'],
'PDFlib::info_textflow' => ['float', 'textflow'=>'int', 'keyword'=>'string'],
'PDFlib::info_textline' => ['float', 'text'=>'string', 'keyword'=>'string', 'optlist'=>'string'],
'PDFlib::initgraphics' => ['bool'],
'PDFlib::lineto' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::load_3ddata' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::load_font' => ['int', 'fontname'=>'string', 'encoding'=>'string', 'optlist'=>'string'],
'PDFlib::load_iccprofile' => ['int', 'profilename'=>'string', 'optlist'=>'string'],
'PDFlib::load_image' => ['int', 'imagetype'=>'string', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::makespotcolor' => ['int', 'spotname'=>'string'],
'PDFlib::moveto' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::open_ccitt' => ['int', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'BitReverse'=>'int', 'k'=>'int', 'Blackls1'=>'int'],
'PDFlib::open_file' => ['bool', 'filename'=>'string'],
'PDFlib::open_image' => ['int', 'imagetype'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'PDFlib::open_image_file' => ['int', 'imagetype'=>'string', 'filename'=>'string', 'stringparam'=>'string', 'intparam'=>'int'],
'PDFlib::open_memory_image' => ['int', 'image'=>'resource'],
'PDFlib::open_pdi' => ['int', 'filename'=>'string', 'optlist'=>'string', 'length'=>'int'],
'PDFlib::open_pdi_document' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::open_pdi_page' => ['int', 'doc'=>'int', 'pagenumber'=>'int', 'optlist'=>'string'],
'PDFlib::pcos_get_number' => ['float', 'doc'=>'int', 'path'=>'string'],
'PDFlib::pcos_get_stream' => ['string', 'doc'=>'int', 'optlist'=>'string', 'path'=>'string'],
'PDFlib::pcos_get_string' => ['string', 'doc'=>'int', 'path'=>'string'],
'PDFlib::place_image' => ['bool', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'PDFlib::place_pdi_page' => ['bool', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'sx'=>'float', 'sy'=>'float'],
'PDFlib::process_pdi' => ['int', 'doc'=>'int', 'page'=>'int', 'optlist'=>'string'],
'PDFlib::rect' => ['bool', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'PDFlib::restore' => ['bool', 'p'=>''],
'PDFlib::resume_page' => ['bool', 'optlist'=>'string'],
'PDFlib::rotate' => ['bool', 'phi'=>'float'],
'PDFlib::save' => ['bool', 'p'=>''],
'PDFlib::scale' => ['bool', 'sx'=>'float', 'sy'=>'float'],
'PDFlib::set_border_color' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::set_border_dash' => ['bool', 'black'=>'float', 'white'=>'float'],
'PDFlib::set_border_style' => ['bool', 'style'=>'string', 'width'=>'float'],
'PDFlib::set_gstate' => ['bool', 'gstate'=>'int'],
'PDFlib::set_info' => ['bool', 'key'=>'string', 'value'=>'string'],
'PDFlib::set_layer_dependency' => ['bool', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::set_parameter' => ['bool', 'key'=>'string', 'value'=>'string'],
'PDFlib::set_text_pos' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::set_value' => ['bool', 'key'=>'string', 'value'=>'float'],
'PDFlib::setcolor' => ['bool', 'fstype'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'PDFlib::setdash' => ['bool', 'b'=>'float', 'w'=>'float'],
'PDFlib::setdashpattern' => ['bool', 'optlist'=>'string'],
'PDFlib::setflat' => ['bool', 'flatness'=>'float'],
'PDFlib::setfont' => ['bool', 'font'=>'int', 'fontsize'=>'float'],
'PDFlib::setgray' => ['bool', 'g'=>'float'],
'PDFlib::setgray_fill' => ['bool', 'g'=>'float'],
'PDFlib::setgray_stroke' => ['bool', 'g'=>'float'],
'PDFlib::setlinecap' => ['bool', 'linecap'=>'int'],
'PDFlib::setlinejoin' => ['bool', 'value'=>'int'],
'PDFlib::setlinewidth' => ['bool', 'width'=>'float'],
'PDFlib::setmatrix' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDFlib::setmiterlimit' => ['bool', 'miter'=>'float'],
'PDFlib::setrgbcolor' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::setrgbcolor_fill' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::setrgbcolor_stroke' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::shading' => ['int', 'shtype'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'PDFlib::shading_pattern' => ['int', 'shading'=>'int', 'optlist'=>'string'],
'PDFlib::shfill' => ['bool', 'shading'=>'int'],
'PDFlib::show' => ['bool', 'text'=>'string'],
'PDFlib::show_boxed' => ['int', 'text'=>'string', 'left'=>'float', 'top'=>'float', 'width'=>'float', 'height'=>'float', 'mode'=>'string', 'feature'=>'string'],
'PDFlib::show_xy' => ['bool', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'PDFlib::skew' => ['bool', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::stringwidth' => ['float', 'text'=>'string', 'font'=>'int', 'fontsize'=>'float'],
'PDFlib::stroke' => ['bool', 'p'=>''],
'PDFlib::suspend_page' => ['bool', 'optlist'=>'string'],
'PDFlib::translate' => ['bool', 'tx'=>'float', 'ty'=>'float'],
'PDFlib::utf16_to_utf8' => ['string', 'utf16string'=>'string'],
'PDFlib::utf32_to_utf16' => ['string', 'utf32string'=>'string', 'ordering'=>'string'],
'PDFlib::utf8_to_utf16' => ['string', 'utf8string'=>'string', 'ordering'=>'string'],
'PDO::__construct' => ['void', 'dsn'=>'string', 'username='=>'?string', 'passwd='=>'?string', 'options='=>'?array'],
'PDO::__sleep' => ['list<string>'],
'PDO::__wakeup' => ['void'],
'PDO::beginTransaction' => ['bool'],
'PDO::commit' => ['bool'],
'PDO::cubrid_schema' => ['array', 'schema_type'=>'int', 'table_name='=>'string', 'col_name='=>'string'],
'PDO::errorCode' => ['?string'],
'PDO::errorInfo' => ['array'],
'PDO::exec' => ['int|false', 'query'=>'string'],
'PDO::getAttribute' => ['', 'attribute'=>'int'],
'PDO::getAvailableDrivers' => ['array'],
'PDO::inTransaction' => ['bool'],
'PDO::lastInsertId' => ['string', 'name='=>'string|null'],
'PDO::pgsqlCopyFromArray' => ['bool', 'table_name'=>'string', 'rows'=>'array', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyFromFile' => ['bool', 'table_name'=>'string', 'filename'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyToArray' => ['array', 'table_name'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyToFile' => ['bool', 'table_name'=>'string', 'filename'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlGetNotify' => ['array', 'result_type'=>'int', 'ms_timeout'=>'int'],
'PDO::pgsqlGetPid' => ['int'],
'PDO::pgsqlLOBCreate' => ['string'],
'PDO::pgsqlLOBOpen' => ['resource', 'oid'=>'string', 'mode='=>'string'],
'PDO::pgsqlLOBUnlink' => ['bool', 'oid'=>'string'],
'PDO::prepare' => ['PDOStatement|false', 'statement'=>'string', 'options='=>'array'],
'PDO::query' => ['PDOStatement|false', 'sql'=>'string'],
'PDO::query\'1' => ['PDOStatement|false', 'sql'=>'string', 'fetch_column'=>'int', 'colno='=>'int'],
'PDO::query\'2' => ['PDOStatement|false', 'sql'=>'string', 'fetch_class'=>'int', 'classname'=>'string', 'ctorargs'=>'array'],
'PDO::query\'3' => ['PDOStatement|false', 'sql'=>'string', 'fetch_into'=>'int', 'object'=>'object'],
'PDO::quote' => ['string|false', 'string'=>'string', 'paramtype='=>'int'],
'PDO::rollBack' => ['bool'],
'PDO::setAttribute' => ['bool', 'attribute'=>'int', 'value'=>''],
'PDO::sqliteCreateAggregate' => ['bool', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'PDO::sqliteCreateCollation' => ['bool', 'name'=>'string', 'callback'=>'callable'],
'PDO::sqliteCreateFunction' => ['bool', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'pdo_drivers' => ['array'],
'PDOException::getCode' => ['string'],
'PDOException::getFile' => ['string'],
'PDOException::getLine' => ['int'],
'PDOException::getMessage' => ['string'],
'PDOException::getPrevious' => ['?Throwable'],
'PDOException::getTrace' => ['list<array<string,mixed>>'],
'PDOException::getTraceAsString' => ['string'],
'PDOStatement::__sleep' => ['list<string>'],
'PDOStatement::__wakeup' => ['void'],
'PDOStatement::bindColumn' => ['bool', 'column'=>'mixed', '&rw_param'=>'mixed', 'type='=>'int', 'maxlen='=>'int', 'driverdata='=>'mixed'],
'PDOStatement::bindParam' => ['bool', 'paramno'=>'mixed', '&rw_param'=>'mixed', 'type='=>'int', 'maxlen='=>'int', 'driverdata='=>'mixed'],
'PDOStatement::bindValue' => ['bool', 'paramno'=>'mixed', 'param'=>'mixed', 'type='=>'int'],
'PDOStatement::closeCursor' => ['bool'],
'PDOStatement::columnCount' => ['int'],
'PDOStatement::debugDumpParams' => ['void'],
'PDOStatement::errorCode' => ['string'],
'PDOStatement::errorInfo' => ['array'],
'PDOStatement::execute' => ['bool', 'bound_input_params='=>'?array'],
'PDOStatement::fetch' => ['mixed', 'how='=>'int', 'orientation='=>'int', 'offset='=>'int'],
'PDOStatement::fetchAll' => ['array|false', 'how='=>'int', 'fetch_argument='=>'int|string|callable', 'ctor_args='=>'?array'],
'PDOStatement::fetchColumn' => ['string|int|float|bool|null', 'column_number='=>'int'],
'PDOStatement::fetchObject' => ['object|false', 'class_name='=>'string', 'ctor_args='=>'array'],
'PDOStatement::getAttribute' => ['mixed', 'attribute'=>'int'],
'PDOStatement::getColumnMeta' => ['array|false', 'column'=>'int'],
'PDOStatement::nextRowset' => ['bool'],
'PDOStatement::rowCount' => ['int'],
'PDOStatement::setAttribute' => ['bool', 'attribute'=>'int', 'value'=>'mixed'],
'PDOStatement::setFetchMode' => ['bool', 'mode'=>'int'],
'PDOStatement::setFetchMode\'1' => ['bool', 'fetch_column'=>'int', 'colno'=>'int'],
'PDOStatement::setFetchMode\'2' => ['bool', 'fetch_class'=>'int', 'classname'=>'string', 'ctorargs'=>'array'],
'PDOStatement::setFetchMode\'3' => ['bool', 'fetch_into'=>'int', 'object'=>'object'],
'pfsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float'],
'pg_affected_rows' => ['int', 'result'=>'resource'],
'pg_cancel_query' => ['bool', 'connection'=>'resource'],
'pg_client_encoding' => ['string|false', 'connection='=>'resource'],
'pg_close' => ['bool', 'connection='=>'resource'],
'pg_connect' => ['resource|false', 'connection_string'=>'string', 'flags='=>'int'],
'pg_connect_poll' => ['int', 'connection'=>'resource'],
'pg_connection_busy' => ['bool', 'connection'=>'resource'],
'pg_connection_reset' => ['bool', 'connection'=>'resource'],
'pg_connection_status' => ['int', 'connection'=>'resource'],
'pg_consume_input' => ['bool', 'connection'=>'resource'],
'pg_convert' => ['array', 'connection'=>'resource', 'table_name'=>'string', 'values'=>'array', 'flags='=>'int'],
'pg_copy_from' => ['bool', 'connection'=>'resource', 'table_name'=>'string', 'rows'=>'array', 'separator='=>'string', 'null_as='=>'string'],
'pg_copy_to' => ['array|false', 'connection'=>'resource', 'table_name'=>'string', 'separator='=>'string', 'null_as='=>'string'],
'pg_dbname' => ['string|false', 'connection='=>'resource'],
'pg_delete' => ['string|bool', 'connection'=>'resource', 'table_name'=>'string', 'conditions'=>'array', 'flags='=>'int'],
'pg_end_copy' => ['bool', 'connection='=>'resource'],
'pg_escape_bytea' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_bytea\'1' => ['string', 'connection'=>'string'],
'pg_escape_identifier' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_identifier\'1' => ['string', 'connection'=>'string'],
'pg_escape_literal' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_literal\'1' => ['string', 'connection'=>'string'],
'pg_escape_string' => ['string', 'connection'=>'resource', 'string'=>'string'],
'pg_escape_string\'1' => ['string', 'connection'=>'string'],
'pg_exec' => ['resource|false', 'connection'=>'resource', 'query'=>'string'],
'pg_execute' => ['resource|false', 'connection'=>'resource', 'statement_name'=>'string', 'params'=>'array'],
'pg_execute\'1' => ['resource|false', 'connection'=>'string', 'statement_name'=>'array'],
'pg_fetch_all' => ['array<array>|false', 'result'=>'resource', 'mode='=>'int'],
'pg_fetch_all_columns' => ['array|false', 'result'=>'resource', 'field='=>'int'],
'pg_fetch_array' => ['array<string|null>|false', 'result'=>'resource', 'row='=>'?int', 'mode='=>'int'],
'pg_fetch_assoc' => ['array<string, mixed>|false', 'result'=>'resource', 'row='=>'?int'],
'pg_fetch_object' => ['object', 'result'=>'resource', 'row='=>'?int', 'class='=>'int'],
'pg_fetch_object\'1' => ['object', 'result'=>'resource', 'row='=>'?int', 'class='=>'string', 'constructor_args='=>'array'],
'pg_fetch_result' => ['string', 'result'=>'resource', 'row'=>'string|int'],
'pg_fetch_result\'1' => ['string', 'result'=>'resource', 'row'=>'?int', 'field'=>'string|int'],
'pg_fetch_row' => ['array', 'result'=>'resource', 'row='=>'?int', 'mode='=>'int'],
'pg_field_is_null' => ['int', 'result'=>'resource', 'row'=>'string|int'],
'pg_field_is_null\'1' => ['int', 'result'=>'resource', 'row'=>'int', 'field'=>'string|int'],
'pg_field_name' => ['string|false', 'result'=>'resource', 'field'=>'int'],
'pg_field_num' => ['int', 'result'=>'resource', 'field'=>'string'],
'pg_field_prtlen' => ['int|false', 'result'=>'resource', 'row'=>''],
'pg_field_prtlen\'1' => ['int', 'result'=>'resource', 'row'=>'int', 'field'=>'string|int'],
'pg_field_size' => ['int', 'result'=>'resource', 'field'=>'int'],
'pg_field_table' => ['mixed|false', 'result'=>'resource', 'field'=>'int', 'oid_only='=>'bool'],
'pg_field_type' => ['string|false', 'result'=>'resource', 'field'=>'int'],
'pg_field_type_oid' => ['int|false', 'result'=>'resource', 'field'=>'int'],
'pg_flush' => ['mixed', 'connection'=>'resource'],
'pg_free_result' => ['bool', 'result'=>'resource'],
'pg_get_notify' => ['array|false', 'result'=>'resource', 'mode='=>'int'],
'pg_get_pid' => ['int|false', 'connection'=>'resource'],
'pg_get_result' => ['resource|false', 'connection='=>'resource'],
'pg_host' => ['string|false', 'connection='=>'resource'],
'pg_insert' => ['resource|string|false', 'connection'=>'resource', 'table_name'=>'string', 'values'=>'array', 'flags='=>'int'],
'pg_last_error' => ['string', 'connection='=>'resource', 'operation='=>'int'],
'pg_last_notice' => ['string|array|bool', 'connection'=>'resource', 'mode='=>'int'],
'pg_last_oid' => ['string', 'result'=>'resource'],
'pg_lo_close' => ['bool', 'lob'=>'resource'],
'pg_lo_create' => ['int|false', 'connection='=>'resource', 'oid='=>''],
'pg_lo_export' => ['bool', 'connection'=>'resource', 'oid'=>'int', 'filename'=>'string'],
'pg_lo_export\'1' => ['bool', 'connection'=>'int', 'oid'=>'string'],
'pg_lo_import' => ['int', 'connection'=>'resource', 'filename'=>'string', 'oid'=>''],
'pg_lo_import\'1' => ['int', 'connection'=>'string', 'filename'=>''],
'pg_lo_open' => ['resource|false', 'connection'=>'resource', 'oid'=>'int', 'mode'=>'string'],
'pg_lo_read' => ['string', 'lob'=>'resource', 'length='=>'int'],
'pg_lo_read_all' => ['int|false', 'lob'=>'resource'],
'pg_lo_seek' => ['bool', 'lob'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'pg_lo_tell' => ['int', 'lob'=>'resource'],
'pg_lo_truncate' => ['bool', 'lob'=>'resource', 'size'=>'int'],
'pg_lo_unlink' => ['bool', 'connection'=>'resource', 'oid'=>'int'],
'pg_lo_write' => ['int|false', 'lob'=>'resource', 'data'=>'string', 'length='=>'int'],
'pg_meta_data' => ['array', 'connection'=>'resource', 'table_name'=>'string', 'extended='=>'bool'],
'pg_num_fields' => ['int', 'result'=>'resource'],
'pg_num_rows' => ['int', 'result'=>'resource'],
'pg_options' => ['string', 'connection='=>'resource'],
'pg_parameter_status' => ['string|false', 'connection'=>'resource', 'name'=>'string'],
'pg_parameter_status\'1' => ['string|false', 'connection'=>'string'],
'pg_pconnect' => ['resource|false', 'connection_string'=>'string', 'flags='=>'string', 'port='=>'string|int', 'options='=>'string', 'tty='=>'string', 'database='=>'string'],
'pg_ping' => ['bool', 'connection='=>'resource'],
'pg_port' => ['int', 'connection='=>'resource'],
'pg_prepare' => ['resource|false', 'connection'=>'resource', 'statement_name'=>'string', 'query'=>'string'],
'pg_prepare\'1' => ['resource|false', 'connection'=>'string', 'statement_name'=>'string'],
'pg_put_line' => ['bool', 'connection'=>'resource', 'query'=>'string'],
'pg_put_line\'1' => ['bool', 'connection'=>'string'],
'pg_query' => ['resource|false', 'connection'=>'resource', 'query'=>'string'],
'pg_query\'1' => ['resource|false', 'connection'=>'string'],
'pg_query_params' => ['resource|false', 'connection'=>'resource', 'query'=>'string', 'params'=>'array'],
'pg_query_params\'1' => ['resource|false', 'connection'=>'string', 'query'=>'array'],
'pg_result_error' => ['string|false', 'result'=>'resource'],
'pg_result_error_field' => ['string|?false', 'result'=>'resource', 'field_code'=>'int'],
'pg_result_seek' => ['bool', 'result'=>'resource', 'row'=>'int'],
'pg_result_status' => ['mixed', 'result'=>'resource', 'mode='=>'int'],
'pg_select' => ['string|bool', 'connection'=>'resource', 'table_name'=>'string', 'conditions'=>'array', 'flags='=>'int', 'mode='=>'int'],
'pg_send_execute' => ['bool', 'connection'=>'resource', 'query'=>'string', 'params'=>'array'],
'pg_send_prepare' => ['bool', 'connection'=>'resource', 'statement_name'=>'string', 'query'=>'string'],
'pg_send_query' => ['bool', 'connection'=>'resource', 'query'=>'string'],
'pg_send_query_params' => ['bool', 'connection'=>'resource', 'query'=>'string', 'params'=>'array'],
'pg_set_client_encoding' => ['int', 'connection'=>'resource', 'encoding'=>'string'],
'pg_set_client_encoding\'1' => ['int', 'connection'=>'string'],
'pg_set_error_verbosity' => ['int', 'connection'=>'resource', 'verbosity'=>'int'],
'pg_set_error_verbosity\'1' => ['int', 'connection'=>'int'],
'pg_socket' => ['resource|false', 'connection'=>'resource'],
'pg_trace' => ['bool', 'filename'=>'string', 'mode='=>'string', 'connection='=>'resource'],
'pg_transaction_status' => ['int', 'connection'=>'resource'],
'pg_tty' => ['string', 'connection='=>'resource'],
'pg_tty\'1' => ['string'],
'pg_unescape_bytea' => ['string', 'string'=>'string'],
'pg_untrace' => ['bool', 'connection='=>'resource'],
'pg_untrace\'1' => ['bool'],
'pg_update' => ['mixed', 'connection'=>'resource', 'table_name'=>'string', 'values'=>'array', 'conditions'=>'array', 'flags='=>'int'],
'pg_version' => ['array', 'connection='=>'resource'],
'Phar::__construct' => ['void', 'fname'=>'string', 'flags='=>'int', 'alias='=>'string'],
'Phar::addEmptyDir' => ['void', 'dirname'=>'string'],
'Phar::addFile' => ['void', 'file'=>'string', 'localname='=>'string'],
'Phar::addFromString' => ['void', 'localname'=>'string', 'contents'=>'string'],
'Phar::apiVersion' => ['string'],
'Phar::buildFromDirectory' => ['array', 'base_dir'=>'string', 'regex='=>'string'],
'Phar::buildFromIterator' => ['array', 'iter'=>'Iterator', 'base_directory='=>'string'],
'Phar::canCompress' => ['bool', 'method='=>'int'],
'Phar::canWrite' => ['bool'],
'Phar::compress' => ['Phar', 'compression'=>'int', 'extension='=>'string'],
'Phar::compressAllFilesBZIP2' => ['bool'],
'Phar::compressAllFilesGZ' => ['bool'],
'Phar::compressFiles' => ['void', 'compression'=>'int'],
'Phar::convertToData' => ['PharData', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'Phar::convertToExecutable' => ['Phar', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'Phar::copy' => ['bool', 'oldfile'=>'string', 'newfile'=>'string'],
'Phar::count' => ['int'],
'Phar::createDefaultStub' => ['string', 'indexfile='=>'string', 'webindexfile='=>'string'],
'Phar::decompress' => ['Phar', 'extension='=>'string'],
'Phar::decompressFiles' => ['bool'],
'Phar::delete' => ['bool', 'entry'=>'string'],
'Phar::delMetadata' => ['bool'],
'Phar::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string|array|null', 'overwrite='=>'bool'],
'Phar::getAlias' => ['string'],
'Phar::getMetadata' => ['mixed'],
'Phar::getModified' => ['bool'],
'Phar::getPath' => ['string'],
'Phar::getSignature' => ['array{hash:string, hash_type:string}'],
'Phar::getStub' => ['string'],
'Phar::getSupportedCompression' => ['array'],
'Phar::getSupportedSignatures' => ['array'],
'Phar::getVersion' => ['string'],
'Phar::hasMetadata' => ['bool'],
'Phar::interceptFileFuncs' => ['void'],
'Phar::isBuffering' => ['bool'],
'Phar::isCompressed' => ['mixed|false'],
'Phar::isFileFormat' => ['bool', 'format'=>'int'],
'Phar::isValidPharFilename' => ['bool', 'filename'=>'string', 'executable='=>'bool'],
'Phar::isWritable' => ['bool'],
'Phar::loadPhar' => ['bool', 'filename'=>'string', 'alias='=>'string'],
'Phar::mapPhar' => ['bool', 'alias='=>'string', 'dataoffset='=>'int'],
'Phar::mount' => ['void', 'pharpath'=>'string', 'externalpath'=>'string'],
'Phar::mungServer' => ['void', 'munglist'=>'array'],
'Phar::offsetExists' => ['bool', 'offset'=>'string'],
'Phar::offsetGet' => ['PharFileInfo', 'offset'=>'string'],
'Phar::offsetSet' => ['void', 'offset'=>'string', 'value'=>'string'],
'Phar::offsetUnset' => ['bool', 'offset'=>'string'],
'Phar::running' => ['string', 'retphar='=>'bool'],
'Phar::setAlias' => ['bool', 'alias'=>'string'],
'Phar::setDefaultStub' => ['bool', 'index='=>'string', 'webindex='=>'string'],
'Phar::setMetadata' => ['void', 'metadata'=>''],
'Phar::setSignatureAlgorithm' => ['void', 'sigtype'=>'int', 'privatekey='=>'string'],
'Phar::setStub' => ['bool', 'stub'=>'string', 'length='=>'int'],
'Phar::startBuffering' => ['void'],
'Phar::stopBuffering' => ['void'],
'Phar::uncompressAllFiles' => ['bool'],
'Phar::unlinkArchive' => ['bool', 'archive'=>'string'],
'Phar::webPhar' => ['', 'alias='=>'string', 'index='=>'string', 'f404='=>'string', 'mimetypes='=>'array', 'rewrites='=>'array'],
'PharData::__construct' => ['void', 'fname'=>'string', 'flags='=>'?int', 'alias='=>'?string', 'format='=>'int'],
'PharData::addEmptyDir' => ['bool', 'dirname'=>'string'],
'PharData::addFile' => ['void', 'file'=>'string', 'localname='=>'string'],
'PharData::addFromString' => ['bool', 'localname'=>'string', 'contents'=>'string'],
'PharData::buildFromDirectory' => ['array', 'base_dir'=>'string', 'regex='=>'string'],
'PharData::buildFromIterator' => ['array', 'iter'=>'Iterator', 'base_directory='=>'string'],
'PharData::compress' => ['PharData', 'compression'=>'int', 'extension='=>'string'],
'PharData::compressFiles' => ['bool', 'compression'=>'int'],
'PharData::convertToData' => ['PharData', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'PharData::convertToExecutable' => ['Phar', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'PharData::copy' => ['bool', 'oldfile'=>'string', 'newfile'=>'string'],
'PharData::decompress' => ['PharData', 'extension='=>'string'],
'PharData::decompressFiles' => ['bool'],
'PharData::delete' => ['bool', 'entry'=>'string'],
'PharData::delMetadata' => ['bool'],
'PharData::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string|array|null', 'overwrite='=>'bool'],
'PharData::isWritable' => ['bool'],
'PharData::offsetExists' => ['bool', 'offset'=>'string'],
'PharData::offsetGet' => ['PharFileInfo', 'offset'=>'string'],
'PharData::offsetSet' => ['void', 'offset'=>'string', 'value'=>'string'],
'PharData::offsetUnset' => ['bool', 'offset'=>'string'],
'PharData::setAlias' => ['bool', 'alias'=>'string'],
'PharData::setDefaultStub' => ['bool', 'index='=>'string', 'webindex='=>'string'],
'phardata::setMetadata' => ['void', 'metadata'=>'mixed'],
'phardata::setSignatureAlgorithm' => ['void', 'sigtype'=>'int'],
'PharData::setStub' => ['bool', 'stub'=>'string', 'length='=>'int'],
'PharFileInfo::__construct' => ['void', 'entry'=>'string'],
'PharFileInfo::chmod' => ['void', 'permissions'=>'int'],
'PharFileInfo::compress' => ['bool', 'compression'=>'int'],
'PharFileInfo::decompress' => ['bool'],
'PharFileInfo::delMetadata' => ['bool'],
'PharFileInfo::getCompressedSize' => ['int'],
'PharFileInfo::getContent' => ['string'],
'PharFileInfo::getCRC32' => ['int'],
'PharFileInfo::getMetadata' => ['mixed'],
'PharFileInfo::getPharFlags' => ['int'],
'PharFileInfo::hasMetadata' => ['bool'],
'PharFileInfo::isCompressed' => ['bool', 'compression_type='=>'int'],
'PharFileInfo::isCompressedBZIP2' => ['bool'],
'PharFileInfo::isCompressedGZ' => ['bool'],
'PharFileInfo::isCRCChecked' => ['bool'],
'PharFileInfo::setCompressedBZIP2' => ['bool'],
'PharFileInfo::setCompressedGZ' => ['bool'],
'PharFileInfo::setMetadata' => ['void', 'metadata'=>'mixed'],
'PharFileInfo::setUncompressed' => ['bool'],
'phdfs::__construct' => ['void', 'ip'=>'string', 'port'=>'string'],
'phdfs::__destruct' => ['void'],
'phdfs::connect' => ['bool'],
'phdfs::copy' => ['bool', 'source_file'=>'string', 'destination_file'=>'string'],
'phdfs::create_directory' => ['bool', 'path'=>'string'],
'phdfs::delete' => ['bool', 'path'=>'string'],
'phdfs::disconnect' => ['bool'],
'phdfs::exists' => ['bool', 'path'=>'string'],
'phdfs::file_info' => ['array', 'path'=>'string'],
'phdfs::list_directory' => ['array', 'path'=>'string'],
'phdfs::read' => ['string', 'path'=>'string', 'length='=>'string'],
'phdfs::rename' => ['bool', 'old_path'=>'string', 'new_path'=>'string'],
'phdfs::tell' => ['int', 'path'=>'string'],
'phdfs::write' => ['bool', 'path'=>'string', 'buffer'=>'string', 'mode='=>'string'],
'php_check_syntax' => ['bool', 'filename'=>'string', 'error_message='=>'string'],
'php_ini_loaded_file' => ['string|false'],
'php_ini_scanned_files' => ['string|false'],
'php_logo_guid' => ['string'],
'php_sapi_name' => ['string'],
'php_strip_whitespace' => ['string', 'filename'=>'string'],
'php_uname' => ['string', 'mode='=>'string'],
'php_user_filter::filter' => ['int', 'in'=>'resource', 'out'=>'resource', '&rw_consumed'=>'int', 'closing'=>'bool'],
'php_user_filter::onClose' => ['void'],
'php_user_filter::onCreate' => ['bool'],
'phpcredits' => ['bool', 'flags='=>'int'],
'phpdbg_break_file' => ['void', 'file'=>'string', 'line'=>'int'],
'phpdbg_break_function' => ['void', 'function'=>'string'],
'phpdbg_break_method' => ['void', 'class'=>'string', 'method'=>'string'],
'phpdbg_break_next' => ['void'],
'phpdbg_clear' => ['void'],
'phpdbg_color' => ['void', 'element'=>'int', 'color'=>'string'],
'phpdbg_end_oplog' => ['array', 'options='=>'array'],
'phpdbg_exec' => ['mixed', 'context='=>'string'],
'phpdbg_get_executable' => ['array', 'options='=>'array'],
'phpdbg_prompt' => ['void', 'string'=>'string'],
'phpdbg_start_oplog' => ['void'],
'phpinfo' => ['bool', 'flags='=>'int'],
'phpversion' => ['string|false', 'extension='=>'string'],
'pht\AtomicInteger::__construct' => ['void', 'value='=>'int'],
'pht\AtomicInteger::dec' => ['void'],
'pht\AtomicInteger::get' => ['int'],
'pht\AtomicInteger::inc' => ['void'],
'pht\AtomicInteger::lock' => ['void'],
'pht\AtomicInteger::set' => ['void', 'value'=>'int'],
'pht\AtomicInteger::unlock' => ['void'],
'pht\HashTable::lock' => ['void'],
'pht\HashTable::size' => ['int'],
'pht\HashTable::unlock' => ['void'],
'pht\Queue::front' => ['mixed'],
'pht\Queue::lock' => ['void'],
'pht\Queue::pop' => ['mixed'],
'pht\Queue::push' => ['void', 'value'=>'mixed'],
'pht\Queue::size' => ['int'],
'pht\Queue::unlock' => ['void'],
'pht\Runnable::run' => ['void'],
'pht\thread::addClassTask' => ['void', 'className'=>'string', '...ctorArgs='=>'mixed'],
'pht\thread::addFileTask' => ['void', 'fileName'=>'string', '...globals='=>'mixed'],
'pht\thread::addFunctionTask' => ['void', 'func'=>'callable', '...funcArgs='=>'mixed'],
'pht\thread::join' => ['void'],
'pht\thread::start' => ['void'],
'pht\thread::taskCount' => ['int'],
'pht\threaded::lock' => ['void'],
'pht\threaded::unlock' => ['void'],
'pht\Vector::__construct' => ['void', 'size='=>'int', 'value='=>'mixed'],
'pht\Vector::deleteAt' => ['void', 'offset'=>'int'],
'pht\Vector::insertAt' => ['void', 'value'=>'mixed', 'offset'=>'int'],
'pht\Vector::lock' => ['void'],
'pht\Vector::pop' => ['mixed'],
'pht\Vector::push' => ['void', 'value'=>'mixed'],
'pht\Vector::resize' => ['void', 'size'=>'int', 'value='=>'mixed'],
'pht\Vector::shift' => ['mixed'],
'pht\Vector::size' => ['int'],
'pht\Vector::unlock' => ['void'],
'pht\Vector::unshift' => ['void', 'value'=>'mixed'],
'pht\Vector::updateAt' => ['void', 'value'=>'mixed', 'offset'=>'int'],
'pi' => ['float'],
'png2wbmp' => ['bool', 'pngname'=>'string', 'wbmpname'=>'string', 'dest_height'=>'int', 'dest_width'=>'int', 'threshold'=>'int'],
'pointObj::__construct' => ['void'],
'pointObj::distanceToLine' => ['float', 'p1'=>'pointObj', 'p2'=>'pointObj'],
'pointObj::distanceToPoint' => ['float', 'poPoint'=>'pointObj'],
'pointObj::distanceToShape' => ['float', 'shape'=>'shapeObj'],
'pointObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj', 'class_index'=>'int', 'text'=>'string'],
'pointObj::ms_newPointObj' => ['pointObj'],
'pointObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'pointObj::setXY' => ['int', 'x'=>'float', 'y'=>'float', 'm'=>'float'],
'pointObj::setXYZ' => ['int', 'x'=>'float', 'y'=>'float', 'z'=>'float', 'm'=>'float'],
'Pool::__construct' => ['void', 'size'=>'int', 'class'=>'string', 'ctor='=>'array'],
'Pool::collect' => ['int', 'collector='=>'Callable'],
'Pool::resize' => ['void', 'size'=>'int'],
'Pool::shutdown' => ['void'],
'Pool::submit' => ['int', 'task'=>'Threaded'],
'Pool::submitTo' => ['int', 'worker'=>'int', 'task'=>'Threaded'],
'popen' => ['resource|false', 'command'=>'string', 'mode'=>'string'],
'pos' => ['mixed', 'array'=>'array'],
'posix_access' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'posix_ctermid' => ['string|false'],
'posix_errno' => ['int'],
'posix_get_last_error' => ['int'],
'posix_getcwd' => ['string'],
'posix_getegid' => ['int'],
'posix_geteuid' => ['int'],
'posix_getgid' => ['int'],
'posix_getgrgid' => ['array', 'group_id'=>'int'],
'posix_getgrnam' => ['array|false', 'name'=>'string'],
'posix_getgroups' => ['array'],
'posix_getlogin' => ['string'],
'posix_getpgid' => ['int|false', 'process_id'=>'int'],
'posix_getpgrp' => ['int'],
'posix_getpid' => ['int'],
'posix_getppid' => ['int'],
'posix_getpwnam' => ['array|false', 'username'=>'string'],
'posix_getpwuid' => ['array', 'user_id'=>'int'],
'posix_getrlimit' => ['array'],
'posix_getsid' => ['int', 'process_id'=>'int'],
'posix_getuid' => ['int'],
'posix_initgroups' => ['bool', 'username'=>'string', 'group_id'=>'int'],
'posix_isatty' => ['bool', 'file_descriptor'=>'resource|int'],
'posix_kill' => ['bool', 'process_id'=>'int', 'signal'=>'int'],
'posix_mkfifo' => ['bool', 'filename'=>'string', 'permissions'=>'int'],
'posix_mknod' => ['bool', 'filename'=>'string', 'flags'=>'int', 'major='=>'int', 'minor='=>'int'],
'posix_setegid' => ['bool', 'group_id'=>'int'],
'posix_seteuid' => ['bool', 'user_id'=>'int'],
'posix_setgid' => ['bool', 'group_id'=>'int'],
'posix_setpgid' => ['bool', 'process_id'=>'int', 'process_group_id'=>'int'],
'posix_setrlimit' => ['bool', 'resource'=>'int', 'soft_limit'=>'int', 'hard_limit'=>'int'],
'posix_setsid' => ['int'],
'posix_setuid' => ['bool', 'user_id'=>'int'],
'posix_strerror' => ['string', 'error_code'=>'int'],
'posix_times' => ['array'],
'posix_ttyname' => ['string|false', 'file_descriptor'=>'resource|int'],
'posix_uname' => ['array'],
'Postal\Expand::expand_address' => ['string[]', 'address'=>'string', 'options='=>'array<string, mixed>'],
'Postal\Parser::parse_address' => ['array<string,string>', 'address'=>'string', 'options='=>'array<string, string>'],
'pow' => ['float|int', 'num'=>'int|float', 'exponent'=>'int|float'],
'preg_filter' => ['null|string|string[]', 'pattern'=>'mixed', 'replacement'=>'mixed', 'subject'=>'mixed', 'limit='=>'int', '&w_count='=>'int'],
'preg_grep' => ['array|false', 'pattern'=>'string', 'array'=>'array', 'flags='=>'int'],
'preg_last_error' => ['int'],
'preg_match' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'string[]', 'flags='=>'0|', 'offset='=>'int'],
'preg_match\'1' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_match_all' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_quote' => ['string', 'str'=>'string', 'delimiter='=>'string'],
'preg_replace' => ['string|string[]|null', 'pattern'=>'string|array', 'replacement'=>'string|array', 'subject'=>'string|array', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback' => ['string|null', 'pattern'=>'string|array', 'callback'=>'callable(array<int, string>):string', 'subject'=>'string', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback\'1' => ['string[]|null', 'pattern'=>'string|array', 'callback'=>'callable(array<int, string>):string', 'subject'=>'string[]', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback_array' => ['string|string[]|null', 'pattern'=>'array<string,callable(array):string>', 'subject'=>'string|array', 'limit='=>'int', '&w_count='=>'int'],
'preg_split' => ['list<string>|false', 'pattern'=>'string', 'subject'=>'string', 'limit'=>'int', 'flags='=>'null'],
'preg_split\'1' => ['list<string>|list<list<string|int>>|false', 'pattern'=>'string', 'subject'=>'string', 'limit='=>'int', 'flags='=>'int'],
'prev' => ['mixed', '&r_array'=>'array|object'],
'print' => ['int', 'arg'=>'string'],
'print_r' => ['string', 'value'=>'mixed'],
'print_r\'1' => ['true', 'value'=>'mixed', 'return='=>'bool'],
'printf' => ['int', 'format'=>'string', '...values='=>'string|int|float'],
'proc_close' => ['int', 'process'=>'resource'],
'proc_get_status' => ['array{command: string, pid: int, running: bool, signaled: bool, stopped: bool, exitcode: int, termsig: int, stopsig: int}|false', 'process'=>'resource'],
'proc_nice' => ['bool', 'priority'=>'int'],
'proc_open' => ['resource|false', 'command'=>'string|array', 'descriptor_spec'=>'array', '&w_pipes'=>'resource[]', 'cwd='=>'?string', 'env_vars='=>'?array', 'options='=>'array'],
'proc_terminate' => ['bool', 'process'=>'resource', 'signal='=>'int'],
'projectionObj::__construct' => ['void', 'projectionString'=>'string'],
'projectionObj::getUnits' => ['int'],
'projectionObj::ms_newProjectionObj' => ['projectionObj', 'projectionString'=>'string'],
'property_exists' => ['bool', 'object_or_class'=>'object|string', 'property'=>'string'],
'ps_add_bookmark' => ['int', 'psdoc'=>'resource', 'text'=>'string', 'parent='=>'int', 'open='=>'int'],
'ps_add_launchlink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'ps_add_locallink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'page'=>'int', 'dest'=>'string'],
'ps_add_note' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'ps_add_pdflink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'ps_add_weblink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'url'=>'string'],
'ps_arc' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'ps_arcn' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'ps_begin_page' => ['bool', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'ps_begin_pattern' => ['int', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'ps_begin_template' => ['int', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'ps_circle' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float'],
'ps_clip' => ['bool', 'psdoc'=>'resource'],
'ps_close' => ['bool', 'psdoc'=>'resource'],
'ps_close_image' => ['void', 'psdoc'=>'resource', 'imageid'=>'int'],
'ps_closepath' => ['bool', 'psdoc'=>'resource'],
'ps_closepath_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_continue_text' => ['bool', 'psdoc'=>'resource', 'text'=>'string'],
'ps_curveto' => ['bool', 'psdoc'=>'resource', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'ps_delete' => ['bool', 'psdoc'=>'resource'],
'ps_end_page' => ['bool', 'psdoc'=>'resource'],
'ps_end_pattern' => ['bool', 'psdoc'=>'resource'],
'ps_end_template' => ['bool', 'psdoc'=>'resource'],
'ps_fill' => ['bool', 'psdoc'=>'resource'],
'ps_fill_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_findfont' => ['int', 'psdoc'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'embed='=>'bool'],
'ps_get_buffer' => ['string', 'psdoc'=>'resource'],
'ps_get_parameter' => ['string', 'psdoc'=>'resource', 'name'=>'string', 'modifier='=>'float'],
'ps_get_value' => ['float', 'psdoc'=>'resource', 'name'=>'string', 'modifier='=>'float'],
'ps_hyphenate' => ['array', 'psdoc'=>'resource', 'text'=>'string'],
'ps_include_file' => ['bool', 'psdoc'=>'resource', 'file'=>'string'],
'ps_lineto' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_makespotcolor' => ['int', 'psdoc'=>'resource', 'name'=>'string', 'reserved='=>'int'],
'ps_moveto' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_new' => ['resource'],
'ps_open_file' => ['bool', 'psdoc'=>'resource', 'filename='=>'string'],
'ps_open_image' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'ps_open_image_file' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'filename'=>'string', 'stringparam='=>'string', 'intparam='=>'int'],
'ps_open_memory_image' => ['int', 'psdoc'=>'resource', 'gd'=>'int'],
'ps_place_image' => ['bool', 'psdoc'=>'resource', 'imageid'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'ps_rect' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'ps_restore' => ['bool', 'psdoc'=>'resource'],
'ps_rotate' => ['bool', 'psdoc'=>'resource', 'rot'=>'float'],
'ps_save' => ['bool', 'psdoc'=>'resource'],
'ps_scale' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_set_border_color' => ['bool', 'psdoc'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'ps_set_border_dash' => ['bool', 'psdoc'=>'resource', 'black'=>'float', 'white'=>'float'],
'ps_set_border_style' => ['bool', 'psdoc'=>'resource', 'style'=>'string', 'width'=>'float'],
'ps_set_info' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'ps_set_parameter' => ['bool', 'psdoc'=>'resource', 'name'=>'string', 'value'=>'string'],
'ps_set_text_pos' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_set_value' => ['bool', 'psdoc'=>'resource', 'name'=>'string', 'value'=>'float'],
'ps_setcolor' => ['bool', 'psdoc'=>'resource', 'type'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'ps_setdash' => ['bool', 'psdoc'=>'resource', 'on'=>'float', 'off'=>'float'],
'ps_setflat' => ['bool', 'psdoc'=>'resource', 'value'=>'float'],
'ps_setfont' => ['bool', 'psdoc'=>'resource', 'fontid'=>'int', 'size'=>'float'],
'ps_setgray' => ['bool', 'psdoc'=>'resource', 'gray'=>'float'],
'ps_setlinecap' => ['bool', 'psdoc'=>'resource', 'type'=>'int'],
'ps_setlinejoin' => ['bool', 'psdoc'=>'resource', 'type'=>'int'],
'ps_setlinewidth' => ['bool', 'psdoc'=>'resource', 'width'=>'float'],
'ps_setmiterlimit' => ['bool', 'psdoc'=>'resource', 'value'=>'float'],
'ps_setoverprintmode' => ['bool', 'psdoc'=>'resource', 'mode'=>'int'],
'ps_setpolydash' => ['bool', 'psdoc'=>'resource', 'arr'=>'float'],
'ps_shading' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'ps_shading_pattern' => ['int', 'psdoc'=>'resource', 'shadingid'=>'int', 'optlist'=>'string'],
'ps_shfill' => ['bool', 'psdoc'=>'resource', 'shadingid'=>'int'],
'ps_show' => ['bool', 'psdoc'=>'resource', 'text'=>'string'],
'ps_show2' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'length'=>'int'],
'ps_show_boxed' => ['int', 'psdoc'=>'resource', 'text'=>'string', 'left'=>'float', 'bottom'=>'float', 'width'=>'float', 'height'=>'float', 'hmode'=>'string', 'feature='=>'string'],
'ps_show_xy' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'ps_show_xy2' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'length'=>'int', 'xcoor'=>'float', 'ycoor'=>'float'],
'ps_string_geometry' => ['array', 'psdoc'=>'resource', 'text'=>'string', 'fontid='=>'int', 'size='=>'float'],
'ps_stringwidth' => ['float', 'psdoc'=>'resource', 'text'=>'string', 'fontid='=>'int', 'size='=>'float'],
'ps_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_symbol' => ['bool', 'psdoc'=>'resource', 'ord'=>'int'],
'ps_symbol_name' => ['string', 'psdoc'=>'resource', 'ord'=>'int', 'fontid='=>'int'],
'ps_symbol_width' => ['float', 'psdoc'=>'resource', 'ord'=>'int', 'fontid='=>'int', 'size='=>'float'],
'ps_translate' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'pspell_add_to_personal' => ['bool', 'dictionary'=>'int', 'word'=>'string'],
'pspell_add_to_session' => ['bool', 'dictionary'=>'int', 'word'=>'string'],
'pspell_check' => ['bool', 'dictionary'=>'int', 'word'=>'string'],
'pspell_clear_session' => ['bool', 'dictionary'=>'int'],
'pspell_config_create' => ['int|false', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string'],
'pspell_config_data_dir' => ['bool', 'config'=>'int', 'directory'=>'string'],
'pspell_config_dict_dir' => ['bool', 'config'=>'int', 'directory'=>'string'],
'pspell_config_ignore' => ['bool', 'config'=>'int', 'min_length'=>'int'],
'pspell_config_mode' => ['bool', 'config'=>'int', 'mode'=>'int'],
'pspell_config_personal' => ['bool', 'config'=>'int', 'filename'=>'string'],
'pspell_config_repl' => ['bool', 'config'=>'int', 'filename'=>'string'],
'pspell_config_runtogether' => ['bool', 'config'=>'int', 'allow'=>'bool'],
'pspell_config_save_repl' => ['bool', 'config'=>'int', 'save'=>'bool'],
'pspell_new' => ['int|false', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string', 'mode='=>'int'],
'pspell_new_config' => ['int|false', 'config'=>'int'],
'pspell_new_personal' => ['int|false', 'filename'=>'string', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string', 'mode='=>'int'],
'pspell_save_wordlist' => ['bool', 'dictionary'=>'int'],
'pspell_store_replacement' => ['bool', 'dictionary'=>'int', 'misspelled'=>'string', 'correct'=>'string'],
'pspell_suggest' => ['array', 'dictionary'=>'int', 'word'=>'string'],
'putenv' => ['bool', 'assignment'=>'string'],
'px_close' => ['bool', 'pxdoc'=>'resource'],
'px_create_fp' => ['bool', 'pxdoc'=>'resource', 'file'=>'resource', 'fielddesc'=>'array'],
'px_date2string' => ['string', 'pxdoc'=>'resource', 'value'=>'int', 'format'=>'string'],
'px_delete' => ['bool', 'pxdoc'=>'resource'],
'px_delete_record' => ['bool', 'pxdoc'=>'resource', 'num'=>'int'],
'px_get_field' => ['array', 'pxdoc'=>'resource', 'fieldno'=>'int'],
'px_get_info' => ['array', 'pxdoc'=>'resource'],
'px_get_parameter' => ['string', 'pxdoc'=>'resource', 'name'=>'string'],
'px_get_record' => ['array', 'pxdoc'=>'resource', 'num'=>'int', 'mode='=>'int'],
'px_get_schema' => ['array', 'pxdoc'=>'resource', 'mode='=>'int'],
'px_get_value' => ['float', 'pxdoc'=>'resource', 'name'=>'string'],
'px_insert_record' => ['int', 'pxdoc'=>'resource', 'data'=>'array'],
'px_new' => ['resource'],
'px_numfields' => ['int', 'pxdoc'=>'resource'],
'px_numrecords' => ['int', 'pxdoc'=>'resource'],
'px_open_fp' => ['bool', 'pxdoc'=>'resource', 'file'=>'resource'],
'px_put_record' => ['bool', 'pxdoc'=>'resource', 'record'=>'array', 'recpos='=>'int'],
'px_retrieve_record' => ['array', 'pxdoc'=>'resource', 'num'=>'int', 'mode='=>'int'],
'px_set_blob_file' => ['bool', 'pxdoc'=>'resource', 'filename'=>'string'],
'px_set_parameter' => ['bool', 'pxdoc'=>'resource', 'name'=>'string', 'value'=>'string'],
'px_set_tablename' => ['void', 'pxdoc'=>'resource', 'name'=>'string'],
'px_set_targetencoding' => ['bool', 'pxdoc'=>'resource', 'encoding'=>'string'],
'px_set_value' => ['bool', 'pxdoc'=>'resource', 'name'=>'string', 'value'=>'float'],
'px_timestamp2string' => ['string', 'pxdoc'=>'resource', 'value'=>'float', 'format'=>'string'],
'px_update_record' => ['bool', 'pxdoc'=>'resource', 'data'=>'array', 'num'=>'int'],
'qdom_error' => ['string'],
'qdom_tree' => ['QDomDocument', 'doc'=>'string'],
'querymapObj::convertToString' => ['string'],
'querymapObj::free' => ['void'],
'querymapObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'querymapObj::updateFromString' => ['int', 'snippet'=>'string'],
'QuickHashIntHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntHash::add' => ['bool', 'key'=>'int', 'value='=>'int'],
'QuickHashIntHash::delete' => ['bool', 'key'=>'int'],
'QuickHashIntHash::exists' => ['bool', 'key'=>'int'],
'QuickHashIntHash::get' => ['int', 'key'=>'int'],
'QuickHashIntHash::getSize' => ['int'],
'QuickHashIntHash::loadFromFile' => ['QuickHashIntHash', 'filename'=>'string', 'options='=>'int'],
'QuickHashIntHash::loadFromString' => ['QuickHashIntHash', 'contents'=>'string', 'options='=>'int'],
'QuickHashIntHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntHash::saveToString' => ['string'],
'QuickHashIntHash::set' => ['bool', 'key'=>'int', 'value'=>'int'],
'QuickHashIntHash::update' => ['bool', 'key'=>'int', 'value'=>'int'],
'QuickHashIntSet::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntSet::add' => ['bool', 'key'=>'int'],
'QuickHashIntSet::delete' => ['bool', 'key'=>'int'],
'QuickHashIntSet::exists' => ['bool', 'key'=>'int'],
'QuickHashIntSet::getSize' => ['int'],
'QuickHashIntSet::loadFromFile' => ['QuickHashIntSet', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntSet::loadFromString' => ['QuickHashIntSet', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntSet::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntSet::saveToString' => ['string'],
'QuickHashIntStringHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntStringHash::add' => ['bool', 'key'=>'int', 'value'=>'string'],
'QuickHashIntStringHash::delete' => ['bool', 'key'=>'int'],
'QuickHashIntStringHash::exists' => ['bool', 'key'=>'int'],
'QuickHashIntStringHash::get' => ['mixed', 'key'=>'int'],
'QuickHashIntStringHash::getSize' => ['int'],
'QuickHashIntStringHash::loadFromFile' => ['QuickHashIntStringHash', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntStringHash::loadFromString' => ['QuickHashIntStringHash', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntStringHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntStringHash::saveToString' => ['string'],
'QuickHashIntStringHash::set' => ['int', 'key'=>'int', 'value'=>'string'],
'QuickHashIntStringHash::update' => ['bool', 'key'=>'int', 'value'=>'string'],
'QuickHashStringIntHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashStringIntHash::add' => ['bool', 'key'=>'string', 'value'=>'int'],
'QuickHashStringIntHash::delete' => ['bool', 'key'=>'string'],
'QuickHashStringIntHash::exists' => ['bool', 'key'=>'string'],
'QuickHashStringIntHash::get' => ['mixed', 'key'=>'string'],
'QuickHashStringIntHash::getSize' => ['int'],
'QuickHashStringIntHash::loadFromFile' => ['QuickHashStringIntHash', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashStringIntHash::loadFromString' => ['QuickHashStringIntHash', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashStringIntHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashStringIntHash::saveToString' => ['string'],
'QuickHashStringIntHash::set' => ['int', 'key'=>'string', 'value'=>'int'],
'QuickHashStringIntHash::update' => ['bool', 'key'=>'string', 'value'=>'int'],
'quoted_printable_decode' => ['string', 'string'=>'string'],
'quoted_printable_encode' => ['string', 'string'=>'string'],
'quotemeta' => ['string', 'string'=>'string'],
'rad2deg' => ['float', 'num'=>'float'],
'radius_acct_open' => ['resource|false'],
'radius_add_server' => ['bool', 'radius_handle'=>'resource', 'hostname'=>'string', 'port'=>'int', 'secret'=>'string', 'timeout'=>'int', 'max_tries'=>'int'],
'radius_auth_open' => ['resource|false'],
'radius_close' => ['bool', 'radius_handle'=>'resource'],
'radius_config' => ['bool', 'radius_handle'=>'resource', 'file'=>'string'],
'radius_create_request' => ['bool', 'radius_handle'=>'resource', 'type'=>'int'],
'radius_cvt_addr' => ['string', 'data'=>'string'],
'radius_cvt_int' => ['int', 'data'=>'string'],
'radius_cvt_string' => ['string', 'data'=>'string'],
'radius_demangle' => ['string', 'radius_handle'=>'resource', 'mangled'=>'string'],
'radius_demangle_mppe_key' => ['string', 'radius_handle'=>'resource', 'mangled'=>'string'],
'radius_get_attr' => ['mixed', 'radius_handle'=>'resource'],
'radius_get_tagged_attr_data' => ['string', 'data'=>'string'],
'radius_get_tagged_attr_tag' => ['int', 'data'=>'string'],
'radius_get_vendor_attr' => ['array', 'data'=>'string'],
'radius_put_addr' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'addr'=>'string'],
'radius_put_attr' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'string'],
'radius_put_int' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'int'],
'radius_put_string' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'string'],
'radius_put_vendor_addr' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'addr'=>'string'],
'radius_put_vendor_attr' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'string'],
'radius_put_vendor_int' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'int'],
'radius_put_vendor_string' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'string'],
'radius_request_authenticator' => ['string', 'radius_handle'=>'resource'],
'radius_salt_encrypt_attr' => ['string', 'radius_handle'=>'resource', 'data'=>'string'],
'radius_send_request' => ['int', 'radius_handle'=>'resource'],
'radius_server_secret' => ['string', 'radius_handle'=>'resource'],
'radius_strerror' => ['string', 'radius_handle'=>'resource'],
'rand' => ['int', 'min'=>'int', 'max'=>'int'],
'rand\'1' => ['int'],
'random_bytes' => ['string', 'length'=>'int'],
'random_int' => ['int', 'min'=>'int', 'max'=>'int'],
'range' => ['array', 'start'=>'mixed', 'end'=>'mixed', 'step='=>'int|float'],
'RangeException::__clone' => ['void'],
'RangeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?RangeException'],
'RangeException::__toString' => ['string'],
'RangeException::getCode' => ['int'],
'RangeException::getFile' => ['string'],
'RangeException::getLine' => ['int'],
'RangeException::getMessage' => ['string'],
'RangeException::getPrevious' => ['Throwable|RangeException|null'],
'RangeException::getTrace' => ['list<array<string,mixed>>'],
'RangeException::getTraceAsString' => ['string'],
'rar_allow_broken_set' => ['bool', 'rarfile'=>'RarArchive', 'allow_broken'=>'bool'],
'rar_broken_is' => ['bool', 'rarfile'=>'rararchive'],
'rar_close' => ['bool', 'rarfile'=>'rararchive'],
'rar_comment_get' => ['string', 'rarfile'=>'rararchive'],
'rar_entry_get' => ['RarEntry', 'rarfile'=>'RarArchive', 'entryname'=>'string'],
'rar_list' => ['RarArchive', 'rarfile'=>'rararchive'],
'rar_open' => ['RarArchive', 'filename'=>'string', 'password='=>'string', 'volume_callback='=>'callable'],
'rar_solid_is' => ['bool', 'rarfile'=>'rararchive'],
'rar_wrapper_cache_stats' => ['string'],
'RarArchive::__toString' => ['string'],
'RarArchive::close' => ['bool'],
'RarArchive::getComment' => ['string|null'],
'RarArchive::getEntries' => ['RarEntry[]|false'],
'RarArchive::getEntry' => ['RarEntry|false', 'entryname'=>'string'],
'RarArchive::isBroken' => ['bool'],
'RarArchive::isSolid' => ['bool'],
'RarArchive::open' => ['RarArchive|false', 'filename'=>'string', 'password='=>'string', 'volume_callback='=>'callable'],
'RarArchive::setAllowBroken' => ['bool', 'allow_broken'=>'bool'],
'RarEntry::__toString' => ['string'],
'RarEntry::extract' => ['bool', 'dir'=>'string', 'filepath='=>'string', 'password='=>'string', 'extended_data='=>'bool'],
'RarEntry::getAttr' => ['int|false'],
'RarEntry::getCrc' => ['string|false'],
'RarEntry::getFileTime' => ['string|false'],
'RarEntry::getHostOs' => ['int|false'],
'RarEntry::getMethod' => ['int|false'],
'RarEntry::getName' => ['string|false'],
'RarEntry::getPackedSize' => ['int|false'],
'RarEntry::getStream' => ['resource|false', 'password='=>'string'],
'RarEntry::getUnpackedSize' => ['int|false'],
'RarEntry::getVersion' => ['int|false'],
'RarEntry::isDirectory' => ['bool'],
'RarEntry::isEncrypted' => ['bool'],
'RarException::getCode' => ['int'],
'RarException::getFile' => ['string'],
'RarException::getLine' => ['int'],
'RarException::getMessage' => ['string'],
'RarException::getPrevious' => ['Exception|Throwable'],
'RarException::getTrace' => ['list<array<string,mixed>>'],
'RarException::getTraceAsString' => ['string'],
'RarException::isUsingExceptions' => ['bool'],
'RarException::setUsingExceptions' => ['RarEntry', 'using_exceptions'=>'bool'],
'rawurldecode' => ['string', 'string'=>'string'],
'rawurlencode' => ['string', 'string'=>'string'],
'rd_kafka_err2str' => ['string', 'err'=>'int'],
'rd_kafka_errno' => ['int'],
'rd_kafka_errno2err' => ['int', 'errnox'=>'int'],
'rd_kafka_offset_tail' => ['int', 'cnt'=>'int'],
'RdKafka::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka::flush' => ['int', 'timeout_ms'=>'int'],
'RdKafka::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka::getOutQLen' => ['int'],
'RdKafka::newQueue' => ['RdKafka\Queue'],
'RdKafka::newTopic' => ['RdKafka\Topic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\Conf::dump' => ['array<string, string>'],
'RdKafka\Conf::set' => ['void', 'name'=>'string', 'value'=>'string'],
'RdKafka\Conf::setDefaultTopicConf' => ['void', 'topic_conf'=>'RdKafka\TopicConf'],
'RdKafka\Conf::setDrMsgCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setErrorCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setRebalanceCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setStatsCb' => ['void', 'callback'=>'callable'],
'RdKafka\Consumer::__construct' => ['void', 'conf='=>'?RdKafka\Conf'],
'RdKafka\Consumer::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka\Consumer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka\Consumer::getOutQLen' => ['int'],
'RdKafka\Consumer::newQueue' => ['RdKafka\Queue'],
'RdKafka\Consumer::newTopic' => ['RdKafka\ConsumerTopic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka\Consumer::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka\Consumer::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\ConsumerTopic::__construct' => ['void'],
'RdKafka\ConsumerTopic::consume' => ['RdKafka\Message', 'partition'=>'int', 'timeout_ms'=>'int'],
'RdKafka\ConsumerTopic::consumeQueueStart' => ['void', 'partition'=>'int', 'offset'=>'int', 'queue'=>'RdKafka\Queue'],
'RdKafka\ConsumerTopic::consumeStart' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\ConsumerTopic::consumeStop' => ['void', 'partition'=>'int'],
'RdKafka\ConsumerTopic::getName' => ['string'],
'RdKafka\ConsumerTopic::offsetStore' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\KafkaConsumer::__construct' => ['void', 'conf'=>'RdKafka\Conf'],
'RdKafka\KafkaConsumer::assign' => ['void', 'topic_partitions='=>'RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::commit' => ['void', 'message_or_offsets='=>'RdKafka\Message|RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::commitAsync' => ['void', 'message_or_offsets='=>'string'],
'RdKafka\KafkaConsumer::consume' => ['RdKafka\Message', 'timeout_ms'=>'int'],
'RdKafka\KafkaConsumer::getAssignment' => ['RdKafka\TopicPartition[]'],
'RdKafka\KafkaConsumer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\KafkaConsumerTopic', 'timeout_ms'=>'int'],
'RdKafka\KafkaConsumer::getSubscription' => ['array'],
'RdKafka\KafkaConsumer::subscribe' => ['void', 'topics'=>'array'],
'RdKafka\KafkaConsumer::unsubscribe' => ['void'],
'RdKafka\KafkaConsumerTopic::getName' => ['string'],
'RdKafka\KafkaConsumerTopic::offsetStore' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\Message::errstr' => ['string'],
'RdKafka\Metadata::getBrokers' => ['RdKafka\Metadata\Collection'],
'RdKafka\Metadata::getOrigBrokerId' => ['int'],
'RdKafka\Metadata::getOrigBrokerName' => ['string'],
'RdKafka\Metadata::getTopics' => ['RdKafka\Metadata\Collection|RdKafka\Metadata\Topic[]'],
'RdKafka\Metadata\Collection::__construct' => ['void'],
'RdKafka\Metadata\Collection::count' => ['int'],
'RdKafka\Metadata\Collection::current' => ['mixed'],
'RdKafka\Metadata\Collection::key' => ['mixed'],
'RdKafka\Metadata\Collection::next' => ['void'],
'RdKafka\Metadata\Collection::rewind' => ['void'],
'RdKafka\Metadata\Collection::valid' => ['bool'],
'RdKafka\Metadata\Partition::getErr' => ['mixed'],
'RdKafka\Metadata\Partition::getId' => ['int'],
'RdKafka\Metadata\Partition::getIsrs' => ['mixed'],
'RdKafka\Metadata\Partition::getLeader' => ['mixed'],
'RdKafka\Metadata\Partition::getReplicas' => ['mixed'],
'RdKafka\Metadata\Topic::getErr' => ['mixed'],
'RdKafka\Metadata\Topic::getPartitions' => ['RdKafka\Metadata\Partition[]'],
'RdKafka\Metadata\Topic::getTopic' => ['string'],
'RdKafka\Producer::__construct' => ['void', 'conf='=>'?RdKafka\Conf'],
'RdKafka\Producer::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka\Producer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka\Producer::getOutQLen' => ['int'],
'RdKafka\Producer::newQueue' => ['RdKafka\Queue'],
'RdKafka\Producer::newTopic' => ['RdKafka\ProducerTopic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka\Producer::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka\Producer::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\ProducerTopic::__construct' => ['void'],
'RdKafka\ProducerTopic::getName' => ['string'],
'RdKafka\ProducerTopic::produce' => ['void', 'partition'=>'int', 'msgflags'=>'int', 'payload'=>'string', 'key='=>'?string'],
'RdKafka\ProducerTopic::producev' => ['void', 'partition'=>'int', 'msgflags'=>'int', 'payload'=>'string', 'key='=>'?string', 'headers'=>'?array<string, string>', 'timestamp_ms'=>'?int'],
'RdKafka\Queue::__construct' => ['void'],
'RdKafka\Queue::consume' => ['?RdKafka\Message', 'timeout_ms'=>'string'],
'RdKafka\Topic::getName' => ['string'],
'RdKafka\TopicConf::dump' => ['array<string, string>'],
'RdKafka\TopicConf::set' => ['void', 'name'=>'string', 'value'=>'string'],
'RdKafka\TopicConf::setPartitioner' => ['void', 'partitioner'=>'int'],
'RdKafka\TopicPartition::__construct' => ['void', 'topic'=>'string', 'partition'=>'int', 'offset='=>'int'],
'RdKafka\TopicPartition::getOffset' => ['int'],
'RdKafka\TopicPartition::getPartition' => ['int'],
'RdKafka\TopicPartition::getTopic' => ['string'],
'RdKafka\TopicPartition::setOffset' => ['void', 'offset'=>'string'],
'RdKafka\TopicPartition::setPartition' => ['void', 'partition'=>'string'],
'RdKafka\TopicPartition::setTopic' => ['void', 'topic_name'=>'string'],
'read_exif_data' => ['array', 'filename'=>'string|resource', 'sections_needed='=>'string', 'sub_arrays='=>'bool', 'read_thumbnail='=>'bool'],
'readdir' => ['string|false', 'dir_handle='=>'resource'],
'readfile' => ['int|false', 'filename'=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'readgzfile' => ['int|false', 'filename'=>'string', 'use_include_path='=>'int'],
'readline' => ['string|false', 'prompt='=>'?string'],
'readline_add_history' => ['bool', 'prompt'=>'string'],
'readline_callback_handler_install' => ['bool', 'prompt'=>'string', 'callback'=>'callable'],
'readline_callback_handler_remove' => ['bool'],
'readline_callback_read_char' => ['void'],
'readline_clear_history' => ['bool'],
'readline_completion_function' => ['bool', 'callback'=>'callable'],
'readline_info' => ['mixed', 'var_name='=>'string', 'value='=>'string|int|bool'],
'readline_list_history' => ['array'],
'readline_on_new_line' => ['void'],
'readline_read_history' => ['bool', 'filename='=>'string'],
'readline_redisplay' => ['void'],
'readline_write_history' => ['bool', 'filename='=>'string'],
'readlink' => ['string|false', 'path'=>'string'],
'realpath' => ['string|false', 'path'=>'string'],
'realpath_cache_get' => ['array'],
'realpath_cache_size' => ['int'],
'recode' => ['string', 'request'=>'string', 'string'=>'string'],
'recode_file' => ['bool', 'request'=>'string', 'input'=>'resource', 'output'=>'resource'],
'recode_string' => ['string|false', 'request'=>'string', 'string'=>'string'],
'rectObj::__construct' => ['void'],
'rectObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj', 'class_index'=>'int', 'text'=>'string'],
'rectObj::fit' => ['float', 'width'=>'int', 'height'=>'int'],
'rectObj::ms_newRectObj' => ['rectObj'],
'rectObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'rectObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'rectObj::setextent' => ['void', 'minx'=>'float', 'miny'=>'float', 'maxx'=>'float', 'maxy'=>'float'],
'RecursiveArrayIterator::__construct' => ['void', 'array='=>'array|object', 'flags='=>'int'],
'RecursiveArrayIterator::append' => ['void', 'value'=>'mixed'],
'RecursiveArrayIterator::asort' => ['void'],
'RecursiveArrayIterator::count' => ['int'],
'RecursiveArrayIterator::current' => ['mixed'],
'RecursiveArrayIterator::getArrayCopy' => ['array'],
'RecursiveArrayIterator::getChildren' => ['RecursiveArrayIterator'],
'RecursiveArrayIterator::getFlags' => ['void'],
'RecursiveArrayIterator::hasChildren' => ['bool'],
'RecursiveArrayIterator::key' => ['false|int|string'],
'RecursiveArrayIterator::ksort' => ['void'],
'RecursiveArrayIterator::natcasesort' => ['void'],
'RecursiveArrayIterator::natsort' => ['void'],
'RecursiveArrayIterator::next' => ['void'],
'RecursiveArrayIterator::offsetExists' => ['void', 'index'=>'string'],
'RecursiveArrayIterator::offsetGet' => ['mixed', 'index'=>'string'],
'RecursiveArrayIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'string'],
'RecursiveArrayIterator::offsetUnset' => ['void', 'index'=>'string'],
'RecursiveArrayIterator::rewind' => ['void'],
'RecursiveArrayIterator::seek' => ['void', 'position'=>'int'],
'RecursiveArrayIterator::serialize' => ['string'],
'RecursiveArrayIterator::setFlags' => ['void', 'flags'=>'string'],
'RecursiveArrayIterator::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'RecursiveArrayIterator::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'RecursiveArrayIterator::unserialize' => ['string', 'serialized'=>'string'],
'RecursiveArrayIterator::valid' => ['bool'],
'RecursiveCachingIterator::__construct' => ['void', 'it'=>'Iterator', 'flags='=>'int'],
'RecursiveCachingIterator::__toString' => ['string'],
'RecursiveCachingIterator::count' => ['int'],
'RecursiveCachingIterator::current' => ['void'],
'RecursiveCachingIterator::getCache' => ['array'],
'RecursiveCachingIterator::getChildren' => ['RecursiveCachingIterator'],
'RecursiveCachingIterator::getFlags' => ['int'],
'RecursiveCachingIterator::getInnerIterator' => ['Iterator'],
'RecursiveCachingIterator::hasChildren' => ['bool'],
'RecursiveCachingIterator::hasNext' => ['bool'],
'RecursiveCachingIterator::key' => ['bool|float|int|string'],
'RecursiveCachingIterator::next' => ['void'],
'RecursiveCachingIterator::offsetExists' => ['bool', 'index'=>'string'],
'RecursiveCachingIterator::offsetGet' => ['string', 'index'=>'string'],
'RecursiveCachingIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'string'],
'RecursiveCachingIterator::offsetUnset' => ['void', 'index'=>'string'],
'RecursiveCachingIterator::rewind' => ['void'],
'RecursiveCachingIterator::setFlags' => ['void', 'flags'=>'int'],
'RecursiveCachingIterator::valid' => ['bool'],
'RecursiveCallbackFilterIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator', 'func'=>'callable'],
'RecursiveCallbackFilterIterator::accept' => ['bool'],
'RecursiveCallbackFilterIterator::current' => ['mixed'],
'RecursiveCallbackFilterIterator::getChildren' => ['RecursiveCallbackFilterIterator'],
'RecursiveCallbackFilterIterator::getInnerIterator' => ['Iterator'],
'RecursiveCallbackFilterIterator::hasChildren' => ['bool'],
'RecursiveCallbackFilterIterator::key' => ['bool|float|int|string'],
'RecursiveCallbackFilterIterator::next' => ['void'],
'RecursiveCallbackFilterIterator::rewind' => ['void'],
'RecursiveCallbackFilterIterator::valid' => ['bool'],
'RecursiveDirectoryIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'RecursiveDirectoryIterator::__toString' => ['string'],
'RecursiveDirectoryIterator::_bad_state_ex' => [''],
'RecursiveDirectoryIterator::current' => ['string|SplFileInfo|FilesystemIterator'],
'RecursiveDirectoryIterator::getATime' => ['int'],
'RecursiveDirectoryIterator::getBasename' => ['string', 'suffix='=>'string'],
'RecursiveDirectoryIterator::getChildren' => ['RecursiveDirectoryIterator'],
'RecursiveDirectoryIterator::getCTime' => ['int'],
'RecursiveDirectoryIterator::getExtension' => ['string'],
'RecursiveDirectoryIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'RecursiveDirectoryIterator::getFilename' => ['string'],
'RecursiveDirectoryIterator::getFlags' => ['int'],
'RecursiveDirectoryIterator::getGroup' => ['int'],
'RecursiveDirectoryIterator::getInode' => ['int'],
'RecursiveDirectoryIterator::getLinkTarget' => ['string'],
'RecursiveDirectoryIterator::getMTime' => ['int'],
'RecursiveDirectoryIterator::getOwner' => ['int'],
'RecursiveDirectoryIterator::getPath' => ['string'],
'RecursiveDirectoryIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'RecursiveDirectoryIterator::getPathname' => ['string'],
'RecursiveDirectoryIterator::getPerms' => ['int'],
'RecursiveDirectoryIterator::getRealPath' => ['string'],
'RecursiveDirectoryIterator::getSize' => ['int'],
'RecursiveDirectoryIterator::getSubPath' => ['string'],
'RecursiveDirectoryIterator::getSubPathname' => ['string'],
'RecursiveDirectoryIterator::getType' => ['string'],
'RecursiveDirectoryIterator::hasChildren' => ['bool', 'allow_links='=>'bool'],
'RecursiveDirectoryIterator::isDir' => ['bool'],
'RecursiveDirectoryIterator::isDot' => ['bool'],
'RecursiveDirectoryIterator::isExecutable' => ['bool'],
'RecursiveDirectoryIterator::isFile' => ['bool'],
'RecursiveDirectoryIterator::isLink' => ['bool'],
'RecursiveDirectoryIterator::isReadable' => ['bool'],
'RecursiveDirectoryIterator::isWritable' => ['bool'],
'RecursiveDirectoryIterator::key' => ['string'],
'RecursiveDirectoryIterator::next' => ['void'],
'RecursiveDirectoryIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'RecursiveDirectoryIterator::rewind' => ['void'],
'RecursiveDirectoryIterator::seek' => ['void', 'position'=>'int'],
'RecursiveDirectoryIterator::setFileClass' => ['void', 'class_name='=>'string'],
'RecursiveDirectoryIterator::setFlags' => ['void', 'flags='=>'int'],
'RecursiveDirectoryIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'RecursiveDirectoryIterator::valid' => ['bool'],
'RecursiveFilterIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator'],
'RecursiveFilterIterator::accept' => ['bool'],
'RecursiveFilterIterator::current' => ['mixed'],
'RecursiveFilterIterator::getChildren' => ['RecursiveFilterIterator'],
'RecursiveFilterIterator::getInnerIterator' => ['Iterator'],
'RecursiveFilterIterator::hasChildren' => ['bool'],
'RecursiveFilterIterator::key' => ['mixed'],
'RecursiveFilterIterator::next' => ['void'],
'RecursiveFilterIterator::rewind' => ['void'],
'RecursiveFilterIterator::valid' => ['bool'],
'RecursiveIterator::__construct' => ['void'],
'RecursiveIterator::current' => ['mixed'],
'RecursiveIterator::getChildren' => ['RecursiveIterator'],
'RecursiveIterator::hasChildren' => ['bool'],
'RecursiveIterator::key' => ['int|string'],
'RecursiveIterator::next' => ['void'],
'RecursiveIterator::rewind' => ['void'],
'RecursiveIterator::valid' => ['bool'],
'RecursiveIteratorIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator|IteratorAggregate', 'mode='=>'int', 'flags='=>'int'],
'RecursiveIteratorIterator::beginChildren' => ['void'],
'RecursiveIteratorIterator::beginIteration' => ['RecursiveIterator'],
'RecursiveIteratorIterator::callGetChildren' => ['RecursiveIterator'],
'RecursiveIteratorIterator::callHasChildren' => ['bool'],
'RecursiveIteratorIterator::current' => ['mixed'],
'RecursiveIteratorIterator::endChildren' => ['void'],
'RecursiveIteratorIterator::endIteration' => ['RecursiveIterator'],
'RecursiveIteratorIterator::getDepth' => ['int'],
'RecursiveIteratorIterator::getInnerIterator' => ['RecursiveIterator'],
'RecursiveIteratorIterator::getMaxDepth' => ['int|false'],
'RecursiveIteratorIterator::getSubIterator' => ['RecursiveIterator', 'level='=>'int'],
'RecursiveIteratorIterator::key' => ['mixed'],
'RecursiveIteratorIterator::next' => ['void'],
'RecursiveIteratorIterator::nextElement' => ['void'],
'RecursiveIteratorIterator::rewind' => ['void'],
'RecursiveIteratorIterator::setMaxDepth' => ['void', 'max_depth='=>'int'],
'RecursiveIteratorIterator::valid' => ['bool'],
'RecursiveRegexIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator', 'regex'=>'string', 'mode='=>'int', 'flags='=>'int', 'preg_flags='=>'int'],
'RecursiveRegexIterator::accept' => ['bool'],
'RecursiveRegexIterator::current' => [''],
'RecursiveRegexIterator::getChildren' => ['RecursiveRegexIterator'],
'RecursiveRegexIterator::getFlags' => ['int'],
'RecursiveRegexIterator::getInnerIterator' => [''],
'RecursiveRegexIterator::getMode' => ['int'],
'RecursiveRegexIterator::getPregFlags' => ['int'],
'RecursiveRegexIterator::getRegex' => ['string'],
'RecursiveRegexIterator::hasChildren' => ['bool'],
'RecursiveRegexIterator::key' => [''],
'RecursiveRegexIterator::next' => [''],
'RecursiveRegexIterator::rewind' => [''],
'RecursiveRegexIterator::setFlags' => ['void', 'new_flags'=>'int'],
'RecursiveRegexIterator::setMode' => ['void', 'new_mode'=>'int'],
'RecursiveRegexIterator::setPregFlags' => ['void', 'new_flags'=>'int'],
'RecursiveRegexIterator::valid' => [''],
'RecursiveTreeIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator|IteratorAggregate', 'flags='=>'int', 'cit_flags='=>'int', 'mode'=>'int'],
'RecursiveTreeIterator::beginChildren' => ['void'],
'RecursiveTreeIterator::beginIteration' => ['RecursiveIterator'],
'RecursiveTreeIterator::callGetChildren' => ['RecursiveIterator'],
'RecursiveTreeIterator::callHasChildren' => ['bool'],
'RecursiveTreeIterator::current' => ['string'],
'RecursiveTreeIterator::endChildren' => ['void'],
'RecursiveTreeIterator::endIteration' => ['void'],
'RecursiveTreeIterator::getDepth' => ['int'],
'RecursiveTreeIterator::getEntry' => ['string'],
'RecursiveTreeIterator::getInnerIterator' => ['RecursiveIterator'],
'RecursiveTreeIterator::getMaxDepth' => ['false|int'],
'RecursiveTreeIterator::getPostfix' => ['string'],
'RecursiveTreeIterator::getPrefix' => ['string'],
'RecursiveTreeIterator::getSubIterator' => ['RecursiveIterator', 'level='=>'int'],
'RecursiveTreeIterator::key' => ['string'],
'RecursiveTreeIterator::next' => ['void'],
'RecursiveTreeIterator::nextElement' => ['void'],
'RecursiveTreeIterator::rewind' => ['void'],
'RecursiveTreeIterator::setMaxDepth' => ['void', 'max_depth='=>'int'],
'RecursiveTreeIterator::setPostfix' => ['void', 'prefix'=>'string'],
'RecursiveTreeIterator::setPrefixPart' => ['void', 'part'=>'int', 'prefix'=>'string'],
'RecursiveTreeIterator::valid' => ['bool'],
'Redis::__construct' => ['void'],
'Redis::__destruct' => ['void'],
'Redis::_prefix' => ['string', 'value'=>'mixed'],
'Redis::_serialize' => ['mixed', 'value'=>'mixed'],
'Redis::_unserialize' => ['mixed', 'value'=>'string'],
'Redis::append' => ['int', 'key'=>'string', 'value'=>'string'],
'Redis::auth' => ['bool', 'password'=>'string'],
'Redis::bgRewriteAOF' => ['bool'],
'Redis::bgSave' => ['bool'],
'Redis::bitCount' => ['int', 'key'=>'string'],
'Redis::bitOp' => ['int', 'operation'=>'string', 'ret_key'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::bitpos' => ['int', 'key'=>'string', 'bit'=>'int', 'start='=>'int', 'end='=>'int'],
'Redis::blPop' => ['array', 'keys'=>'string[]', 'timeout'=>'int'],
'Redis::blPop\'1' => ['array', 'key'=>'string', 'timeout_or_key'=>'int|string', '...extra_args'=>'int|string'],
'Redis::brPop' => ['array', 'keys'=>'string[]', 'timeout'=>'int'],
'Redis::brPop\'1' => ['array', 'key'=>'string', 'timeout_or_key'=>'int|string', '...extra_args'=>'int|string'],
'Redis::brpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string', 'timeout'=>'int'],
'Redis::clearLastError' => ['bool'],
'Redis::client' => ['mixed', 'command'=>'string', 'arg='=>'string'],
'Redis::close' => ['bool'],
'Redis::command' => ['', '...args'=>''],
'Redis::config' => ['string', 'operation'=>'string', 'key'=>'string', 'value='=>'string'],
'Redis::connect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'reserved='=>'null', 'retry_interval='=>'?int', 'read_timeout='=>'float'],
'Redis::dbSize' => ['int'],
'Redis::debug' => ['', 'key'=>''],
'Redis::decr' => ['int', 'key'=>'string'],
'Redis::decrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'Redis::decrByFloat' => ['float', 'key'=>'string', 'value'=>'float'],
'Redis::del' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::del\'1' => ['int', 'key'=>'string[]'],
'Redis::delete' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::delete\'1' => ['int', 'key'=>'string[]'],
'Redis::discard' => [''],
'Redis::dump' => ['string|false', 'key'=>'string'],
'Redis::echo' => ['string', 'message'=>'string'],
'Redis::eval' => ['mixed', 'script'=>'', 'args='=>'', 'numKeys='=>''],
'Redis::evalSha' => ['mixed', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::evaluate' => ['mixed', 'script'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::evaluateSha' => ['', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::exec' => ['array'],
'Redis::exists' => ['int', 'keys'=>'string|string[]'],
'Redis::exists\'1' => ['int', '...keys'=>'string'],
'Redis::expire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'Redis::expireAt' => ['bool', 'key'=>'string', 'expiry'=>'int'],
'Redis::flushAll' => ['bool', 'async='=>'bool'],
'Redis::flushDb' => ['bool', 'async='=>'bool'],
'Redis::geoAdd' => ['int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'member'=>'string', '...other_triples='=>'string|int|float'],
'Redis::geoDist' => ['float', 'key'=>'string', 'member1'=>'string', 'member2'=>'string', 'unit='=>'string'],
'Redis::geoHash' => ['array<int,string>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::geoPos' => ['array<int,array{0:string,1:string}>', 'key'=>'string', 'member'=>'string', '...members='=>'string'],
'Redis::geoRadius' => ['array<int,mixed>|int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'radius'=>'float', 'unit'=>'float', 'options='=>'array<string,mixed>'],
'Redis::geoRadiusByMember' => ['array<int,mixed>|int', 'key'=>'string', 'member'=>'string', 'radius'=>'float', 'units'=>'string', 'options='=>'array<string,mixed>'],
'Redis::get' => ['string|false', 'key'=>'string'],
'Redis::getAuth' => ['string|false|null'],
'Redis::getBit' => ['int', 'key'=>'string', 'offset'=>'int'],
'Redis::getDBNum' => ['int|false'],
'Redis::getHost' => ['string|false'],
'Redis::getKeys' => ['array<int,string>', 'pattern'=>'string'],
'Redis::getLastError' => ['?string'],
'Redis::getMode' => ['int'],
'Redis::getMultiple' => ['array', 'keys'=>'string[]'],
'Redis::getOption' => ['int', 'name'=>'int'],
'Redis::getPersistentID' => ['string|false|null'],
'Redis::getPort' => ['int|false'],
'Redis::getRange' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::getReadTimeout' => ['float|false'],
'Redis::getSet' => ['string', 'key'=>'string', 'string'=>'string'],
'Redis::getTimeout' => ['float|false'],
'Redis::hDel' => ['int|false', 'key'=>'string', 'hashKey1'=>'string', '...otherHashKeys='=>'string'],
'Redis::hExists' => ['bool', 'key'=>'string', 'hashKey'=>'string'],
'Redis::hGet' => ['string|false', 'key'=>'string', 'hashKey'=>'string'],
'Redis::hGetAll' => ['array', 'key'=>'string'],
'Redis::hIncrBy' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'int'],
'Redis::hIncrByFloat' => ['float', 'key'=>'string', 'field'=>'string', 'increment'=>'float'],
'Redis::hKeys' => ['array', 'key'=>'string'],
'Redis::hLen' => ['int|false', 'key'=>'string'],
'Redis::hMGet' => ['array', 'key'=>'string', 'hashKeys'=>'array'],
'Redis::hMSet' => ['bool', 'key'=>'string', 'hashKeys'=>'array'],
'Redis::hScan' => ['array', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::hSet' => ['int|false', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'Redis::hSetNx' => ['bool', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'Redis::hStrLen' => ['', 'key'=>'', 'member'=>''],
'Redis::hVals' => ['array', 'key'=>'string'],
'Redis::incr' => ['int', 'key'=>'string'],
'Redis::incrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'Redis::incrByFloat' => ['float', 'key'=>'string', 'value'=>'float'],
'Redis::info' => ['array', 'option='=>'string'],
'Redis::isConnected' => ['bool'],
'Redis::keys' => ['array<int,string>', 'pattern'=>'string'],
'Redis::lastSave' => ['int'],
'Redis::lGet' => ['string', 'key'=>'string', 'index'=>'int'],
'Redis::lGetRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::lIndex' => ['string|false', 'key'=>'string', 'index'=>'int'],
'Redis::lInsert' => ['int', 'key'=>'string', 'position'=>'int', 'pivot'=>'string', 'value'=>'string'],
'Redis::listTrim' => ['', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'Redis::lLen' => ['int|false', 'key'=>'string'],
'Redis::lPop' => ['string|false', 'key'=>'string'],
'Redis::lPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::lPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'Redis::lRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::lRem' => ['int|false', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'Redis::lRemove' => ['int', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'Redis::lSet' => ['bool', 'key'=>'string', 'index'=>'int', 'value'=>'string'],
'Redis::lSize' => ['int', 'key'=>'string'],
'Redis::lTrim' => ['array|false', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'Redis::mGet' => ['array', 'keys'=>'string[]'],
'Redis::migrate' => ['bool', 'host'=>'string', 'port'=>'int', 'key'=>'string|string[]', 'db'=>'int', 'timeout'=>'int', 'copy='=>'bool', 'replace='=>'bool'],
'Redis::move' => ['bool', 'key'=>'string', 'dbindex'=>'int'],
'Redis::mSet' => ['bool', 'pairs'=>'array'],
'Redis::mSetNx' => ['bool', 'pairs'=>'array'],
'Redis::multi' => ['Redis', 'mode='=>'int'],
'Redis::object' => ['string|long|false', 'info'=>'string', 'key'=>'string'],
'Redis::open' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'reserved='=>'null', 'retry_interval='=>'?int', 'read_timeout='=>'float'],
'Redis::pconnect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'persistent_id='=>'string', 'retry_interval='=>'?int'],
'Redis::persist' => ['bool', 'key'=>'string'],
'Redis::pExpire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'Redis::pexpireAt' => ['bool', 'key'=>'string', 'expiry'=>'int'],
'Redis::pfAdd' => ['bool', 'key'=>'string', 'elements'=>'array'],
'Redis::pfCount' => ['int', 'key'=>'array|string'],
'Redis::pfMerge' => ['bool', 'destkey'=>'string', 'sourcekeys'=>'array'],
'Redis::ping' => ['string'],
'Redis::pipeline' => ['Redis'],
'Redis::popen' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'persistent_id='=>'string', 'retry_interval='=>'?int'],
'Redis::psetex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::psubscribe' => ['', 'patterns'=>'array', 'callback'=>'array|string'],
'Redis::pttl' => ['int|false', 'key'=>'string'],
'Redis::publish' => ['int', 'channel'=>'string', 'message'=>'string'],
'Redis::pubsub' => ['array|int', 'keyword'=>'string', 'argument='=>'array|string'],
'Redis::punsubscribe' => ['', 'pattern'=>'string', '...other_patterns='=>'string'],
'Redis::randomKey' => ['string'],
'Redis::rawCommand' => ['mixed', 'command'=>'string', '...arguments='=>'mixed'],
'Redis::rename' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::renameKey' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::renameNx' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::resetStat' => ['bool'],
'Redis::restore' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::role' => ['array', 'nodeParams'=>'string|array{0:string,1:int}'],
'Redis::rPop' => ['string|false', 'key'=>'string'],
'Redis::rpoplpush' => ['string', 'srcKey'=>'string', 'dstKey'=>'string'],
'Redis::rPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::rPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'Redis::sAdd' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::sAddArray' => ['bool', 'key'=>'string', 'values'=>'array'],
'Redis::save' => ['bool'],
'Redis::scan' => ['array<int,string>|false', '&rw_iterator'=>'?int', 'pattern='=>'?string', 'count='=>'?int'],
'Redis::sCard' => ['int', 'key'=>'string'],
'Redis::sContains' => ['', 'key'=>'string', 'value'=>'string'],
'Redis::script' => ['mixed', 'command'=>'string', '...args='=>'mixed'],
'Redis::sDiff' => ['array', 'key1'=>'string', '...other_keys='=>'string'],
'Redis::sDiffStore' => ['int|false', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::select' => ['bool', 'dbindex'=>'int'],
'Redis::sendEcho' => ['string', 'msg'=>'string'],
'Redis::set' => ['bool', 'key'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Redis::set\'1' => ['bool', 'key'=>'string', 'value'=>'mixed', 'timeout='=>'int'],
'Redis::setBit' => ['int', 'key'=>'string', 'offset'=>'int', 'value'=>'int'],
'Redis::setEx' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::setNx' => ['bool', 'key'=>'string', 'value'=>'string'],
'Redis::setOption' => ['bool', 'name'=>'int', 'value'=>'mixed'],
'Redis::setRange' => ['int', 'key'=>'string', 'offset'=>'int', 'end'=>'int'],
'Redis::setTimeout' => ['', 'key'=>'string', 'ttl'=>'int'],
'Redis::sGetMembers' => ['', 'key'=>'string'],
'Redis::sInter' => ['array|false', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sInterStore' => ['int|false', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sIsMember' => ['bool', 'key'=>'string', 'value'=>'string'],
'Redis::slave' => ['bool', 'host'=>'string', 'port'=>'int'],
'Redis::slave\'1' => ['bool', 'host'=>'string', 'port'=>'int'],
'Redis::slaveof' => ['bool', 'host='=>'string', 'port='=>'int'],
'Redis::slowLog' => ['mixed', 'operation'=>'string', 'length='=>'int'],
'Redis::sMembers' => ['array', 'key'=>'string'],
'Redis::sMove' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string', 'member'=>'string'],
'Redis::sort' => ['array|int', 'key'=>'string', 'options='=>'array'],
'Redis::sortAsc' => ['array', 'key'=>'string', 'pattern='=>'string', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortAscAlpha' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortDesc' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortDescAlpha' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sPop' => ['string|false', 'key'=>'string'],
'Redis::sRandMember' => ['array|string|false', 'key'=>'string', 'count='=>'int'],
'Redis::sRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'Redis::sRemove' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'Redis::sScan' => ['array|bool', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::sSize' => ['int', 'key'=>'string'],
'Redis::strLen' => ['int', 'key'=>'string'],
'Redis::subscribe' => ['mixed|null', 'channels'=>'array', 'callback'=>'string|array'],
'Redis::substr' => ['', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::sUnion' => ['array', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sUnionStore' => ['int', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::swapdb' => ['bool', 'srcdb'=>'int', 'dstdb'=>'int'],
'Redis::time' => ['array'],
'Redis::ttl' => ['int|false', 'key'=>'string'],
'Redis::type' => ['int', 'key'=>'string'],
'Redis::unlink' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::unlink\'1' => ['int', 'key'=>'string[]'],
'Redis::unsubscribe' => ['', 'channel'=>'string', '...other_channels='=>'string'],
'Redis::unwatch' => [''],
'Redis::wait' => ['int', 'numSlaves'=>'int', 'timeout'=>'int'],
'Redis::watch' => ['void', 'key'=>'string', '...other_keys='=>'string'],
'Redis::xack' => ['', 'str_key'=>'string', 'str_group'=>'string', 'arr_ids'=>'array'],
'Redis::xadd' => ['', 'str_key'=>'string', 'str_id'=>'string', 'arr_fields'=>'array', 'i_maxlen='=>'', 'boo_approximate='=>''],
'Redis::xclaim' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_consumer'=>'string', 'i_min_idle'=>'', 'arr_ids'=>'array', 'arr_opts='=>'array'],
'Redis::xdel' => ['', 'str_key'=>'string', 'arr_ids'=>'array'],
'Redis::xgroup' => ['', 'str_operation'=>'string', 'str_key='=>'string', 'str_arg1='=>'', 'str_arg2='=>'', 'str_arg3='=>''],
'Redis::xinfo' => ['', 'str_cmd'=>'string', 'str_key='=>'string', 'str_group='=>'string'],
'Redis::xlen' => ['', 'key'=>''],
'Redis::xpending' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_start='=>'', 'str_end='=>'', 'i_count='=>'', 'str_consumer='=>'string'],
'Redis::xrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'Redis::xread' => ['', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'Redis::xreadgroup' => ['', 'str_group'=>'string', 'str_consumer'=>'string', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'Redis::xrevrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'Redis::xtrim' => ['', 'str_key'=>'string', 'i_maxlen'=>'', 'boo_approximate='=>''],
'Redis::zAdd' => ['int', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'Redis::zAdd\'1' => ['int', 'options'=>'array', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'Redis::zCard' => ['int', 'key'=>'string'],
'Redis::zCount' => ['int', 'key'=>'string', 'start'=>'string', 'end'=>'string'],
'Redis::zDelete' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zDeleteRangeByRank' => ['', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zDeleteRangeByScore' => ['', 'key'=>'string', 'start'=>'float', 'end'=>'float'],
'Redis::zIncrBy' => ['float', 'key'=>'string', 'value'=>'float', 'member'=>'string'],
'Redis::zInter' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zInterStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zLexCount' => ['int', 'key'=>'string', 'min'=>'string', 'max'=>'string'],
'Redis::zRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscores='=>'bool'],
'Redis::zRangeByLex' => ['array|false', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'Redis::zRangeByScore' => ['array', 'key'=>'string', 'start'=>'int|string', 'end'=>'int|string', 'options='=>'array'],
'Redis::zRank' => ['int', 'key'=>'string', 'member'=>'string'],
'Redis::zRem' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zRemove' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zRemoveRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zRemoveRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'Redis::zRemRangeByLex' => ['int', 'key'=>'string', 'min'=>'string', 'max'=>'string'],
'Redis::zRemRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zRemRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'Redis::zReverseRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'Redis::zRevRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'Redis::zRevRangeByLex' => ['array', 'key'=>'string', 'min'=>'string', 'max'=>'string', 'offset='=>'int', 'limit='=>'int'],
'Redis::zRevRangeByScore' => ['array', 'key'=>'string', 'start'=>'string', 'end'=>'string', 'options='=>'array'],
'Redis::zRevRank' => ['int', 'key'=>'string', 'member'=>'string'],
'Redis::zScan' => ['array|bool', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::zScore' => ['float|false', 'key'=>'string', 'member'=>'string'],
'Redis::zSize' => ['', 'key'=>'string'],
'Redis::zUnion' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zUnionStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'RedisArray::__call' => ['mixed', 'function_name'=>'string', 'arguments'=>'array'],
'RedisArray::__construct' => ['void', 'name='=>'string', 'hosts='=>'?array', 'opts='=>'?array'],
'RedisArray::_continuum' => [''],
'RedisArray::_distributor' => [''],
'RedisArray::_function' => ['string'],
'RedisArray::_hosts' => ['array'],
'RedisArray::_instance' => ['', 'host'=>''],
'RedisArray::_rehash' => ['', 'callable='=>'callable'],
'RedisArray::_target' => ['string', 'key'=>'string'],
'RedisArray::bgsave' => [''],
'RedisArray::del' => ['bool', 'key'=>'string', '...args'=>'string'],
'RedisArray::delete' => ['bool', 'key'=>'string', '...args'=>'string'],
'RedisArray::delete\'1' => ['bool', 'key'=>'string[]'],
'RedisArray::discard' => [''],
'RedisArray::exec' => ['array'],
'RedisArray::flushAll' => ['bool', 'async='=>'bool'],
'RedisArray::flushDb' => ['bool', 'async='=>'bool'],
'RedisArray::getMultiple' => ['', 'keys'=>''],
'RedisArray::getOption' => ['', 'opt'=>''],
'RedisArray::info' => ['array'],
'RedisArray::keys' => ['array<int,string>', 'pattern'=>''],
'RedisArray::mGet' => ['array', 'keys'=>'string[]'],
'RedisArray::mSet' => ['bool', 'pairs'=>'array'],
'RedisArray::multi' => ['RedisArray', 'host'=>'string', 'mode='=>'int'],
'RedisArray::ping' => ['string'],
'RedisArray::save' => ['bool'],
'RedisArray::select' => ['', 'index'=>''],
'RedisArray::setOption' => ['', 'opt'=>'', 'value'=>''],
'RedisArray::unlink' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisArray::unlink\'1' => ['int', 'key'=>'string[]'],
'RedisArray::unwatch' => [''],
'RedisCluster::__construct' => ['void', 'name'=>'?string', 'seeds='=>'string[]', 'timeout='=>'float', 'readTimeout='=>'float', 'persistent='=>'bool', 'auth='=>'?string'],
'RedisCluster::_masters' => ['array'],
'RedisCluster::_prefix' => ['string', 'value'=>'mixed'],
'RedisCluster::_redir' => [''],
'RedisCluster::_serialize' => ['mixed', 'value'=>'mixed'],
'RedisCluster::_unserialize' => ['mixed', 'value'=>'string'],
'RedisCluster::append' => ['int', 'key'=>'string', 'value'=>'string'],
'RedisCluster::bgrewriteaof' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::bgsave' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::bitCount' => ['int', 'key'=>'string'],
'RedisCluster::bitOp' => ['int', 'operation'=>'string', 'retKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::bitpos' => ['int', 'key'=>'string', 'bit'=>'int', 'start='=>'int', 'end='=>'int'],
'RedisCluster::blPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'RedisCluster::brPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'RedisCluster::brpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string', 'timeout'=>'int'],
'RedisCluster::clearLastError' => ['bool'],
'RedisCluster::client' => ['', 'nodeParams'=>'string|array{0:string,1:int}', 'subCmd='=>'string', '...args='=>''],
'RedisCluster::close' => [''],
'RedisCluster::cluster' => ['mixed', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'arguments='=>'mixed'],
'RedisCluster::command' => ['array|bool'],
'RedisCluster::config' => ['array|bool', 'nodeParams'=>'string|array{0:string,1:int}', 'operation'=>'string', 'key'=>'string', 'value='=>'string'],
'RedisCluster::dbSize' => ['int', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::decr' => ['int', 'key'=>'string'],
'RedisCluster::decrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'RedisCluster::del' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::del\'1' => ['int', 'key'=>'string[]'],
'RedisCluster::discard' => [''],
'RedisCluster::dump' => ['string|false', 'key'=>'string'],
'RedisCluster::echo' => ['string', 'nodeParams'=>'string|array{0:string,1:int}', 'msg'=>'string'],
'RedisCluster::eval' => ['mixed', 'script'=>'', 'args='=>'', 'numKeys='=>''],
'RedisCluster::evalSha' => ['mixed', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'RedisCluster::exec' => ['array|void'],
'RedisCluster::exists' => ['bool', 'key'=>'string'],
'RedisCluster::expire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'RedisCluster::expireAt' => ['bool', 'key'=>'string', 'timestamp'=>'int'],
'RedisCluster::flushAll' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}', 'async='=>'bool'],
'RedisCluster::flushDB' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}', 'async='=>'bool'],
'RedisCluster::geoAdd' => ['int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'member'=>'string', '...other_members='=>'float|string'],
'RedisCluster::geoDist' => ['', 'key'=>'string', 'member1'=>'string', 'member2'=>'string', 'unit='=>'string'],
'RedisCluster::geohash' => ['array<int,string>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'RedisCluster::geopos' => ['array<int,array{0:string,1:string}>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'RedisCluster::geoRadius' => ['', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'radius'=>'float', 'radiusUnit'=>'string', 'options='=>'array'],
'RedisCluster::geoRadiusByMember' => ['string[]', 'key'=>'string', 'member'=>'string', 'radius'=>'float', 'radiusUnit'=>'string', 'options='=>'array'],
'RedisCluster::get' => ['string|false', 'key'=>'string'],
'RedisCluster::getBit' => ['int', 'key'=>'string', 'offset'=>'int'],
'RedisCluster::getLastError' => ['?string'],
'RedisCluster::getMode' => ['int'],
'RedisCluster::getOption' => ['int', 'name'=>'string'],
'RedisCluster::getRange' => ['string', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::getSet' => ['string', 'key'=>'string', 'value'=>'string'],
'RedisCluster::hDel' => ['int|false', 'key'=>'string', 'hashKey'=>'string', '...other_hashKeys='=>'string[]'],
'RedisCluster::hExists' => ['bool', 'key'=>'string', 'hashKey'=>'string'],
'RedisCluster::hGet' => ['string|false', 'key'=>'string', 'hashKey'=>'string'],
'RedisCluster::hGetAll' => ['array', 'key'=>'string'],
'RedisCluster::hIncrBy' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'int'],
'RedisCluster::hIncrByFloat' => ['float', 'key'=>'string', 'field'=>'string', 'increment'=>'float'],
'RedisCluster::hKeys' => ['array', 'key'=>'string'],
'RedisCluster::hLen' => ['int|false', 'key'=>'string'],
'RedisCluster::hMGet' => ['array', 'key'=>'string', 'hashKeys'=>'array'],
'RedisCluster::hMSet' => ['bool', 'key'=>'string', 'hashKeys'=>'array'],
'RedisCluster::hScan' => ['array', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::hSet' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'RedisCluster::hSetNx' => ['bool', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'RedisCluster::hStrlen' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::hVals' => ['array', 'key'=>'string'],
'RedisCluster::incr' => ['int', 'key'=>'string'],
'RedisCluster::incrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'RedisCluster::incrByFloat' => ['float', 'key'=>'string', 'increment'=>'float'],
'RedisCluster::info' => ['array', 'nodeParams'=>'string|array{0:string,1:int}', 'option='=>'string'],
'RedisCluster::keys' => ['array', 'pattern'=>'string'],
'RedisCluster::lastSave' => ['int', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::lGet' => ['', 'key'=>'string', 'index'=>'int'],
'RedisCluster::lIndex' => ['string|false', 'key'=>'string', 'index'=>'int'],
'RedisCluster::lInsert' => ['int', 'key'=>'string', 'position'=>'int', 'pivot'=>'string', 'value'=>'string'],
'RedisCluster::lLen' => ['int', 'key'=>'string'],
'RedisCluster::lPop' => ['string|false', 'key'=>'string'],
'RedisCluster::lPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::lPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'RedisCluster::lRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::lRem' => ['int|false', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'RedisCluster::lSet' => ['bool', 'key'=>'string', 'index'=>'int', 'value'=>'string'],
'RedisCluster::lTrim' => ['array|false', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'RedisCluster::mget' => ['array', 'array'=>'array'],
'RedisCluster::mset' => ['bool', 'array'=>'array'],
'RedisCluster::msetnx' => ['int', 'array'=>'array'],
'RedisCluster::multi' => ['Redis', 'mode='=>'int'],
'RedisCluster::object' => ['string|int|false', 'string'=>'string', 'key'=>'string'],
'RedisCluster::persist' => ['bool', 'key'=>'string'],
'RedisCluster::pExpire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'RedisCluster::pExpireAt' => ['bool', 'key'=>'string', 'timestamp'=>'int'],
'RedisCluster::pfAdd' => ['bool', 'key'=>'string', 'elements'=>'array'],
'RedisCluster::pfCount' => ['int', 'key'=>'string'],
'RedisCluster::pfMerge' => ['bool', 'destKey'=>'string', 'sourceKeys'=>'array'],
'RedisCluster::ping' => ['string', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::psetex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::psubscribe' => ['mixed', 'patterns'=>'array', 'callback'=>'string'],
'RedisCluster::pttl' => ['int', 'key'=>'string'],
'RedisCluster::publish' => ['int', 'channel'=>'string', 'message'=>'string'],
'RedisCluster::pubsub' => ['array', 'nodeParams'=>'string', 'keyword'=>'string', '...argument='=>'string'],
'RedisCluster::punSubscribe' => ['', 'channels'=>'', 'callback'=>''],
'RedisCluster::randomKey' => ['string', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::rawCommand' => ['mixed', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'arguments='=>'mixed'],
'RedisCluster::rename' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::renameNx' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::restore' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::role' => ['array'],
'RedisCluster::rPop' => ['string|false', 'key'=>'string'],
'RedisCluster::rpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::rPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::rPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'RedisCluster::sAdd' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::sAddArray' => ['int|false', 'key'=>'string', 'valueArray'=>'array'],
'RedisCluster::save' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::scan' => ['array|false', '&iterator'=>'int', 'nodeParams'=>'string|array{0:string,1:int}', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::sCard' => ['int', 'key'=>'string'],
'RedisCluster::script' => ['string|bool|array', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'script='=>'string', '...other_scripts='=>'string[]'],
'RedisCluster::sDiff' => ['list<string>', 'key1'=>'string', 'key2'=>'string', '...other_keys='=>'string'],
'RedisCluster::sDiffStore' => ['int', 'dstKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::set' => ['bool', 'key'=>'string', 'value'=>'string', 'timeout='=>'array|int'],
'RedisCluster::setBit' => ['int', 'key'=>'string', 'offset'=>'int', 'value'=>'bool|int'],
'RedisCluster::setex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::setnx' => ['bool', 'key'=>'string', 'value'=>'string'],
'RedisCluster::setOption' => ['bool', 'name'=>'string', 'value'=>'string'],
'RedisCluster::setRange' => ['string', 'key'=>'string', 'offset'=>'int', 'value'=>'string'],
'RedisCluster::sInter' => ['list<string>', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sInterStore' => ['int', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sIsMember' => ['bool', 'key'=>'string', 'value'=>'string'],
'RedisCluster::slowLog' => ['array|int|bool', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'length='=>'int'],
'RedisCluster::sMembers' => ['list<string>', 'key'=>'string'],
'RedisCluster::sMove' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string', 'member'=>'string'],
'RedisCluster::sort' => ['array', 'key'=>'string', 'option='=>'array'],
'RedisCluster::sPop' => ['string', 'key'=>'string'],
'RedisCluster::sRandMember' => ['array|string', 'key'=>'string', 'count='=>'int'],
'RedisCluster::sRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'RedisCluster::sScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'null', 'count='=>'int'],
'RedisCluster::strlen' => ['int', 'key'=>'string'],
'RedisCluster::subscribe' => ['mixed', 'channels'=>'array', 'callback'=>'string'],
'RedisCluster::sUnion' => ['list<string>', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::sUnion\'1' => ['list<string>', 'keys'=>'string[]'],
'RedisCluster::sUnionStore' => ['int', 'dstKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::time' => ['array'],
'RedisCluster::ttl' => ['int', 'key'=>'string'],
'RedisCluster::type' => ['int', 'key'=>'string'],
'RedisCluster::unlink' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::unSubscribe' => ['', 'channels'=>'', '...other_channels='=>''],
'RedisCluster::unwatch' => [''],
'RedisCluster::watch' => ['void', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::xack' => ['', 'str_key'=>'string', 'str_group'=>'string', 'arr_ids'=>'array'],
'RedisCluster::xadd' => ['', 'str_key'=>'string', 'str_id'=>'string', 'arr_fields'=>'array', 'i_maxlen='=>'', 'boo_approximate='=>''],
'RedisCluster::xclaim' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_consumer'=>'string', 'i_min_idle'=>'', 'arr_ids'=>'array', 'arr_opts='=>'array'],
'RedisCluster::xdel' => ['', 'str_key'=>'string', 'arr_ids'=>'array'],
'RedisCluster::xgroup' => ['', 'str_operation'=>'string', 'str_key='=>'string', 'str_arg1='=>'', 'str_arg2='=>'', 'str_arg3='=>''],
'RedisCluster::xinfo' => ['', 'str_cmd'=>'string', 'str_key='=>'string', 'str_group='=>'string'],
'RedisCluster::xlen' => ['', 'key'=>''],
'RedisCluster::xpending' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_start='=>'', 'str_end='=>'', 'i_count='=>'', 'str_consumer='=>'string'],
'RedisCluster::xrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'RedisCluster::xread' => ['', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'RedisCluster::xreadgroup' => ['', 'str_group'=>'string', 'str_consumer'=>'string', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'RedisCluster::xrevrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'RedisCluster::xtrim' => ['', 'str_key'=>'string', 'i_maxlen'=>'', 'boo_approximate='=>''],
'RedisCluster::zAdd' => ['int', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'RedisCluster::zCard' => ['int', 'key'=>'string'],
'RedisCluster::zCount' => ['int', 'key'=>'string', 'start'=>'string', 'end'=>'string'],
'RedisCluster::zIncrBy' => ['float', 'key'=>'string', 'value'=>'float', 'member'=>'string'],
'RedisCluster::zInterStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'RedisCluster::zLexCount' => ['int', 'key'=>'string', 'min'=>'int', 'max'=>'int'],
'RedisCluster::zRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscores='=>'bool'],
'RedisCluster::zRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'RedisCluster::zRangeByScore' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'options='=>'array'],
'RedisCluster::zRank' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'RedisCluster::zRemRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int'],
'RedisCluster::zRemRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::zRemRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'RedisCluster::zRevRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'RedisCluster::zRevRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'RedisCluster::zRevRangeByScore' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'options='=>'array'],
'RedisCluster::zRevRank' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::zScore' => ['float', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zUnionStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Reflection::export' => ['?string', 'r'=>'reflector', 'return='=>'bool'],
'Reflection::getModifierNames' => ['array', 'modifiers'=>'int'],
'ReflectionClass::__clone' => ['void'],
'ReflectionClass::__construct' => ['void', 'argument'=>'object|class-string'],
'ReflectionClass::__toString' => ['string'],
'ReflectionClass::export' => ['?string', 'argument'=>'string|object', 'return='=>'bool'],
'ReflectionClass::getConstant' => ['mixed', 'name'=>'string'],
'ReflectionClass::getConstants' => ['array<string,mixed>'],
'ReflectionClass::getConstructor' => ['?ReflectionMethod'],
'ReflectionClass::getDefaultProperties' => ['array'],
'ReflectionClass::getDocComment' => ['string|false'],
'ReflectionClass::getEndLine' => ['int|false'],
'ReflectionClass::getExtension' => ['?ReflectionExtension'],
'ReflectionClass::getExtensionName' => ['string|false'],
'ReflectionClass::getFileName' => ['string|false'],
'ReflectionClass::getInterfaceNames' => ['list<class-string>'],
'ReflectionClass::getInterfaces' => ['array<class-string, ReflectionClass>'],
'ReflectionClass::getMethod' => ['ReflectionMethod', 'name'=>'string'],
'ReflectionClass::getMethods' => ['list<ReflectionMethod>', 'filter='=>'int'],
'ReflectionClass::getModifiers' => ['int'],
'ReflectionClass::getName' => ['class-string'],
'ReflectionClass::getNamespaceName' => ['string'],
'ReflectionClass::getParentClass' => ['ReflectionClass|false'],
'ReflectionClass::getProperties' => ['list<ReflectionProperty>', 'filter='=>'int'],
'ReflectionClass::getProperty' => ['ReflectionProperty', 'name'=>'string'],
'ReflectionClass::getReflectionConstant' => ['ReflectionClassConstant|false', 'name'=>'string'],
'ReflectionClass::getReflectionConstants' => ['list<ReflectionClassConstant>'],
'ReflectionClass::getShortName' => ['string'],
'ReflectionClass::getStartLine' => ['int|false'],
'ReflectionClass::getStaticProperties' => ['array<string, ReflectionProperty>'],
'ReflectionClass::getStaticPropertyValue' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'ReflectionClass::getTraitAliases' => ['array<string,string>|null'],
'ReflectionClass::getTraitNames' => ['list<trait-string>|null'],
'ReflectionClass::getTraits' => ['array<trait-string,ReflectionClass>'],
'ReflectionClass::hasConstant' => ['bool', 'name'=>'string'],
'ReflectionClass::hasMethod' => ['bool', 'name'=>'string'],
'ReflectionClass::hasProperty' => ['bool', 'name'=>'string'],
'ReflectionClass::implementsInterface' => ['bool', 'interface_name'=>'class-string|ReflectionClass'],
'ReflectionClass::inNamespace' => ['bool'],
'ReflectionClass::isAbstract' => ['bool'],
'ReflectionClass::isAnonymous' => ['bool'],
'ReflectionClass::isCloneable' => ['bool'],
'ReflectionClass::isFinal' => ['bool'],
'ReflectionClass::isInstance' => ['bool', 'object'=>'object'],
'ReflectionClass::isInstantiable' => ['bool'],
'ReflectionClass::isInterface' => ['bool'],
'ReflectionClass::isInternal' => ['bool'],
'ReflectionClass::isIterable' => ['bool'],
'ReflectionClass::isIterateable' => ['bool'],
'ReflectionClass::isSubclassOf' => ['bool', 'class'=>'class-string|ReflectionClass'],
'ReflectionClass::isTrait' => ['bool'],
'ReflectionClass::isUserDefined' => ['bool'],
'ReflectionClass::newInstance' => ['object', '...args='=>'mixed'],
'ReflectionClass::newInstanceArgs' => ['object', 'args='=>'list<mixed>'],
'ReflectionClass::newInstanceWithoutConstructor' => ['object'],
'ReflectionClass::setStaticPropertyValue' => ['void', 'name'=>'string', 'value'=>'mixed'],
'ReflectionClassConstant::__construct' => ['void', 'class'=>'mixed', 'name'=>'string'],
'ReflectionClassConstant::__toString' => ['string'],
'ReflectionClassConstant::export' => ['string', 'class'=>'mixed', 'name'=>'string', 'return='=>'bool'],
'ReflectionClassConstant::getDeclaringClass' => ['ReflectionClass'],
'ReflectionClassConstant::getDocComment' => ['string|false'],
'ReflectionClassConstant::getModifiers' => ['int'],
'ReflectionClassConstant::getName' => ['string'],
'ReflectionClassConstant::getValue' => ['scalar|array<scalar>|null'],
'ReflectionClassConstant::isPrivate' => ['bool'],
'ReflectionClassConstant::isProtected' => ['bool'],
'ReflectionClassConstant::isPublic' => ['bool'],
'ReflectionExtension::__clone' => ['void'],
'ReflectionExtension::__construct' => ['void', 'name'=>'string'],
'ReflectionExtension::__toString' => ['string'],
'ReflectionExtension::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionExtension::getClasses' => ['array<class-string,ReflectionClass>'],
'ReflectionExtension::getClassNames' => ['list<class-string>'],
'ReflectionExtension::getConstants' => ['array<string,mixed>'],
'ReflectionExtension::getDependencies' => ['array<string,string>'],
'ReflectionExtension::getFunctions' => ['array<string,ReflectionFunction>'],
'ReflectionExtension::getINIEntries' => ['array<string,mixed>'],
'ReflectionExtension::getName' => ['string'],
'ReflectionExtension::getVersion' => ['string'],
'ReflectionExtension::info' => ['void'],
'ReflectionExtension::isPersistent' => ['bool'],
'ReflectionExtension::isTemporary' => ['bool'],
'ReflectionFunction::__construct' => ['void', 'name'=>'callable-string|Closure'],
'ReflectionFunction::__toString' => ['string'],
'ReflectionFunction::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionFunction::getClosure' => ['?Closure'],
'ReflectionFunction::getClosureScopeClass' => ['ReflectionClass'],
'ReflectionFunction::getClosureThis' => ['bool'],
'ReflectionFunction::getDocComment' => ['string|false'],
'ReflectionFunction::getEndLine' => ['int|false'],
'ReflectionFunction::getExtension' => ['?ReflectionExtension'],
'ReflectionFunction::getExtensionName' => ['string|false'],
'ReflectionFunction::getFileName' => ['string|false'],
'ReflectionFunction::getName' => ['callable-string'],
'ReflectionFunction::getNamespaceName' => ['string'],
'ReflectionFunction::getNumberOfParameters' => ['int'],
'ReflectionFunction::getNumberOfRequiredParameters' => ['int'],
'ReflectionFunction::getParameters' => ['list<ReflectionParameter>'],
'ReflectionFunction::getReturnType' => ['?ReflectionType'],
'ReflectionFunction::getShortName' => ['string'],
'ReflectionFunction::getStartLine' => ['int|false'],
'ReflectionFunction::getStaticVariables' => ['array'],
'ReflectionFunction::hasReturnType' => ['bool'],
'ReflectionFunction::inNamespace' => ['bool'],
'ReflectionFunction::invoke' => ['mixed', '...args='=>'mixed'],
'ReflectionFunction::invokeArgs' => ['mixed', 'args'=>'array'],
'ReflectionFunction::isClosure' => ['bool'],
'ReflectionFunction::isDeprecated' => ['bool'],
'ReflectionFunction::isDisabled' => ['bool'],
'ReflectionFunction::isGenerator' => ['bool'],
'ReflectionFunction::isInternal' => ['bool'],
'ReflectionFunction::isUserDefined' => ['bool'],
'ReflectionFunction::isVariadic' => ['bool'],
'ReflectionFunction::returnsReference' => ['bool'],
'ReflectionFunctionAbstract::__clone' => ['void'],
'ReflectionFunctionAbstract::__toString' => ['string'],
'ReflectionFunctionAbstract::export' => ['?string'],
'ReflectionFunctionAbstract::getClosureScopeClass' => ['ReflectionClass|null'],
'ReflectionFunctionAbstract::getClosureThis' => ['object|null'],
'ReflectionFunctionAbstract::getDocComment' => ['string|false'],
'ReflectionFunctionAbstract::getEndLine' => ['int|false'],
'ReflectionFunctionAbstract::getExtension' => ['ReflectionExtension'],
'ReflectionFunctionAbstract::getExtensionName' => ['string'],
'ReflectionFunctionAbstract::getFileName' => ['string|false'],
'ReflectionFunctionAbstract::getName' => ['string'],
'ReflectionFunctionAbstract::getNamespaceName' => ['string'],
'ReflectionFunctionAbstract::getNumberOfParameters' => ['int'],
'ReflectionFunctionAbstract::getNumberOfRequiredParameters' => ['int'],
'ReflectionFunctionAbstract::getParameters' => ['list<ReflectionParameter>'],
'ReflectionFunctionAbstract::getReturnType' => ['?ReflectionType'],
'ReflectionFunctionAbstract::getShortName' => ['string'],
'ReflectionFunctionAbstract::getStartLine' => ['int|false'],
'ReflectionFunctionAbstract::getStaticVariables' => ['array'],
'ReflectionFunctionAbstract::hasReturnType' => ['bool'],
'ReflectionFunctionAbstract::inNamespace' => ['bool'],
'ReflectionFunctionAbstract::isClosure' => ['bool'],
'ReflectionFunctionAbstract::isDeprecated' => ['bool'],
'ReflectionFunctionAbstract::isGenerator' => ['bool'],
'ReflectionFunctionAbstract::isInternal' => ['bool'],
'ReflectionFunctionAbstract::isUserDefined' => ['bool'],
'ReflectionFunctionAbstract::isVariadic' => ['bool'],
'ReflectionFunctionAbstract::returnsReference' => ['bool'],
'ReflectionGenerator::__construct' => ['void', 'generator'=>'object'],
'ReflectionGenerator::getExecutingFile' => ['string'],
'ReflectionGenerator::getExecutingGenerator' => ['Generator'],
'ReflectionGenerator::getExecutingLine' => ['int'],
'ReflectionGenerator::getFunction' => ['ReflectionFunctionAbstract'],
'ReflectionGenerator::getThis' => ['?object'],
'ReflectionGenerator::getTrace' => ['array', 'options='=>'int'],
'ReflectionMethod::__construct' => ['void', 'class'=>'class-string|object', 'name'=>'string'],
'ReflectionMethod::__construct\'1' => ['void', 'class_method'=>'string'],
'ReflectionMethod::__toString' => ['string'],
'ReflectionMethod::export' => ['?string', 'class'=>'string', 'name'=>'string', 'return='=>'bool'],
'ReflectionMethod::getClosure' => ['?Closure', 'object='=>'object'],
'ReflectionMethod::getClosureScopeClass' => ['ReflectionClass'],
'ReflectionMethod::getClosureThis' => ['object'],
'ReflectionMethod::getDeclaringClass' => ['ReflectionClass'],
'ReflectionMethod::getDocComment' => ['false|string'],
'ReflectionMethod::getEndLine' => ['false|int'],
'ReflectionMethod::getExtension' => ['ReflectionExtension'],
'ReflectionMethod::getExtensionName' => ['string'],
'ReflectionMethod::getFileName' => ['false|string'],
'ReflectionMethod::getModifiers' => ['int'],
'ReflectionMethod::getName' => ['string'],
'ReflectionMethod::getNamespaceName' => ['string'],
'ReflectionMethod::getNumberOfParameters' => ['int'],
'ReflectionMethod::getNumberOfRequiredParameters' => ['int'],
'ReflectionMethod::getParameters' => ['list<\ReflectionParameter>'],
'ReflectionMethod::getPrototype' => ['ReflectionMethod'],
'ReflectionMethod::getReturnType' => ['?ReflectionType'],
'ReflectionMethod::getShortName' => ['string'],
'ReflectionMethod::getStartLine' => ['false|int'],
'ReflectionMethod::getStaticVariables' => ['array'],
'ReflectionMethod::hasReturnType' => ['bool'],
'ReflectionMethod::inNamespace' => ['bool'],
'ReflectionMethod::invoke' => ['mixed', 'object'=>'?object', '...args='=>'mixed'],
'ReflectionMethod::invokeArgs' => ['mixed', 'object'=>'?object', 'args'=>'array'],
'ReflectionMethod::isAbstract' => ['bool'],
'ReflectionMethod::isClosure' => ['bool'],
'ReflectionMethod::isConstructor' => ['bool'],
'ReflectionMethod::isDeprecated' => ['bool'],
'ReflectionMethod::isDestructor' => ['bool'],
'ReflectionMethod::isFinal' => ['bool'],
'ReflectionMethod::isGenerator' => ['bool'],
'ReflectionMethod::isInternal' => ['bool'],
'ReflectionMethod::isPrivate' => ['bool'],
'ReflectionMethod::isProtected' => ['bool'],
'ReflectionMethod::isPublic' => ['bool'],
'ReflectionMethod::isStatic' => ['bool'],
'ReflectionMethod::isUserDefined' => ['bool'],
'ReflectionMethod::isVariadic' => ['bool'],
'ReflectionMethod::returnsReference' => ['bool'],
'ReflectionMethod::setAccessible' => ['void', 'visible'=>'bool'],
'ReflectionNamedType::__clone' => ['void'],
'ReflectionNamedType::__toString' => ['string'],
'ReflectionNamedType::allowsNull' => [''],
'ReflectionNamedType::getName' => ['string'],
'ReflectionNamedType::isBuiltin' => [''],
'ReflectionObject::__clone' => ['void'],
'ReflectionObject::__construct' => ['void', 'argument'=>'object'],
'ReflectionObject::__toString' => ['string'],
'ReflectionObject::export' => ['?string', 'argument'=>'object', 'return='=>'bool'],
'ReflectionObject::getConstant' => ['mixed', 'name'=>'string'],
'ReflectionObject::getConstants' => ['array<string,mixed>'],
'ReflectionObject::getConstructor' => ['?ReflectionMethod'],
'ReflectionObject::getDefaultProperties' => ['array'],
'ReflectionObject::getDocComment' => ['false|string'],
'ReflectionObject::getEndLine' => ['false|int'],
'ReflectionObject::getExtension' => ['?ReflectionExtension'],
'ReflectionObject::getExtensionName' => ['false|string'],
'ReflectionObject::getFileName' => ['false|string'],
'ReflectionObject::getInterfaceNames' => ['class-string[]'],
'ReflectionObject::getInterfaces' => ['array<string,\ReflectionClass>'],
'ReflectionObject::getMethod' => ['ReflectionMethod', 'name'=>'string'],
'ReflectionObject::getMethods' => ['ReflectionMethod[]', 'filter='=>'int'],
'ReflectionObject::getModifiers' => ['int'],
'ReflectionObject::getName' => ['string'],
'ReflectionObject::getNamespaceName' => ['string'],
'ReflectionObject::getParentClass' => ['ReflectionClass|false'],
'ReflectionObject::getProperties' => ['ReflectionProperty[]', 'filter='=>'int'],
'ReflectionObject::getProperty' => ['ReflectionProperty', 'name'=>'string'],
'ReflectionObject::getReflectionConstant' => ['ReflectionClassConstant', 'name'=>'string'],
'ReflectionObject::getReflectionConstants' => ['list<\ReflectionClassConstant>'],
'ReflectionObject::getShortName' => ['string'],
'ReflectionObject::getStartLine' => ['false|int'],
'ReflectionObject::getStaticProperties' => ['ReflectionProperty[]'],
'ReflectionObject::getStaticPropertyValue' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'ReflectionObject::getTraitAliases' => ['array<string,string>'],
'ReflectionObject::getTraitNames' => ['list<string>'],
'ReflectionObject::getTraits' => ['array<string,\ReflectionClass>'],
'ReflectionObject::hasConstant' => ['bool', 'name'=>'string'],
'ReflectionObject::hasMethod' => ['bool', 'name'=>'string'],
'ReflectionObject::hasProperty' => ['bool', 'name'=>'string'],
'ReflectionObject::implementsInterface' => ['bool', 'interface_name'=>'ReflectionClass|string'],
'ReflectionObject::inNamespace' => ['bool'],
'ReflectionObject::isAbstract' => ['bool'],
'ReflectionObject::isAnonymous' => ['bool'],
'ReflectionObject::isCloneable' => ['bool'],
'ReflectionObject::isFinal' => ['bool'],
'ReflectionObject::isInstance' => ['bool', 'object'=>'object'],
'ReflectionObject::isInstantiable' => ['bool'],
'ReflectionObject::isInterface' => ['bool'],
'ReflectionObject::isInternal' => ['bool'],
'ReflectionObject::isIterable' => ['bool'],
'ReflectionObject::isIterateable' => ['bool'],
'ReflectionObject::isSubclassOf' => ['bool', 'class'=>'ReflectionClass|string'],
'ReflectionObject::isTrait' => ['bool'],
'ReflectionObject::isUserDefined' => ['bool'],
'ReflectionObject::newInstance' => ['object', 'args='=>'mixed', '...args='=>'array'],
'ReflectionObject::newInstanceArgs' => ['object', 'args='=>'array'],
'ReflectionObject::newInstanceWithoutConstructor' => ['object'],
'ReflectionObject::setStaticPropertyValue' => ['void', 'name'=>'string', 'value'=>'string'],
'ReflectionParameter::__clone' => ['void'],
'ReflectionParameter::__construct' => ['void', 'function'=>'', 'parameter'=>''],
'ReflectionParameter::__toString' => ['string'],
'ReflectionParameter::allowsNull' => ['bool'],
'ReflectionParameter::canBePassedByValue' => ['bool'],
'ReflectionParameter::export' => ['?string', 'function'=>'string', 'parameter'=>'string', 'return='=>'bool'],
'ReflectionParameter::getClass' => ['?ReflectionClass'],
'ReflectionParameter::getDeclaringClass' => ['?ReflectionClass'],
'ReflectionParameter::getDeclaringFunction' => ['ReflectionFunctionAbstract'],
'ReflectionParameter::getDefaultValue' => ['mixed'],
'ReflectionParameter::getDefaultValueConstantName' => ['?string'],
'ReflectionParameter::getName' => ['string'],
'ReflectionParameter::getPosition' => ['int'],
'ReflectionParameter::getType' => ['?ReflectionType'],
'ReflectionParameter::hasType' => ['bool'],
'ReflectionParameter::isArray' => ['bool'],
'ReflectionParameter::isCallable' => ['?bool'],
'ReflectionParameter::isDefaultValueAvailable' => ['bool'],
'ReflectionParameter::isDefaultValueConstant' => ['bool'],
'ReflectionParameter::isOptional' => ['bool'],
'ReflectionParameter::isPassedByReference' => ['bool'],
'ReflectionParameter::isVariadic' => ['bool'],
'ReflectionProperty::__clone' => ['void'],
'ReflectionProperty::__construct' => ['void', 'class'=>'', 'name'=>'string'],
'ReflectionProperty::__toString' => ['string'],
'ReflectionProperty::export' => ['?string', 'class'=>'mixed', 'name'=>'string', 'return='=>'bool'],
'ReflectionProperty::getDeclaringClass' => ['ReflectionClass'],
'ReflectionProperty::getDocComment' => ['string|false'],
'ReflectionProperty::getModifiers' => ['int'],
'ReflectionProperty::getName' => ['string'],
'ReflectionProperty::getType' => ['?ReflectionType'],
'ReflectionProperty::getValue' => ['mixed', 'object='=>'object'],
'ReflectionProperty::isDefault' => ['bool'],
'ReflectionProperty::isPrivate' => ['bool'],
'ReflectionProperty::isProtected' => ['bool'],
'ReflectionProperty::isPublic' => ['bool'],
'ReflectionProperty::isStatic' => ['bool'],
'ReflectionProperty::setAccessible' => ['void', 'visible'=>'bool'],
'ReflectionProperty::setValue' => ['void', 'object'=>'null|object', 'value'=>''],
'ReflectionProperty::setValue\'1' => ['void', 'value'=>''],
'ReflectionType::__clone' => ['void'],
'ReflectionType::__toString' => ['string'],
'ReflectionType::allowsNull' => ['bool'],
'ReflectionType::getName' => ['string'],
'ReflectionType::isBuiltin' => ['bool'],
'ReflectionZendExtension::__clone' => ['void'],
'ReflectionZendExtension::__construct' => ['void', 'name'=>'string'],
'ReflectionZendExtension::__toString' => ['string'],
'ReflectionZendExtension::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionZendExtension::getAuthor' => ['string'],
'ReflectionZendExtension::getCopyright' => ['string'],
'ReflectionZendExtension::getName' => ['string'],
'ReflectionZendExtension::getURL' => ['string'],
'ReflectionZendExtension::getVersion' => ['string'],
'Reflector::__toString' => ['string'],
'Reflector::export' => ['?string'],
'RegexIterator::__construct' => ['void', 'iterator'=>'Iterator', 'regex'=>'string', 'mode='=>'int', 'flags='=>'int', 'preg_flags='=>'int'],
'RegexIterator::accept' => ['bool'],
'RegexIterator::current' => ['mixed'],
'RegexIterator::getFlags' => ['int'],
'RegexIterator::getInnerIterator' => ['Iterator'],
'RegexIterator::getMode' => ['int'],
'RegexIterator::getPregFlags' => ['int'],
'RegexIterator::getRegex' => ['string'],
'RegexIterator::key' => ['mixed'],
'RegexIterator::next' => ['void'],
'RegexIterator::rewind' => ['void'],
'RegexIterator::setFlags' => ['void', 'new_flags'=>'int'],
'RegexIterator::setMode' => ['void', 'new_mode'=>'int'],
'RegexIterator::setPregFlags' => ['void', 'new_flags'=>'int'],
'RegexIterator::valid' => ['bool'],
'register_event_handler' => ['bool', 'event_handler_func'=>'string', 'handler_register_name'=>'string', 'event_type_mask'=>'int'],
'register_shutdown_function' => ['void', 'callback'=>'callable', '...args='=>'mixed'],
'register_tick_function' => ['bool', 'callback'=>'callable():void', '...args='=>'mixed'],
'rename' => ['bool', 'from'=>'string', 'to'=>'string', 'context='=>'resource'],
'rename_function' => ['bool', 'original_name'=>'string', 'new_name'=>'string'],
'reset' => ['mixed|false', '&r_array'=>'array|object'],
'ResourceBundle::__construct' => ['void', 'locale'=>'string', 'bundlename'=>'string', 'fallback='=>'bool'],
'ResourceBundle::count' => ['int'],
'ResourceBundle::create' => ['?ResourceBundle', 'locale'=>'string', 'bundlename'=>'string', 'fallback='=>'bool'],
'ResourceBundle::get' => ['', 'index'=>'string|int', 'fallback='=>'bool'],
'ResourceBundle::getErrorCode' => ['int'],
'ResourceBundle::getErrorMessage' => ['string'],
'ResourceBundle::getLocales' => ['array', 'bundlename'=>'string'],
'resourcebundle_count' => ['int', 'bundle'=>'ResourceBundle'],
'resourcebundle_create' => ['?ResourceBundle', 'locale'=>'string', 'bundle'=>'string', 'fallback='=>'bool'],
'resourcebundle_get' => ['mixed|null', 'bundle'=>'ResourceBundle', 'index'=>'string|int', 'fallback='=>'bool'],
'resourcebundle_get_error_code' => ['int', 'bundle'=>'ResourceBundle'],
'resourcebundle_get_error_message' => ['string', 'bundle'=>'ResourceBundle'],
'resourcebundle_locales' => ['array', 'bundle'=>'string'],
'restore_error_handler' => ['true'],
'restore_exception_handler' => ['bool'],
'restore_include_path' => ['void'],
'rewind' => ['bool', 'stream'=>'resource'],
'rewinddir' => ['null|false', 'dir_handle='=>'resource'],
'rmdir' => ['bool', 'directory'=>'string', 'context='=>'resource'],
'round' => ['float', 'num'=>'float', 'precision='=>'int', 'mode='=>'int'],
'rpm_close' => ['bool', 'rpmr'=>'resource'],
'rpm_get_tag' => ['mixed', 'rpmr'=>'resource', 'tagnum'=>'int'],
'rpm_is_valid' => ['bool', 'filename'=>'string'],
'rpm_open' => ['resource|false', 'filename'=>'string'],
'rpm_version' => ['string'],
'rpmaddtag' => ['bool', 'tag'=>'int'],
'rpmdbinfo' => ['array', 'nevr'=>'string', 'full='=>'bool'],
'rpmdbsearch' => ['array', 'pattern'=>'string', 'rpmtag='=>'int', 'rpmmire='=>'int', 'full='=>'bool'],
'rpminfo' => ['array', 'path'=>'string', 'full='=>'bool', 'error='=>'string'],
'rpmvercmp' => ['int', 'evr1'=>'string', 'evr2'=>'string'],
'rrd_create' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_disconnect' => ['void'],
'rrd_error' => ['string'],
'rrd_fetch' => ['array', 'filename'=>'string', 'options'=>'array'],
'rrd_first' => ['int|false', 'file'=>'string', 'raaindex='=>'int'],
'rrd_graph' => ['array|false', 'filename'=>'string', 'options'=>'array'],
'rrd_info' => ['array|false', 'filename'=>'string'],
'rrd_last' => ['int', 'filename'=>'string'],
'rrd_lastupdate' => ['array|false', 'filename'=>'string'],
'rrd_restore' => ['bool', 'xml_file'=>'string', 'rrd_file'=>'string', 'options='=>'array'],
'rrd_tune' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_update' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_version' => ['string'],
'rrd_xport' => ['array|false', 'options'=>'array'],
'rrdc_disconnect' => ['void'],
'RRDCreator::__construct' => ['void', 'path'=>'string', 'starttime='=>'string', 'step='=>'int'],
'RRDCreator::addArchive' => ['void', 'description'=>'string'],
'RRDCreator::addDataSource' => ['void', 'description'=>'string'],
'RRDCreator::save' => ['bool'],
'RRDGraph::__construct' => ['void', 'path'=>'string'],
'RRDGraph::save' => ['array|false'],
'RRDGraph::saveVerbose' => ['array|false'],
'RRDGraph::setOptions' => ['void', 'options'=>'array'],
'RRDUpdater::__construct' => ['void', 'path'=>'string'],
'RRDUpdater::update' => ['bool', 'values'=>'array', 'time='=>'string'],
'rsort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'rtrim' => ['string', 'string'=>'string', 'characters='=>'string'],
'runkit7_constant_add' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'new_visibility='=>'int'],
'runkit7_constant_redefine' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'new_visibility='=>'?int'],
'runkit7_constant_remove' => ['bool', 'constant_name'=>'string'],
'runkit7_function_add' => ['bool', 'function_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_doc_comment='=>'?string', 'return_by_reference='=>'?bool', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_function_copy' => ['bool', 'source_name'=>'string', 'target_name'=>'string'],
'runkit7_function_redefine' => ['bool', 'function_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_doc_comment='=>'?string', 'return_by_reference='=>'?bool', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_function_remove' => ['bool', 'function_name'=>'string'],
'runkit7_function_rename' => ['bool', 'source_name'=>'string', 'target_name'=>'string'],
'runkit7_import' => ['bool', 'filename'=>'string', 'flags='=>'?int'],
'runkit7_method_add' => ['bool', 'class_name'=>'string', 'method_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_flags='=>'int|null|string', 'flags_or_doc_comment='=>'int|null|string', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_method_copy' => ['bool', 'destination_class'=>'string', 'destination_method'=>'string', 'source_class'=>'string', 'source_method='=>'?string'],
'runkit7_method_redefine' => ['bool', 'class_name'=>'string', 'method_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_flags='=>'int|null|string', 'flags_or_doc_comment='=>'int|null|string', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_method_remove' => ['bool', 'class_name'=>'string', 'method_name'=>'string'],
'runkit7_method_rename' => ['bool', 'class_name'=>'string', 'source_method_name'=>'string', 'source_target_name'=>'string'],
'runkit7_superglobals' => ['array'],
'runkit7_zval_inspect' => ['array', 'value'=>'mixed'],
'runkit_class_adopt' => ['bool', 'classname'=>'string', 'parentname'=>'string'],
'runkit_class_emancipate' => ['bool', 'classname'=>'string'],
'runkit_constant_add' => ['bool', 'constname'=>'string', 'value'=>'mixed'],
'runkit_constant_redefine' => ['bool', 'constname'=>'string', 'newvalue'=>'mixed'],
'runkit_constant_remove' => ['bool', 'constname'=>'string'],
'runkit_function_add' => ['bool', 'funcname'=>'string', 'arglist'=>'string', 'code'=>'string', 'doccomment='=>'?string'],
'runkit_function_add\'1' => ['bool', 'funcname'=>'string', 'closure'=>'Closure', 'doccomment='=>'?string'],
'runkit_function_copy' => ['bool', 'funcname'=>'string', 'targetname'=>'string'],
'runkit_function_redefine' => ['bool', 'funcname'=>'string', 'arglist'=>'string', 'code'=>'string', 'doccomment='=>'?string'],
'runkit_function_redefine\'1' => ['bool', 'funcname'=>'string', 'closure'=>'Closure', 'doccomment='=>'?string'],
'runkit_function_remove' => ['bool', 'funcname'=>'string'],
'runkit_function_rename' => ['bool', 'funcname'=>'string', 'newname'=>'string'],
'runkit_import' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'runkit_lint' => ['bool', 'code'=>'string'],
'runkit_lint_file' => ['bool', 'filename'=>'string'],
'runkit_method_add' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_add\'1' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'closure'=>'Closure', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_copy' => ['bool', 'dclass'=>'string', 'dmethod'=>'string', 'sclass'=>'string', 'smethod='=>'string'],
'runkit_method_redefine' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_redefine\'1' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'closure'=>'Closure', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_remove' => ['bool', 'classname'=>'string', 'methodname'=>'string'],
'runkit_method_rename' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'newname'=>'string'],
'runkit_return_value_used' => ['bool'],
'Runkit_Sandbox::__construct' => ['void', 'options='=>'array'],
'runkit_sandbox_output_handler' => ['mixed', 'sandbox'=>'object', 'callback='=>'mixed'],
'Runkit_Sandbox_Parent' => [''],
'Runkit_Sandbox_Parent::__construct' => ['void'],
'runkit_superglobals' => ['array'],
'runkit_zval_inspect' => ['array', 'value'=>'mixed'],
'RuntimeException::__clone' => ['void'],
'RuntimeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?RuntimeException'],
'RuntimeException::__toString' => ['string'],
'RuntimeException::getCode' => ['int'],
'RuntimeException::getFile' => ['string'],
'RuntimeException::getLine' => ['int'],
'RuntimeException::getMessage' => ['string'],
'RuntimeException::getPrevious' => ['Throwable|RuntimeException|null'],
'RuntimeException::getTrace' => ['list<array<string,mixed>>'],
'RuntimeException::getTraceAsString' => ['string'],
'SAMConnection::commit' => ['bool'],
'SAMConnection::connect' => ['bool', 'protocol'=>'string', 'properties='=>'array'],
'SAMConnection::disconnect' => ['bool'],
'SAMConnection::errno' => ['int'],
'SAMConnection::error' => ['string'],
'SAMConnection::isConnected' => ['bool'],
'SAMConnection::peek' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::peekAll' => ['array', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::receive' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::remove' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::rollback' => ['bool'],
'SAMConnection::send' => ['string', 'target'=>'string', 'msg'=>'sammessage', 'properties='=>'array'],
'SAMConnection::setDebug' => ['', 'switch'=>'bool'],
'SAMConnection::subscribe' => ['string', 'targettopic'=>'string'],
'SAMConnection::unsubscribe' => ['bool', 'subscriptionid'=>'string', 'targettopic='=>'string'],
'SAMMessage::body' => ['string'],
'SAMMessage::header' => ['object'],
'sapi_windows_cp_conv' => ['string', 'in_codepage'=>'int|string', 'out_codepage'=>'int|string', 'subject'=>'string'],
'sapi_windows_cp_get' => ['int'],
'sapi_windows_cp_is_utf8' => ['bool'],
'sapi_windows_cp_set' => ['bool', 'codepage'=>'int'],
'sapi_windows_vt100_support' => ['bool', 'stream'=>'resource', 'enable='=>'bool'],
'Saxon\SaxonProcessor::__construct' => ['void', 'license='=>'bool', 'cwd='=>'string'],
'Saxon\SaxonProcessor::createAtomicValue' => ['Saxon\XdmValue', 'primitive_type_val'=>'bool|float|int|string'],
'Saxon\SaxonProcessor::newSchemaValidator' => ['Saxon\SchemaValidator'],
'Saxon\SaxonProcessor::newXPathProcessor' => ['Saxon\XPathProcessor'],
'Saxon\SaxonProcessor::newXQueryProcessor' => ['Saxon\XQueryProcessor'],
'Saxon\SaxonProcessor::newXsltProcessor' => ['Saxon\XsltProcessor'],
'Saxon\SaxonProcessor::parseXmlFromFile' => ['Saxon\XdmNode', 'fileName'=>'string'],
'Saxon\SaxonProcessor::parseXmlFromString' => ['Saxon\XdmNode', 'value'=>'string'],
'Saxon\SaxonProcessor::registerPHPFunctions' => ['void', 'library'=>'string'],
'Saxon\SaxonProcessor::setConfigurationProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\SaxonProcessor::setcwd' => ['void', 'cwd'=>'string'],
'Saxon\SaxonProcessor::setResourceDirectory' => ['void', 'dir'=>'string'],
'Saxon\SaxonProcessor::version' => ['string'],
'Saxon\SchemaValidator::clearParameters' => ['void'],
'Saxon\SchemaValidator::clearProperties' => ['void'],
'Saxon\SchemaValidator::exceptionClear' => ['void'],
'Saxon\SchemaValidator::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\SchemaValidator::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\SchemaValidator::getExceptionCount' => ['int'],
'Saxon\SchemaValidator::getValidationReport' => ['Saxon\XdmNode'],
'Saxon\SchemaValidator::registerSchemaFromFile' => ['void', 'fileName'=>'string'],
'Saxon\SchemaValidator::registerSchemaFromString' => ['void', 'schemaStr'=>'string'],
'Saxon\SchemaValidator::setOutputFile' => ['void', 'fileName'=>'string'],
'Saxon\SchemaValidator::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\SchemaValidator::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\SchemaValidator::setSourceNode' => ['void', 'node'=>'Saxon\XdmNode'],
'Saxon\SchemaValidator::validate' => ['void', 'filename='=>'?string'],
'Saxon\SchemaValidator::validateToNode' => ['Saxon\XdmNode', 'filename='=>'?string'],
'Saxon\XdmAtomicValue::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmAtomicValue::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmAtomicValue::getBooleanValue' => ['bool'],
'Saxon\XdmAtomicValue::getDoubleValue' => ['float'],
'Saxon\XdmAtomicValue::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmAtomicValue::getLongValue' => ['int'],
'Saxon\XdmAtomicValue::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmAtomicValue::getStringValue' => ['string'],
'Saxon\XdmAtomicValue::isAtomic' => ['true'],
'Saxon\XdmAtomicValue::isNode' => ['bool'],
'Saxon\XdmAtomicValue::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmAtomicValue::size' => ['int'],
'Saxon\XdmItem::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmItem::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmItem::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmItem::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmItem::getStringValue' => ['string'],
'Saxon\XdmItem::isAtomic' => ['bool'],
'Saxon\XdmItem::isNode' => ['bool'],
'Saxon\XdmItem::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmItem::size' => ['int'],
'Saxon\XdmNode::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmNode::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmNode::getAttributeCount' => ['int'],
'Saxon\XdmNode::getAttributeNode' => ['?Saxon\XdmNode', 'index'=>'int'],
'Saxon\XdmNode::getAttributeValue' => ['?string', 'index'=>'int'],
'Saxon\XdmNode::getChildCount' => ['int'],
'Saxon\XdmNode::getChildNode' => ['?Saxon\XdmNode', 'index'=>'int'],
'Saxon\XdmNode::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmNode::getNodeKind' => ['int'],
'Saxon\XdmNode::getNodeName' => ['string'],
'Saxon\XdmNode::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmNode::getParent' => ['?Saxon\XdmNode'],
'Saxon\XdmNode::getStringValue' => ['string'],
'Saxon\XdmNode::isAtomic' => ['false'],
'Saxon\XdmNode::isNode' => ['bool'],
'Saxon\XdmNode::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmNode::size' => ['int'],
'Saxon\XdmValue::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmValue::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmValue::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmValue::size' => ['int'],
'Saxon\XPathProcessor::clearParameters' => ['void'],
'Saxon\XPathProcessor::clearProperties' => ['void'],
'Saxon\XPathProcessor::declareNamespace' => ['void', 'prefix'=>'', 'namespace'=>''],
'Saxon\XPathProcessor::effectiveBooleanValue' => ['bool', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::evaluate' => ['Saxon\XdmValue', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::evaluateSingle' => ['Saxon\XdmItem', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::exceptionClear' => ['void'],
'Saxon\XPathProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XPathProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XPathProcessor::getExceptionCount' => ['int'],
'Saxon\XPathProcessor::setBaseURI' => ['void', 'uri'=>'string'],
'Saxon\XPathProcessor::setContextFile' => ['void', 'fileName'=>'string'],
'Saxon\XPathProcessor::setContextItem' => ['void', 'item'=>'Saxon\XdmItem'],
'Saxon\XPathProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XPathProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XQueryProcessor::clearParameters' => ['void'],
'Saxon\XQueryProcessor::clearProperties' => ['void'],
'Saxon\XQueryProcessor::declareNamespace' => ['void', 'prefix'=>'string', 'namespace'=>'string'],
'Saxon\XQueryProcessor::exceptionClear' => ['void'],
'Saxon\XQueryProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XQueryProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XQueryProcessor::getExceptionCount' => ['int'],
'Saxon\XQueryProcessor::runQueryToFile' => ['void', 'outfilename'=>'string'],
'Saxon\XQueryProcessor::runQueryToString' => ['?string'],
'Saxon\XQueryProcessor::runQueryToValue' => ['?Saxon\XdmValue'],
'Saxon\XQueryProcessor::setContextItem' => ['void', 'object'=>'Saxon\XdmAtomicValue|Saxon\XdmItem|Saxon\XdmNode|Saxon\XdmValue'],
'Saxon\XQueryProcessor::setContextItemFromFile' => ['void', 'fileName'=>'string'],
'Saxon\XQueryProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XQueryProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XQueryProcessor::setQueryBaseURI' => ['void', 'uri'=>'string'],
'Saxon\XQueryProcessor::setQueryContent' => ['void', 'string'=>'string'],
'Saxon\XQueryProcessor::setQueryFile' => ['void', 'filename'=>'string'],
'Saxon\XQueryProcessor::setQueryItem' => ['void', 'item'=>'Saxon\XdmItem'],
'Saxon\XsltProcessor::clearParameters' => ['void'],
'Saxon\XsltProcessor::clearProperties' => ['void'],
'Saxon\XsltProcessor::compileFromFile' => ['void', 'fileName'=>'string'],
'Saxon\XsltProcessor::compileFromString' => ['void', 'string'=>'string'],
'Saxon\XsltProcessor::compileFromValue' => ['void', 'node'=>'Saxon\XdmNode'],
'Saxon\XsltProcessor::exceptionClear' => ['void'],
'Saxon\XsltProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XsltProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XsltProcessor::getExceptionCount' => ['int'],
'Saxon\XsltProcessor::setOutputFile' => ['void', 'fileName'=>'string'],
'Saxon\XsltProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XsltProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XsltProcessor::setSourceFromFile' => ['void', 'filename'=>'string'],
'Saxon\XsltProcessor::setSourceFromXdmValue' => ['void', 'value'=>'Saxon\XdmValue'],
'Saxon\XsltProcessor::transformFileToFile' => ['void', 'sourceFileName'=>'string', 'stylesheetFileName'=>'string', 'outputfileName'=>'string'],
'Saxon\XsltProcessor::transformFileToString' => ['?string', 'sourceFileName'=>'string', 'stylesheetFileName'=>'string'],
'Saxon\XsltProcessor::transformFileToValue' => ['Saxon\XdmValue', 'fileName'=>'string'],
'Saxon\XsltProcessor::transformToFile' => ['void'],
'Saxon\XsltProcessor::transformToString' => ['string'],
'Saxon\XsltProcessor::transformToValue' => ['?Saxon\XdmValue'],
'SCA::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SCA::getService' => ['', 'target'=>'string', 'binding='=>'string', 'config='=>'array'],
'SCA_LocalProxy::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SCA_SoapProxy::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'scalebarObj::convertToString' => ['string'],
'scalebarObj::free' => ['void'],
'scalebarObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'scalebarObj::setImageColor' => ['int', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'scalebarObj::updateFromString' => ['int', 'snippet'=>'string'],
'scandir' => ['list<string>|false', 'directory'=>'string', 'sorting_order='=>'int', 'context='=>'resource'],
'SDO_DAS_ChangeSummary::beginLogging' => [''],
'SDO_DAS_ChangeSummary::endLogging' => [''],
'SDO_DAS_ChangeSummary::getChangedDataObjects' => ['SDO_List'],
'SDO_DAS_ChangeSummary::getChangeType' => ['int', 'dataobject'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::getOldContainer' => ['SDO_DataObject', 'data_object'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::getOldValues' => ['SDO_List', 'data_object'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::isLogging' => ['bool'],
'SDO_DAS_DataFactory::addPropertyToType' => ['', 'parent_type_namespace_uri'=>'string', 'parent_type_name'=>'string', 'property_name'=>'string', 'type_namespace_uri'=>'string', 'type_name'=>'string', 'options='=>'array'],
'SDO_DAS_DataFactory::addType' => ['', 'type_namespace_uri'=>'string', 'type_name'=>'string', 'options='=>'array'],
'SDO_DAS_DataFactory::getDataFactory' => ['SDO_DAS_DataFactory'],
'SDO_DAS_DataObject::getChangeSummary' => ['SDO_DAS_ChangeSummary'],
'SDO_DAS_Relational::__construct' => ['void', 'database_metadata'=>'array', 'application_root_type='=>'string', 'sdo_containment_references_metadata='=>'array'],
'SDO_DAS_Relational::applyChanges' => ['', 'database_handle'=>'pdo', 'root_data_object'=>'sdodataobject'],
'SDO_DAS_Relational::createRootDataObject' => ['SDODataObject'],
'SDO_DAS_Relational::executePreparedQuery' => ['SDODataObject', 'database_handle'=>'pdo', 'prepared_statement'=>'pdostatement', 'value_list'=>'array', 'column_specifier='=>'array'],
'SDO_DAS_Relational::executeQuery' => ['SDODataObject', 'database_handle'=>'pdo', 'sql_statement'=>'string', 'column_specifier='=>'array'],
'SDO_DAS_Setting::getListIndex' => ['int'],
'SDO_DAS_Setting::getPropertyIndex' => ['int'],
'SDO_DAS_Setting::getPropertyName' => ['string'],
'SDO_DAS_Setting::getValue' => [''],
'SDO_DAS_Setting::isSet' => ['bool'],
'SDO_DAS_XML::addTypes' => ['', 'xsd_file'=>'string'],
'SDO_DAS_XML::create' => ['SDO_DAS_XML', 'xsd_file='=>'mixed', 'key='=>'string'],
'SDO_DAS_XML::createDataObject' => ['SDO_DataObject', 'namespace_uri'=>'string', 'type_name'=>'string'],
'SDO_DAS_XML::createDocument' => ['SDO_DAS_XML_Document', 'document_element_name'=>'string', 'document_element_namespace_uri'=>'string', 'dataobject='=>'sdo_dataobject'],
'SDO_DAS_XML::loadFile' => ['SDO_XMLDocument', 'xml_file'=>'string'],
'SDO_DAS_XML::loadString' => ['SDO_DAS_XML_Document', 'xml_string'=>'string'],
'SDO_DAS_XML::saveFile' => ['', 'xdoc'=>'sdo_xmldocument', 'xml_file'=>'string', 'indent='=>'int'],
'SDO_DAS_XML::saveString' => ['string', 'xdoc'=>'sdo_xmldocument', 'indent='=>'int'],
'SDO_DAS_XML_Document::getRootDataObject' => ['SDO_DataObject'],
'SDO_DAS_XML_Document::getRootElementName' => ['string'],
'SDO_DAS_XML_Document::getRootElementURI' => ['string'],
'SDO_DAS_XML_Document::setEncoding' => ['', 'encoding'=>'string'],
'SDO_DAS_XML_Document::setXMLDeclaration' => ['', 'xmldeclatation'=>'bool'],
'SDO_DAS_XML_Document::setXMLVersion' => ['', 'xmlversion'=>'string'],
'SDO_DataFactory::create' => ['void', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SDO_DataObject::clear' => ['void'],
'SDO_DataObject::createDataObject' => ['SDO_DataObject', 'identifier'=>''],
'SDO_DataObject::getContainer' => ['SDO_DataObject'],
'SDO_DataObject::getSequence' => ['SDO_Sequence'],
'SDO_DataObject::getTypeName' => ['string'],
'SDO_DataObject::getTypeNamespaceURI' => ['string'],
'SDO_Exception::getCause' => [''],
'SDO_List::insert' => ['void', 'value'=>'mixed', 'index='=>'int'],
'SDO_Model_Property::getContainingType' => ['SDO_Model_Type'],
'SDO_Model_Property::getDefault' => [''],
'SDO_Model_Property::getName' => ['string'],
'SDO_Model_Property::getType' => ['SDO_Model_Type'],
'SDO_Model_Property::isContainment' => ['bool'],
'SDO_Model_Property::isMany' => ['bool'],
'SDO_Model_ReflectionDataObject::__construct' => ['void', 'data_object'=>'sdo_dataobject'],
'SDO_Model_ReflectionDataObject::export' => ['mixed', 'rdo'=>'sdo_model_reflectiondataobject', 'return='=>'bool'],
'SDO_Model_ReflectionDataObject::getContainmentProperty' => ['SDO_Model_Property'],
'SDO_Model_ReflectionDataObject::getInstanceProperties' => ['array'],
'SDO_Model_ReflectionDataObject::getType' => ['SDO_Model_Type'],
'SDO_Model_Type::getBaseType' => ['SDO_Model_Type'],
'SDO_Model_Type::getName' => ['string'],
'SDO_Model_Type::getNamespaceURI' => ['string'],
'SDO_Model_Type::getProperties' => ['array'],
'SDO_Model_Type::getProperty' => ['SDO_Model_Property', 'identifier'=>''],
'SDO_Model_Type::isAbstractType' => ['bool'],
'SDO_Model_Type::isDataType' => ['bool'],
'SDO_Model_Type::isInstance' => ['bool', 'data_object'=>'sdo_dataobject'],
'SDO_Model_Type::isOpenType' => ['bool'],
'SDO_Model_Type::isSequencedType' => ['bool'],
'SDO_Sequence::getProperty' => ['SDO_Model_Property', 'sequence_index'=>'int'],
'SDO_Sequence::insert' => ['void', 'value'=>'mixed', 'sequenceindex='=>'int', 'propertyidentifier='=>'mixed'],
'SDO_Sequence::move' => ['void', 'toindex'=>'int', 'fromindex'=>'int'],
'SeasLog::__destruct' => ['void'],
'SeasLog::alert' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::analyzerCount' => ['mixed', 'level'=>'string', 'log_path='=>'string', 'key_word='=>'string'],
'SeasLog::analyzerDetail' => ['mixed', 'level'=>'string', 'log_path='=>'string', 'key_word='=>'string', 'start='=>'int', 'limit='=>'int', 'order='=>'int'],
'SeasLog::closeLoggerStream' => ['bool', 'model'=>'int', 'logger'=>'string'],
'SeasLog::critical' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::debug' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::emergency' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::error' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::flushBuffer' => ['bool'],
'SeasLog::getBasePath' => ['string'],
'SeasLog::getBuffer' => ['array'],
'SeasLog::getBufferEnabled' => ['bool'],
'SeasLog::getDatetimeFormat' => ['string'],
'SeasLog::getLastLogger' => ['string'],
'SeasLog::getRequestID' => ['string'],
'SeasLog::getRequestVariable' => ['bool', 'key'=>'int'],
'SeasLog::info' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::log' => ['bool', 'level'=>'string', 'message='=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::notice' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::setBasePath' => ['bool', 'base_path'=>'string'],
'SeasLog::setDatetimeFormat' => ['bool', 'format'=>'string'],
'SeasLog::setLogger' => ['bool', 'logger'=>'string'],
'SeasLog::setRequestID' => ['bool', 'request_id'=>'string'],
'SeasLog::setRequestVariable' => ['bool', 'key'=>'int', 'value'=>'string'],
'SeasLog::warning' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'seaslog_get_author' => ['string'],
'seaslog_get_version' => ['string'],
'SeekableIterator::__construct' => ['void'],
'SeekableIterator::current' => ['mixed'],
'SeekableIterator::key' => ['int|string'],
'SeekableIterator::next' => ['void'],
'SeekableIterator::rewind' => ['void'],
'SeekableIterator::seek' => ['void', 'position'=>'int'],
'SeekableIterator::valid' => ['bool'],
'sem_acquire' => ['bool', 'semaphore'=>'resource', 'non_blocking='=>'bool'],
'sem_get' => ['resource|false', 'key'=>'int', 'max_acquire='=>'int', 'permissions='=>'int', 'auto_release='=>'int'],
'sem_release' => ['bool', 'semaphore'=>'resource'],
'sem_remove' => ['bool', 'semaphore'=>'resource'],
'Serializable::__construct' => ['void'],
'Serializable::serialize' => ['?string'],
'Serializable::unserialize' => ['void', 'serialized'=>'string'],
'serialize' => ['string', 'value'=>'mixed'],
'ServerRequest::withInput' => ['ServerRequest', 'input'=>'mixed'],
'ServerRequest::withoutParams' => ['ServerRequest', 'params'=>'int|string'],
'ServerRequest::withParam' => ['ServerRequest', 'key'=>'int|string', 'value'=>'mixed'],
'ServerRequest::withParams' => ['ServerRequest', 'params'=>'mixed'],
'ServerRequest::withUrl' => ['ServerRequest', 'url'=>'array'],
'ServerResponse::addHeader' => ['void', 'label'=>'string', 'value'=>'string'],
'ServerResponse::date' => ['string', 'date'=>'string|DateTimeInterface'],
'ServerResponse::getHeader' => ['string', 'label'=>'string'],
'ServerResponse::getHeaders' => ['string[]'],
'ServerResponse::getStatus' => ['int'],
'ServerResponse::getVersion' => ['string'],
'ServerResponse::setHeader' => ['void', 'label'=>'string', 'value'=>'string'],
'ServerResponse::setStatus' => ['void', 'status'=>'int'],
'ServerResponse::setVersion' => ['void', 'version'=>'string'],
'session_abort' => ['bool'],
'session_cache_expire' => ['int', 'value='=>'int'],
'session_cache_limiter' => ['string', 'value='=>'string'],
'session_commit' => ['bool'],
'session_create_id' => ['string', 'prefix='=>'string'],
'session_decode' => ['bool', 'data'=>'string'],
'session_destroy' => ['bool'],
'session_encode' => ['string'],
'session_gc' => ['int|false'],
'session_get_cookie_params' => ['array'],
'session_id' => ['string', 'id='=>'string'],
'session_is_registered' => ['bool', 'name'=>'string'],
'session_module_name' => ['string', 'module='=>'string'],
'session_name' => ['string|false', 'name='=>'string'],
'session_pgsql_add_error' => ['bool', 'error_level'=>'int', 'error_message='=>'string'],
'session_pgsql_get_error' => ['array', 'with_error_message='=>'bool'],
'session_pgsql_get_field' => ['string'],
'session_pgsql_reset' => ['bool'],
'session_pgsql_set_field' => ['bool', 'value'=>'string'],
'session_pgsql_status' => ['array'],
'session_regenerate_id' => ['bool', 'delete_old_session='=>'bool'],
'session_register' => ['bool', 'name'=>'mixed', '...args='=>'mixed'],
'session_register_shutdown' => ['void'],
'session_reset' => ['bool'],
'session_save_path' => ['string', 'path='=>'string'],
'session_set_cookie_params' => ['bool', 'lifetime_or_options'=>'int', 'path='=>'string', 'domain='=>'?string', 'secure='=>'bool', 'httponly='=>'bool'],
'session_set_cookie_params\'1' => ['bool', 'lifetime_or_options'=>'array{lifetime?:int,path?:string,domain?:?string,secure?:bool,httponly?:bool}'],
'session_set_save_handler' => ['bool', 'open'=>'callable(string,string):bool', 'close'=>'callable():bool', 'read'=>'callable(string):string', 'write'=>'callable(string,string):bool', 'destroy'=>'callable(string):bool', 'gc'=>'callable(string):bool', 'create_sid='=>'callable():string', 'validate_sid='=>'callable(string):bool', 'update_timestamp='=>'callable(string):bool'],
'session_set_save_handler\'1' => ['bool', 'open'=>'SessionHandlerInterface', 'close='=>'bool'],
'session_start' => ['bool', 'options='=>'array'],
'session_status' => ['int'],
'session_unregister' => ['bool', 'name'=>'string'],
'session_unset' => ['bool'],
'session_write_close' => ['bool'],
'SessionHandler::close' => ['bool'],
'SessionHandler::create_sid' => ['char'],
'SessionHandler::destroy' => ['bool', 'id'=>'string'],
'SessionHandler::gc' => ['bool', 'maxlifetime'=>'int'],
'SessionHandler::open' => ['bool', 'save_path'=>'string', 'session_name'=>'string'],
'SessionHandler::read' => ['string', 'id'=>'string'],
'SessionHandler::updateTimestamp' => ['bool', 'session_id'=>'string', 'session_data'=>'string'],
'SessionHandler::validateId' => ['bool', 'session_id'=>'string'],
'SessionHandler::write' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionHandlerInterface::close' => ['bool'],
'SessionHandlerInterface::destroy' => ['bool', 'session_id'=>'string'],
'SessionHandlerInterface::gc' => ['bool', 'maxlifetime'=>'int'],
'SessionHandlerInterface::open' => ['bool', 'save_path'=>'string', 'name'=>'string'],
'SessionHandlerInterface::read' => ['string', 'session_id'=>'string'],
'SessionHandlerInterface::write' => ['bool', 'session_id'=>'string', 'session_data'=>'string'],
'SessionIdInterface::create_sid' => ['string'],
'SessionUpdateTimestampHandler::updateTimestamp' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionUpdateTimestampHandler::validateId' => ['char', 'id'=>'string'],
'SessionUpdateTimestampHandlerInterface::updateTimestamp' => ['bool', 'key'=>'string', 'value'=>'string'],
'SessionUpdateTimestampHandlerInterface::validateId' => ['bool', 'key'=>'string'],
'set_error_handler' => ['null|callable(int,string,string=,int=,array=):bool', 'callback'=>'null|callable(int,string,string=,int=,array=):bool', 'error_levels='=>'int'],
'set_exception_handler' => ['null|callable(Throwable):void', 'callback'=>'null|callable(Throwable):void'],
'set_file_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'set_include_path' => ['string|false', 'include_path'=>'string'],
'set_magic_quotes_runtime' => ['bool', 'new_setting'=>'bool'],
'set_time_limit' => ['bool', 'seconds'=>'int'],
'setcookie' => ['bool', 'name'=>'string', 'value='=>'string', 'expires_or_options='=>'int', 'path='=>'string', 'domain='=>'string', 'secure='=>'bool', 'httponly='=>'bool', 'samesite='=>'string', 'url_encode='=>'int'],
'setcookie\'1' => ['bool', 'name'=>'string', 'value='=>'string', 'expires_or_options='=>'array'],
'setLeftFill' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setLine' => ['void', 'width'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setlocale' => ['string|false', 'category'=>'int', 'locales'=>'string|0|null', '...rest='=>'string'],
'setlocale\'1' => ['string|false', 'category'=>'int', 'locales'=>'?array'],
'setproctitle' => ['void', 'title'=>'string'],
'setrawcookie' => ['bool', 'name'=>'string', 'value='=>'string', 'expires_or_options='=>'int', 'path='=>'string', 'domain='=>'string', 'secure='=>'bool', 'httponly='=>'bool'],
'setRightFill' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setthreadtitle' => ['bool', 'title'=>'string'],
'settype' => ['bool', '&rw_var'=>'mixed', 'type'=>'string'],
'sha1' => ['string', 'string'=>'string', 'binary='=>'bool'],
'sha1_file' => ['string|false', 'filename'=>'string', 'binary='=>'bool'],
'sha256' => ['string', 'string'=>'string', 'raw_output='=>'bool'],
'sha256_file' => ['string', 'filename'=>'string', 'raw_output='=>'bool'],
'shapefileObj::__construct' => ['void', 'filename'=>'string', 'type'=>'int'],
'shapefileObj::addPoint' => ['int', 'point'=>'pointObj'],
'shapefileObj::addShape' => ['int', 'shape'=>'shapeObj'],
'shapefileObj::free' => ['void'],
'shapefileObj::getExtent' => ['rectObj', 'i'=>'int'],
'shapefileObj::getPoint' => ['shapeObj', 'i'=>'int'],
'shapefileObj::getShape' => ['shapeObj', 'i'=>'int'],
'shapefileObj::getTransformed' => ['shapeObj', 'map'=>'mapObj', 'i'=>'int'],
'shapefileObj::ms_newShapefileObj' => ['shapefileObj', 'filename'=>'string', 'type'=>'int'],
'shapeObj::__construct' => ['void', 'type'=>'int'],
'shapeObj::add' => ['int', 'line'=>'lineObj'],
'shapeObj::boundary' => ['shapeObj'],
'shapeObj::contains' => ['bool', 'point'=>'pointObj'],
'shapeObj::containsShape' => ['int', 'shape2'=>'shapeObj'],
'shapeObj::convexhull' => ['shapeObj'],
'shapeObj::crosses' => ['int', 'shape'=>'shapeObj'],
'shapeObj::difference' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::disjoint' => ['int', 'shape'=>'shapeObj'],
'shapeObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj'],
'shapeObj::equals' => ['int', 'shape'=>'shapeObj'],
'shapeObj::free' => ['void'],
'shapeObj::getArea' => ['float'],
'shapeObj::getCentroid' => ['pointObj'],
'shapeObj::getLabelPoint' => ['pointObj'],
'shapeObj::getLength' => ['float'],
'shapeObj::getPointUsingMeasure' => ['pointObj', 'm'=>'float'],
'shapeObj::getValue' => ['string', 'layer'=>'layerObj', 'filedname'=>'string'],
'shapeObj::intersection' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::intersects' => ['bool', 'shape'=>'shapeObj'],
'shapeObj::line' => ['lineObj', 'i'=>'int'],
'shapeObj::ms_shapeObjFromWkt' => ['shapeObj', 'wkt'=>'string'],
'shapeObj::overlaps' => ['int', 'shape'=>'shapeObj'],
'shapeObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'shapeObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'shapeObj::setBounds' => ['int'],
'shapeObj::simplify' => ['shapeObj|null', 'tolerance'=>'float'],
'shapeObj::symdifference' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::topologyPreservingSimplify' => ['shapeObj|null', 'tolerance'=>'float'],
'shapeObj::touches' => ['int', 'shape'=>'shapeObj'],
'shapeObj::toWkt' => ['string'],
'shapeObj::union' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::within' => ['int', 'shape2'=>'shapeObj'],
'shell_exec' => ['?string', 'command'=>'string'],
'shm_attach' => ['resource', 'key'=>'int', 'size='=>'int', 'permissions='=>'int'],
'shm_detach' => ['bool', 'shm'=>'resource'],
'shm_get_var' => ['mixed', 'shm'=>'resource', 'key'=>'int'],
'shm_has_var' => ['bool', 'shm'=>'resource', 'key'=>'int'],
'shm_put_var' => ['bool', 'shm'=>'resource', 'key'=>'int', 'value'=>'mixed'],
'shm_remove' => ['bool', 'shm'=>'resource'],
'shm_remove_var' => ['bool', 'shm'=>'resource', 'key'=>'int'],
'shmop_close' => ['void', 'shmop'=>'resource'],
'shmop_delete' => ['bool', 'shmop'=>'resource'],
'shmop_open' => ['resource|false', 'key'=>'int', 'mode'=>'string', 'permissions'=>'int', 'size'=>'int'],
'shmop_read' => ['string|false', 'shmop'=>'resource', 'offset'=>'int', 'size'=>'int'],
'shmop_size' => ['int', 'shmop'=>'resource'],
'shmop_write' => ['int|false', 'shmop'=>'resource', 'data'=>'string', 'offset'=>'int'],
'show_source' => ['string|bool', 'filename'=>'string', 'return='=>'bool'],
'shuffle' => ['bool', '&rw_array'=>'array'],
'signeurlpaiement' => ['string', 'clent'=>'string', 'data'=>'string'],
'similar_text' => ['int', 'string1'=>'string', 'string2'=>'string', '&w_percent='=>'float'],
'simplexml_import_dom' => ['SimpleXMLElement|false', 'node'=>'DOMNode', 'class_name='=>'string'],
'simplexml_load_file' => ['SimpleXMLElement|false', 'filename'=>'string', 'class_name='=>'string', 'options='=>'int', 'namespace_or_prefix='=>'string', 'is_prefix='=>'bool'],
'simplexml_load_string' => ['SimpleXMLElement|false', 'data'=>'string', 'class_name='=>'string', 'options='=>'int', 'namespace_or_prefix='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::__construct' => ['void', 'data'=>'string', 'options='=>'int', 'data_is_url='=>'bool', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::__get' => ['SimpleXMLElement', 'name'=>'string'],
'SimpleXMLElement::__toString' => ['string'],
'SimpleXMLElement::addAttribute' => ['void', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLElement::addChild' => ['SimpleXMLElement', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLElement::asXML' => ['bool', 'filename'=>'string'],
'SimpleXMLElement::asXML\'1' => ['string|false'],
'SimpleXMLElement::attributes' => ['?SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::children' => ['SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::count' => ['int'],
'SimpleXMLElement::getDocNamespaces' => ['string[]', 'recursive='=>'bool', 'from_root='=>'bool'],
'SimpleXMLElement::getName' => ['string'],
'SimpleXMLElement::getNamespaces' => ['string[]', 'recursive='=>'bool'],
'SimpleXMLElement::offsetExists' => ['bool', 'offset'=>'int|string'],
'SimpleXMLElement::offsetGet' => ['SimpleXMLElement', 'offset'=>'int|string'],
'SimpleXMLElement::offsetSet' => ['void', 'offset'=>'int|string', 'value'=>'mixed'],
'SimpleXMLElement::offsetUnset' => ['void', 'offset'=>'int|string'],
'SimpleXMLElement::registerXPathNamespace' => ['bool', 'prefix'=>'string', 'ns'=>'string'],
'SimpleXMLElement::saveXML' => ['mixed', 'filename='=>'string'],
'SimpleXMLElement::xpath' => ['SimpleXMLElement[]|false', 'path'=>'string'],
'SimpleXMLIterator::__construct' => ['void', 'data'=>'string', 'options='=>'int', 'data_is_url='=>'bool', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLIterator::__toString' => ['string'],
'SimpleXMLIterator::addAttribute' => ['void', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLIterator::addChild' => ['SimpleXMLElement', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLIterator::asXML' => ['bool|string', 'filename='=>'string'],
'SimpleXMLIterator::attributes' => ['?SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLIterator::children' => ['SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLIterator::count' => ['int'],
'SimpleXMLIterator::current' => ['?SimpleXMLIterator'],
'SimpleXMLIterator::getChildren' => ['SimpleXMLIterator'],
'SimpleXMLIterator::getDocNamespaces' => ['string[]', 'recursive='=>'bool', 'from_root='=>'bool'],
'SimpleXMLIterator::getName' => ['string'],
'SimpleXMLIterator::getNamespaces' => ['string[]', 'recursive='=>'bool'],
'SimpleXMLIterator::hasChildren' => ['bool'],
'SimpleXMLIterator::key' => ['string|false'],
'SimpleXMLIterator::next' => ['void'],
'SimpleXMLIterator::registerXPathNamespace' => ['bool', 'prefix'=>'string', 'ns'=>'string'],
'SimpleXMLIterator::rewind' => ['void'],
'SimpleXMLIterator::saveXML' => ['mixed', 'filename='=>'string'],
'SimpleXMLIterator::valid' => ['bool'],
'SimpleXMLIterator::xpath' => ['SimpleXMLElement[]|false', 'path'=>'string'],
'sin' => ['float', 'num'=>'float'],
'sinh' => ['float', 'num'=>'float'],
'sizeof' => ['int', 'value'=>'Countable|array', 'mode='=>'int'],
'sleep' => ['int|false', 'seconds'=>'int'],
'snmp2_get' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_getnext' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_real_walk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_set' => ['bool', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_walk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_get' => ['string|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_getnext' => ['string|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_real_walk' => ['array|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_set' => ['bool', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_walk' => ['array|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SNMP::__construct' => ['void', 'version'=>'int', 'hostname'=>'string', 'community'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SNMP::close' => ['bool'],
'SNMP::get' => ['array|string|false', 'objectId'=>'string|array', 'preserveKeys='=>'bool'],
'SNMP::getErrno' => ['int'],
'SNMP::getError' => ['string'],
'SNMP::getnext' => ['string|array|false', 'objectId'=>'string|array'],
'SNMP::set' => ['bool', 'objectId'=>'string|array', 'type'=>'string|array', 'value'=>'mixed'],
'SNMP::setSecurity' => ['bool', 'securityLevel'=>'string', 'authProtocol='=>'string', 'authPassphrase='=>'string', 'privacyProtocol='=>'string', 'privacyPassphrase='=>'string', 'contextName='=>'string', 'contextEngineId='=>'string'],
'SNMP::walk' => ['array|false', 'objectId'=>'string', 'suffixAsKey='=>'bool', 'maxRepetitions='=>'int', 'nonRepeaters='=>'int'],
'snmp_get_quick_print' => ['bool'],
'snmp_get_valueretrieval' => ['int'],
'snmp_read_mib' => ['bool', 'filename'=>'string'],
'snmp_set_enum_print' => ['bool', 'enable'=>'int'],
'snmp_set_oid_numeric_print' => ['void', 'format'=>'int'],
'snmp_set_oid_output_format' => ['bool', 'format'=>'int'],
'snmp_set_quick_print' => ['bool', 'enable'=>'bool'],
'snmp_set_valueretrieval' => ['bool', 'method='=>'int'],
'snmpget' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpgetnext' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmprealwalk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpset' => ['bool', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'mixed', 'timeout='=>'int', 'retries='=>'int'],
'snmpwalk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpwalkoid' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SoapClient::__call' => ['', 'function_name'=>'string', 'arguments'=>'array'],
'SoapClient::__construct' => ['void', 'wsdl'=>'mixed', 'options='=>'array|null'],
'SoapClient::__doRequest' => ['string', 'request'=>'string', 'location'=>'string', 'action'=>'string', 'version'=>'int', 'one_way='=>'int'],
'SoapClient::__getCookies' => ['array'],
'SoapClient::__getFunctions' => ['array'],
'SoapClient::__getLastRequest' => ['string'],
'SoapClient::__getLastRequestHeaders' => ['string'],
'SoapClient::__getLastResponse' => ['string'],
'SoapClient::__getLastResponseHeaders' => ['string'],
'SoapClient::__getTypes' => ['array'],
'SoapClient::__setCookie' => ['', 'name'=>'string', 'value='=>'string'],
'SoapClient::__setLocation' => ['string', 'new_location='=>'string'],
'SoapClient::__setSoapHeaders' => ['bool', 'soapheaders='=>''],
'SoapClient::__soapCall' => ['', 'function_name'=>'string', 'arguments'=>'array', 'options='=>'array', 'input_headers='=>'SoapHeader|array', '&w_output_headers='=>'array'],
'SoapClient::SoapClient' => ['object', 'wsdl'=>'mixed', 'options='=>'array|null'],
'SoapFault::__clone' => ['void'],
'SoapFault::__construct' => ['void', 'faultcode'=>'string', 'faultstring'=>'string', 'faultactor='=>'string', 'detail='=>'string', 'faultname='=>'string', 'headerfault='=>'string'],
'SoapFault::__toString' => ['string'],
'SoapFault::__wakeup' => ['void'],
'SoapFault::getCode' => ['int'],
'SoapFault::getFile' => ['string'],
'SoapFault::getLine' => ['int'],
'SoapFault::getMessage' => ['string'],
'SoapFault::getPrevious' => ['?Exception|?Throwable'],
'SoapFault::getTrace' => ['list<array<string,mixed>>'],
'SoapFault::getTraceAsString' => ['string'],
'SoapFault::SoapFault' => ['object', 'faultcode'=>'string', 'faultstring'=>'string', 'faultactor='=>'string', 'detail='=>'string', 'faultname='=>'string', 'headerfault='=>'string'],
'SoapHeader::__construct' => ['void', 'namespace'=>'string', 'name'=>'string', 'data='=>'mixed', 'mustunderstand='=>'bool', 'actor='=>'string'],
'SoapHeader::SoapHeader' => ['object', 'namespace'=>'string', 'name'=>'string', 'data='=>'mixed', 'mustunderstand='=>'bool', 'actor='=>'string'],
'SoapParam::__construct' => ['void', 'data'=>'mixed', 'name'=>'string'],
'SoapParam::SoapParam' => ['object', 'data'=>'mixed', 'name'=>'string'],
'SoapServer::__construct' => ['void', 'wsdl'=>'?string', 'options='=>'array'],
'SoapServer::addFunction' => ['void', 'functions'=>'mixed'],
'SoapServer::addSoapHeader' => ['void', 'object'=>'SoapHeader'],
'SoapServer::fault' => ['void', 'code'=>'string', 'string'=>'string', 'actor='=>'string', 'details='=>'string', 'name='=>'string'],
'SoapServer::getFunctions' => ['array'],
'SoapServer::handle' => ['void', 'soap_request='=>'string'],
'SoapServer::setClass' => ['void', 'class_name'=>'string', '...args='=>'mixed'],
'SoapServer::setObject' => ['void', 'object'=>'object'],
'SoapServer::setPersistence' => ['void', 'mode'=>'int'],
'SoapServer::SoapServer' => ['object', 'wsdl'=>'?string', 'options='=>'array'],
'SoapVar::__construct' => ['void', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string|null', 'type_namespace='=>'string|null', 'node_name='=>'string|null', 'node_namespace='=>'string|null'],
'SoapVar::SoapVar' => ['object', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string|null', 'type_namespace='=>'string|null', 'node_name='=>'string|null', 'node_namespace='=>'string|null'],
'socket_accept' => ['resource|false', 'socket'=>'resource'],
'socket_addrinfo_bind' => ['?resource', 'address'=>'resource'],
'socket_addrinfo_connect' => ['?resource', 'address'=>'resource'],
'socket_addrinfo_explain' => ['array', 'address'=>'resource'],
'socket_addrinfo_lookup' => ['AddressInfo[]', 'host'=>'string', 'service='=>'mixed', 'hints='=>'array'],
'socket_bind' => ['bool', 'socket'=>'resource', 'address'=>'string', 'port='=>'int'],
'socket_clear_error' => ['void', 'socket='=>'resource'],
'socket_close' => ['void', 'socket'=>'resource'],
'socket_cmsg_space' => ['int', 'level'=>'int', 'type'=>'int'],
'socket_connect' => ['bool', 'socket'=>'resource', 'address'=>'string', 'port='=>'int'],
'socket_create' => ['resource|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'socket_create_listen' => ['resource|false', 'port'=>'int', 'backlog='=>'int'],
'socket_create_pair' => ['bool', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int', '&w_pair'=>'resource[]'],
'socket_export_stream' => ['resource|false', 'socket'=>'resource'],
'socket_get_option' => ['mixed|false', 'socket'=>'resource', 'level'=>'int', 'option'=>'int'],
'socket_get_status' => ['array', 'stream'=>'resource'],
'socket_getopt' => ['mixed', 'socket'=>'resource', 'level'=>'int', 'option'=>'int'],
'socket_getpeername' => ['bool', 'socket'=>'resource', '&w_address'=>'string', '&w_port='=>'int'],
'socket_getsockname' => ['bool', 'socket'=>'resource', '&w_address'=>'string', '&w_port='=>'int'],
'socket_import_stream' => ['resource|false|null', 'stream'=>'resource'],
'socket_last_error' => ['int', 'socket='=>'resource'],
'socket_listen' => ['bool', 'socket'=>'resource', 'backlog='=>'int'],
'socket_read' => ['string|false', 'socket'=>'resource', 'length'=>'int', 'mode='=>'int'],
'socket_recv' => ['int|false', 'socket'=>'resource', '&w_data'=>'string', 'length'=>'int', 'flags'=>'int'],
'socket_recvfrom' => ['int|false', 'socket'=>'resource', '&w_data'=>'string', 'length'=>'int', 'flags'=>'int', '&w_address'=>'string', '&w_port='=>'int'],
'socket_recvmsg' => ['int|false', 'socket'=>'resource', '&w_message'=>'string', 'flags='=>'int'],
'socket_select' => ['int|false', '&rw_read'=>'resource[]|null', '&rw_write'=>'resource[]|null', '&rw_except'=>'resource[]|null', 'seconds'=>'int', 'microseconds='=>'int'],
'socket_send' => ['int|false', 'socket'=>'resource', 'data'=>'string', 'length'=>'int', 'flags'=>'int'],
'socket_sendmsg' => ['int|false', 'socket'=>'resource', 'message'=>'array', 'flags'=>'int'],
'socket_sendto' => ['int|false', 'socket'=>'resource', 'data'=>'string', 'length'=>'int', 'flags'=>'int', 'address'=>'string', 'port='=>'int'],
'socket_set_block' => ['bool', 'socket'=>'resource'],
'socket_set_blocking' => ['bool', 'stream'=>'resource', 'enable'=>'int'],
'socket_set_nonblock' => ['bool', 'socket'=>'resource'],
'socket_set_option' => ['bool', 'socket'=>'resource', 'level'=>'int', 'option'=>'int', 'value'=>'int|string|array'],
'socket_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'socket_setopt' => ['void', 'socket'=>'resource', 'level'=>'int', 'option'=>'int', 'value'=>'int|string|array'],
'socket_shutdown' => ['bool', 'socket'=>'resource', 'mode='=>'int'],
'socket_strerror' => ['string', 'error_code'=>'int'],
'socket_write' => ['int|false', 'socket'=>'resource', 'data'=>'string', 'length='=>'int'],
'socket_wsaprotocol_info_export' => ['string|false', 'socket'=>'resource', 'process_id'=>'int'],
'socket_wsaprotocol_info_import' => ['resource|false', 'info_id'=>'string'],
'socket_wsaprotocol_info_release' => ['bool', 'info_id'=>'string'],
'Sodium\add' => ['void', '&left'=>'string', 'right'=>'string'],
'Sodium\bin2hex' => ['string', 'binary'=>'string'],
'Sodium\compare' => ['int', 'left'=>'string', 'right'=>'string'],
'Sodium\crypto_aead_aes256gcm_decrypt' => ['string|false', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_aead_aes256gcm_encrypt' => ['string', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_aead_aes256gcm_is_available' => ['bool'],
'Sodium\crypto_aead_chacha20poly1305_decrypt' => ['string', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_aead_chacha20poly1305_encrypt' => ['string', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_auth' => ['string', 'msg'=>'string', 'key'=>'string'],
'Sodium\crypto_auth_verify' => ['bool', 'mac'=>'string', 'msg'=>'string', 'key'=>'string'],
'Sodium\crypto_box' => ['string', 'msg'=>'string', 'nonce'=>'string', 'keypair'=>'string'],
'Sodium\crypto_box_keypair' => ['string'],
'Sodium\crypto_box_keypair_from_secretkey_and_publickey' => ['string', 'secretkey'=>'string', 'publickey'=>'string'],
'Sodium\crypto_box_open' => ['string', 'msg'=>'string', 'nonce'=>'string', 'keypair'=>'string'],
'Sodium\crypto_box_publickey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_box_publickey_from_secretkey' => ['string', 'secretkey'=>'string'],
'Sodium\crypto_box_seal' => ['string', 'message'=>'string', 'publickey'=>'string'],
'Sodium\crypto_box_seal_open' => ['string', 'encrypted'=>'string', 'keypair'=>'string'],
'Sodium\crypto_box_secretkey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_box_seed_keypair' => ['string', 'seed'=>'string'],
'Sodium\crypto_generichash' => ['string', 'input'=>'string', 'key='=>'string', 'length='=>'int'],
'Sodium\crypto_generichash_final' => ['string', 'state'=>'string', 'length='=>'int'],
'Sodium\crypto_generichash_init' => ['string', 'key='=>'string', 'length='=>'int'],
'Sodium\crypto_generichash_update' => ['bool', '&hashState'=>'string', 'append'=>'string'],
'Sodium\crypto_kx' => ['string', 'secretkey'=>'string', 'publickey'=>'string', 'client_publickey'=>'string', 'server_publickey'=>'string'],
'Sodium\crypto_pwhash' => ['string', 'out_len'=>'int', 'passwd'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_scryptsalsa208sha256' => ['string', 'out_len'=>'int', 'passwd'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_scryptsalsa208sha256_str' => ['string', 'passwd'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_scryptsalsa208sha256_str_verify' => ['bool', 'hash'=>'string', 'passwd'=>'string'],
'Sodium\crypto_pwhash_str' => ['string', 'passwd'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_str_verify' => ['bool', 'hash'=>'string', 'passwd'=>'string'],
'Sodium\crypto_scalarmult' => ['string', 'ecdhA'=>'string', 'ecdhB'=>'string'],
'Sodium\crypto_scalarmult_base' => ['string', 'sk'=>'string'],
'Sodium\crypto_secretbox' => ['string', 'plaintext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'Sodium\crypto_secretbox_open' => ['string', 'ciphertext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'Sodium\crypto_shorthash' => ['string', 'message'=>'string', 'key'=>'string'],
'Sodium\crypto_sign' => ['string', 'message'=>'string', 'secretkey'=>'string'],
'Sodium\crypto_sign_detached' => ['string', 'message'=>'string', 'secretkey'=>'string'],
'Sodium\crypto_sign_ed25519_pk_to_curve25519' => ['string', 'sign_pk'=>'string'],
'Sodium\crypto_sign_ed25519_sk_to_curve25519' => ['string', 'sign_sk'=>'string'],
'Sodium\crypto_sign_keypair' => ['string'],
'Sodium\crypto_sign_keypair_from_secretkey_and_publickey' => ['string', 'secretkey'=>'string', 'publickey'=>'string'],
'Sodium\crypto_sign_open' => ['string|false', 'signed_message'=>'string', 'publickey'=>'string'],
'Sodium\crypto_sign_publickey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_sign_publickey_from_secretkey' => ['string', 'secretkey'=>'string'],
'Sodium\crypto_sign_secretkey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_sign_seed_keypair' => ['string', 'seed'=>'string'],
'Sodium\crypto_sign_verify_detached' => ['bool', 'signature'=>'string', 'msg'=>'string', 'publickey'=>'string'],
'Sodium\crypto_stream' => ['string', 'length'=>'int', 'nonce'=>'string', 'key'=>'string'],
'Sodium\crypto_stream_xor' => ['string', 'plaintext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'Sodium\hex2bin' => ['string', 'hex'=>'string'],
'Sodium\increment' => ['string', '&nonce'=>'string'],
'Sodium\library_version_major' => ['int'],
'Sodium\library_version_minor' => ['int'],
'Sodium\memcmp' => ['int', 'left'=>'string', 'right'=>'string'],
'Sodium\memzero' => ['void', '&target'=>'string'],
'Sodium\randombytes_buf' => ['string', 'length'=>'int'],
'Sodium\randombytes_random16' => ['int|string'],
'Sodium\randombytes_uniform' => ['int', 'upperBoundNonInclusive'=>'int'],
'Sodium\version_string' => ['string'],
'sodium_add' => ['string', 'string1'=>'string', 'string2'=>'string'],
'sodium_base642bin' => ['string', 'string'=>'string', 'id'=>'int', 'ignore='=>'string'],
'sodium_bin2base64' => ['string', 'string'=>'string', 'id'=>'int'],
'sodium_bin2hex' => ['string', 'string'=>'string'],
'sodium_compare' => ['int', 'string1'=>'string', 'string2'=>'string'],
'sodium_crypto_aead_aes256gcm_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_encrypt' => ['string', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_is_available' => ['bool'],
'sodium_crypto_aead_aes256gcm_keygen' => ['string'],
'sodium_crypto_aead_chacha20poly1305_decrypt' => ['string', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_encrypt' => ['string', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_decrypt' => ['array<int,string>|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_encrypt' => ['string', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_keygen' => ['string'],
'sodium_crypto_aead_chacha20poly1305_keygen' => ['string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt' => ['string', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_keygen' => ['string'],
'sodium_crypto_auth' => ['string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_auth_keygen' => ['string'],
'sodium_crypto_auth_verify' => ['bool', 'mac'=>'string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_box' => ['string', 'message'=>'string', 'nonce'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_keypair' => ['string'],
'sodium_crypto_box_keypair_from_secretkey_and_publickey' => ['string', 'secret_key'=>'string', 'public_key'=>'string'],
'sodium_crypto_box_open' => ['string|false', 'ciphertext'=>'string', 'nonce'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_box_publickey_from_secretkey' => ['string', 'secret_key'=>'string'],
'sodium_crypto_box_seal' => ['string', 'message'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_seal_open' => ['string|false', 'ciphertext'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_box_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_generichash' => ['string', 'message'=>'string', 'key='=>'?string', 'length='=>'?int'],
'sodium_crypto_generichash_final' => ['string', 'state'=>'string', 'length='=>'?int'],
'sodium_crypto_generichash_init' => ['string', 'key='=>'?string', 'length='=>'?int'],
'sodium_crypto_generichash_keygen' => ['string'],
'sodium_crypto_generichash_update' => ['bool', 'state'=>'string', 'message'=>'string'],
'sodium_crypto_kdf_derive_from_key' => ['string', 'subkey_length'=>'int', 'subkey_id'=>'int', 'context'=>'string', 'key'=>'string'],
'sodium_crypto_kdf_keygen' => ['string'],
'sodium_crypto_kx' => ['string', 'secretkey'=>'string', 'publickey'=>'string', 'client_publickey'=>'string', 'server_publickey'=>'string'],
'sodium_crypto_kx_client_session_keys' => ['array<int,string>', 'client_key_pair'=>'string', 'server_key'=>'string'],
'sodium_crypto_kx_keypair' => ['string'],
'sodium_crypto_kx_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_kx_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_kx_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_kx_server_session_keys' => ['array<int,string>', 'server_key_pair'=>'string', 'client_key'=>'string'],
'sodium_crypto_pwhash' => ['string', 'length'=>'int', 'password'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int', 'algo='=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256' => ['string', 'length'=>'int', 'password'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256_str' => ['string', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256_str_verify' => ['bool', 'hash'=>'string', 'password'=>'string'],
'sodium_crypto_pwhash_str' => ['string', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_str_needs_rehash' => ['bool', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_str_verify' => ['bool', 'hash'=>'string', 'password'=>'string'],
'sodium_crypto_scalarmult' => ['string', 'n'=>'string', 'p'=>'string'],
'sodium_crypto_scalarmult_base' => ['string', 'secret_key'=>'string'],
'sodium_crypto_secretbox' => ['string', 'message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_secretbox_keygen' => ['string'],
'sodium_crypto_secretbox_open' => ['string|false', 'ciphertext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_init_pull' => ['string', 'header'=>'string', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_init_push' => ['array', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_keygen' => ['string'],
'sodium_crypto_secretstream_xchacha20poly1305_pull' => ['array', 'state'=>'string', 'ciphertext'=>'string', 'additional_data='=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_push' => ['string', 'state'=>'string', 'message'=>'string', 'additional_data='=>'string', 'tag='=>'int'],
'sodium_crypto_secretstream_xchacha20poly1305_rekey' => ['void', 'state'=>'string'],
'sodium_crypto_shorthash' => ['string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_shorthash_keygen' => ['string'],
'sodium_crypto_sign' => ['string', 'message'=>'string', 'secret_key'=>'string'],
'sodium_crypto_sign_detached' => ['string', 'message'=>'string', 'secret_key'=>'string'],
'sodium_crypto_sign_ed25519_pk_to_curve25519' => ['string', 'public_key'=>'string'],
'sodium_crypto_sign_ed25519_sk_to_curve25519' => ['string', 'secret_key'=>'string'],
'sodium_crypto_sign_keypair' => ['string'],
'sodium_crypto_sign_keypair_from_secretkey_and_publickey' => ['string', 'secret_key'=>'string', 'public_key'=>'string'],
'sodium_crypto_sign_open' => ['string|false', 'ciphertext'=>'string', 'public_key'=>'string'],
'sodium_crypto_sign_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_sign_publickey_from_secretkey' => ['string', 'secret_key'=>'string'],
'sodium_crypto_sign_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_sign_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_sign_verify_detached' => ['bool', 'signature'=>'string', 'message'=>'string', 'public_key'=>'string'],
'sodium_crypto_stream' => ['string', 'length'=>'int', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_stream_keygen' => ['string'],
'sodium_crypto_stream_xor' => ['string', 'message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_hex2bin' => ['string', 'string'=>'string', 'ignore='=>'string'],
'sodium_increment' => ['string', '&string'=>'string'],
'sodium_library_version_major' => ['int'],
'sodium_library_version_minor' => ['int'],
'sodium_memcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'sodium_memzero' => ['void', '&string'=>'string'],
'sodium_pad' => ['string', 'string'=>'string', 'length'=>'int'],
'sodium_randombytes_buf' => ['string', 'length'=>'int'],
'sodium_randombytes_random16' => ['int|string'],
'sodium_randombytes_uniform' => ['int', 'upperBoundNonInclusive'=>'int'],
'sodium_unpad' => ['string', 'string'=>'string', 'block_size'=>'int'],
'sodium_version_string' => ['string'],
'solid_fetch_prev' => ['bool', 'result_id'=>''],
'solr_get_version' => ['string|false'],
'SolrClient::__construct' => ['void', 'clientOptions'=>'array'],
'SolrClient::__destruct' => ['void'],
'SolrClient::addDocument' => ['SolrUpdateResponse', 'doc'=>'SolrInputDocument', 'allowdups='=>'bool', 'commitwithin='=>'int'],
'SolrClient::addDocuments' => ['SolrUpdateResponse', 'docs'=>'array', 'allowdups='=>'bool', 'commitwithin='=>'int'],
'SolrClient::commit' => ['SolrUpdateResponse', 'maxsegments='=>'int', 'waitflush='=>'bool', 'waitsearcher='=>'bool'],
'SolrClient::deleteById' => ['SolrUpdateResponse', 'id'=>'string'],
'SolrClient::deleteByIds' => ['SolrUpdateResponse', 'ids'=>'array'],
'SolrClient::deleteByQueries' => ['SolrUpdateResponse', 'queries'=>'array'],
'SolrClient::deleteByQuery' => ['SolrUpdateResponse', 'query'=>'string'],
'SolrClient::getById' => ['SolrQueryResponse', 'id'=>'string'],
'SolrClient::getByIds' => ['SolrQueryResponse', 'ids'=>'array'],
'SolrClient::getDebug' => ['string'],
'SolrClient::getOptions' => ['array'],
'SolrClient::optimize' => ['SolrUpdateResponse', 'maxsegments='=>'int', 'waitflush='=>'bool', 'waitsearcher='=>'bool'],
'SolrClient::ping' => ['SolrPingResponse'],
'SolrClient::query' => ['SolrQueryResponse', 'query'=>'SolrParams'],
'SolrClient::request' => ['SolrUpdateResponse', 'raw_request'=>'string'],
'SolrClient::rollback' => ['SolrUpdateResponse'],
'SolrClient::setResponseWriter' => ['void', 'responsewriter'=>'string'],
'SolrClient::setServlet' => ['bool', 'type'=>'int', 'value'=>'string'],
'SolrClient::system' => ['SolrGenericResponse'],
'SolrClient::threads' => ['SolrGenericResponse'],
'SolrClientException::__clone' => ['void'],
'SolrClientException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrClientException::__toString' => ['string'],
'SolrClientException::__wakeup' => ['void'],
'SolrClientException::getCode' => ['int'],
'SolrClientException::getFile' => ['string'],
'SolrClientException::getInternalInfo' => ['array'],
'SolrClientException::getLine' => ['int'],
'SolrClientException::getMessage' => ['string'],
'SolrClientException::getPrevious' => ['?Exception|?Throwable'],
'SolrClientException::getTrace' => ['list<array<string,mixed>>'],
'SolrClientException::getTraceAsString' => ['string'],
'SolrCollapseFunction::__construct' => ['void', 'field'=>'string'],
'SolrCollapseFunction::__toString' => ['string'],
'SolrCollapseFunction::getField' => ['string'],
'SolrCollapseFunction::getHint' => ['string'],
'SolrCollapseFunction::getMax' => ['string'],
'SolrCollapseFunction::getMin' => ['string'],
'SolrCollapseFunction::getNullPolicy' => ['string'],
'SolrCollapseFunction::getSize' => ['int'],
'SolrCollapseFunction::setField' => ['SolrCollapseFunction', 'fieldName'=>'string'],
'SolrCollapseFunction::setHint' => ['SolrCollapseFunction', 'hint'=>'string'],
'SolrCollapseFunction::setMax' => ['SolrCollapseFunction', 'max'=>'string'],
'SolrCollapseFunction::setMin' => ['SolrCollapseFunction', 'min'=>'string'],
'SolrCollapseFunction::setNullPolicy' => ['SolrCollapseFunction', 'nullPolicy'=>'string'],
'SolrCollapseFunction::setSize' => ['SolrCollapseFunction', 'size'=>'int'],
'SolrDisMaxQuery::__construct' => ['void', 'q='=>'string'],
'SolrDisMaxQuery::__destruct' => ['void'],
'SolrDisMaxQuery::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrDisMaxQuery::addBigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addBoostQuery' => ['SolrDisMaxQuery', 'field'=>'string', 'value'=>'string', 'boost='=>'string'],
'SolrDisMaxQuery::addExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::addExpandSortField' => ['SolrQuery', 'field'=>'string', 'order'=>'string'],
'SolrDisMaxQuery::addFacetDateField' => ['SolrQuery', 'dateField'=>'string'],
'SolrDisMaxQuery::addFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::addFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addFacetQuery' => ['SolrQuery', 'facetQuery'=>'string'],
'SolrDisMaxQuery::addField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::addGroupField' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupFunction' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupQuery' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupSortField' => ['SolrQuery', 'field'=>'string', 'order'=>'int'],
'SolrDisMaxQuery::addHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addMltField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addMltQueryField' => ['SolrQuery', 'field'=>'string', 'boost'=>'float'],
'SolrDisMaxQuery::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrDisMaxQuery::addPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addQueryField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost='=>'string'],
'SolrDisMaxQuery::addSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrDisMaxQuery::addStatsFacet' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addTrigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addUserField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::collapse' => ['SolrQuery', 'collapseFunction'=>'SolrCollapseFunction'],
'SolrDisMaxQuery::get' => ['mixed', 'param_name'=>'string'],
'SolrDisMaxQuery::getExpand' => ['bool'],
'SolrDisMaxQuery::getExpandFilterQueries' => ['array'],
'SolrDisMaxQuery::getExpandQuery' => ['array'],
'SolrDisMaxQuery::getExpandRows' => ['int'],
'SolrDisMaxQuery::getExpandSortFields' => ['array'],
'SolrDisMaxQuery::getFacet' => ['bool'],
'SolrDisMaxQuery::getFacetDateEnd' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateFields' => ['array'],
'SolrDisMaxQuery::getFacetDateGap' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateHardEnd' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateOther' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateStart' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetFields' => ['array'],
'SolrDisMaxQuery::getFacetLimit' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMethod' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMinCount' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMissing' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetOffset' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetPrefix' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetQueries' => ['string'],
'SolrDisMaxQuery::getFacetSort' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFields' => ['string'],
'SolrDisMaxQuery::getFilterQueries' => ['string'],
'SolrDisMaxQuery::getGroup' => ['bool'],
'SolrDisMaxQuery::getGroupCachePercent' => ['int'],
'SolrDisMaxQuery::getGroupFacet' => ['bool'],
'SolrDisMaxQuery::getGroupFields' => ['array'],
'SolrDisMaxQuery::getGroupFormat' => ['string'],
'SolrDisMaxQuery::getGroupFunctions' => ['array'],
'SolrDisMaxQuery::getGroupLimit' => ['int'],
'SolrDisMaxQuery::getGroupMain' => ['bool'],
'SolrDisMaxQuery::getGroupNGroups' => ['bool'],
'SolrDisMaxQuery::getGroupOffset' => ['bool'],
'SolrDisMaxQuery::getGroupQueries' => ['array'],
'SolrDisMaxQuery::getGroupSortFields' => ['array'],
'SolrDisMaxQuery::getGroupTruncate' => ['bool'],
'SolrDisMaxQuery::getHighlight' => ['bool'],
'SolrDisMaxQuery::getHighlightAlternateField' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFields' => ['array'],
'SolrDisMaxQuery::getHighlightFormatter' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFragmenter' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFragsize' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightHighlightMultiTerm' => ['bool'],
'SolrDisMaxQuery::getHighlightMaxAlternateFieldLength' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightMaxAnalyzedChars' => ['int'],
'SolrDisMaxQuery::getHighlightMergeContiguous' => ['bool', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightRegexMaxAnalyzedChars' => ['int'],
'SolrDisMaxQuery::getHighlightRegexPattern' => ['string'],
'SolrDisMaxQuery::getHighlightRegexSlop' => ['float'],
'SolrDisMaxQuery::getHighlightRequireFieldMatch' => ['bool'],
'SolrDisMaxQuery::getHighlightSimplePost' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightSimplePre' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightSnippets' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightUsePhraseHighlighter' => ['bool'],
'SolrDisMaxQuery::getMlt' => ['bool'],
'SolrDisMaxQuery::getMltBoost' => ['bool'],
'SolrDisMaxQuery::getMltCount' => ['int'],
'SolrDisMaxQuery::getMltFields' => ['array'],
'SolrDisMaxQuery::getMltMaxNumQueryTerms' => ['int'],
'SolrDisMaxQuery::getMltMaxNumTokens' => ['int'],
'SolrDisMaxQuery::getMltMaxWordLength' => ['int'],
'SolrDisMaxQuery::getMltMinDocFrequency' => ['int'],
'SolrDisMaxQuery::getMltMinTermFrequency' => ['int'],
'SolrDisMaxQuery::getMltMinWordLength' => ['int'],
'SolrDisMaxQuery::getMltQueryFields' => ['array'],
'SolrDisMaxQuery::getParam' => ['mixed', 'param_name'=>'string'],
'SolrDisMaxQuery::getParams' => ['array'],
'SolrDisMaxQuery::getPreparedParams' => ['array'],
'SolrDisMaxQuery::getQuery' => ['string'],
'SolrDisMaxQuery::getRows' => ['int'],
'SolrDisMaxQuery::getSortFields' => ['array'],
'SolrDisMaxQuery::getStart' => ['int'],
'SolrDisMaxQuery::getStats' => ['bool'],
'SolrDisMaxQuery::getStatsFacets' => ['array'],
'SolrDisMaxQuery::getStatsFields' => ['array'],
'SolrDisMaxQuery::getTerms' => ['bool'],
'SolrDisMaxQuery::getTermsField' => ['string'],
'SolrDisMaxQuery::getTermsIncludeLowerBound' => ['bool'],
'SolrDisMaxQuery::getTermsIncludeUpperBound' => ['bool'],
'SolrDisMaxQuery::getTermsLimit' => ['int'],
'SolrDisMaxQuery::getTermsLowerBound' => ['string'],
'SolrDisMaxQuery::getTermsMaxCount' => ['int'],
'SolrDisMaxQuery::getTermsMinCount' => ['int'],
'SolrDisMaxQuery::getTermsPrefix' => ['string'],
'SolrDisMaxQuery::getTermsReturnRaw' => ['bool'],
'SolrDisMaxQuery::getTermsSort' => ['int'],
'SolrDisMaxQuery::getTermsUpperBound' => ['string'],
'SolrDisMaxQuery::getTimeAllowed' => ['int'],
'SolrDisMaxQuery::removeBigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeBoostQuery' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::removeExpandSortField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetDateField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::removeFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetQuery' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::removeField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::removeHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeMltField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeMltQueryField' => ['SolrQuery', 'queryField'=>'string'],
'SolrDisMaxQuery::removePhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeQueryField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeSortField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeStatsFacet' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::removeStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeTrigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeUserField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::serialize' => ['string'],
'SolrDisMaxQuery::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrDisMaxQuery::setBigramPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setBigramPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setBoostFunction' => ['SolrDisMaxQuery', 'function'=>'string'],
'SolrDisMaxQuery::setBoostQuery' => ['SolrDisMaxQuery', 'q'=>'string'],
'SolrDisMaxQuery::setEchoHandler' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setEchoParams' => ['SolrQuery', 'type'=>'string'],
'SolrDisMaxQuery::setExpand' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setExpandQuery' => ['SolrQuery', 'q'=>'string'],
'SolrDisMaxQuery::setExpandRows' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setExplainOther' => ['SolrQuery', 'query'=>'string'],
'SolrDisMaxQuery::setFacet' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setFacetDateEnd' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateGap' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateHardEnd' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateStart' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetEnumCacheMinDefaultFrequency' => ['SolrQuery', 'frequency'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetLimit' => ['SolrQuery', 'limit'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMethod' => ['SolrQuery', 'method'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMinCount' => ['SolrQuery', 'mincount'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMissing' => ['SolrQuery', 'flag'=>'bool', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetOffset' => ['SolrQuery', 'offset'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetPrefix' => ['SolrQuery', 'prefix'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetSort' => ['SolrQuery', 'facetSort'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setGroup' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupCachePercent' => ['SolrQuery', 'percent'=>'int'],
'SolrDisMaxQuery::setGroupFacet' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupFormat' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setGroupLimit' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setGroupMain' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setGroupNGroups' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupOffset' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setGroupTruncate' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setHighlight' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightAlternateField' => ['SolrQuery', 'field'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFormatter' => ['SolrQuery', 'formatter'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFragmenter' => ['SolrQuery', 'fragmenter'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFragsize' => ['SolrQuery', 'size'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightHighlightMultiTerm' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightMaxAlternateFieldLength' => ['SolrQuery', 'fieldLength'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightMaxAnalyzedChars' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setHighlightMergeContiguous' => ['SolrQuery', 'flag'=>'bool', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightRegexMaxAnalyzedChars' => ['SolrQuery', 'maxAnalyzedChars'=>'int'],
'SolrDisMaxQuery::setHighlightRegexPattern' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setHighlightRegexSlop' => ['SolrQuery', 'factor'=>'float'],
'SolrDisMaxQuery::setHighlightRequireFieldMatch' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightSimplePost' => ['SolrQuery', 'simplePost'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightSimplePre' => ['SolrQuery', 'simplePre'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightSnippets' => ['SolrQuery', 'value'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightUsePhraseHighlighter' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMinimumMatch' => ['SolrDisMaxQuery', 'value'=>'string'],
'SolrDisMaxQuery::setMlt' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMltBoost' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMltCount' => ['SolrQuery', 'count'=>'int'],
'SolrDisMaxQuery::setMltMaxNumQueryTerms' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setMltMaxNumTokens' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setMltMaxWordLength' => ['SolrQuery', 'maxWordLength'=>'int'],
'SolrDisMaxQuery::setMltMinDocFrequency' => ['SolrQuery', 'minDocFrequency'=>'int'],
'SolrDisMaxQuery::setMltMinTermFrequency' => ['SolrQuery', 'minTermFrequency'=>'int'],
'SolrDisMaxQuery::setMltMinWordLength' => ['SolrQuery', 'minWordLength'=>'int'],
'SolrDisMaxQuery::setOmitHeader' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrDisMaxQuery::setPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setQuery' => ['SolrQuery', 'query'=>'string'],
'SolrDisMaxQuery::setQueryAlt' => ['SolrDisMaxQuery', 'q'=>'string'],
'SolrDisMaxQuery::setQueryPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setRows' => ['SolrQuery', 'rows'=>'int'],
'SolrDisMaxQuery::setShowDebugInfo' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setStart' => ['SolrQuery', 'start'=>'int'],
'SolrDisMaxQuery::setStats' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTerms' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsField' => ['SolrQuery', 'fieldname'=>'string'],
'SolrDisMaxQuery::setTermsIncludeLowerBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsIncludeUpperBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsLimit' => ['SolrQuery', 'limit'=>'int'],
'SolrDisMaxQuery::setTermsLowerBound' => ['SolrQuery', 'lowerBound'=>'string'],
'SolrDisMaxQuery::setTermsMaxCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrDisMaxQuery::setTermsMinCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrDisMaxQuery::setTermsPrefix' => ['SolrQuery', 'prefix'=>'string'],
'SolrDisMaxQuery::setTermsReturnRaw' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsSort' => ['SolrQuery', 'sortType'=>'int'],
'SolrDisMaxQuery::setTermsUpperBound' => ['SolrQuery', 'upperBound'=>'string'],
'SolrDisMaxQuery::setTieBreaker' => ['SolrDisMaxQuery', 'tieBreaker'=>'string'],
'SolrDisMaxQuery::setTimeAllowed' => ['SolrQuery', 'timeAllowed'=>'int'],
'SolrDisMaxQuery::setTrigramPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setTrigramPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setUserFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::toString' => ['string', 'url_encode='=>'bool'],
'SolrDisMaxQuery::unserialize' => ['void', 'serialized'=>'string'],
'SolrDisMaxQuery::useDisMaxQueryParser' => ['SolrDisMaxQuery'],
'SolrDisMaxQuery::useEDisMaxQueryParser' => ['SolrDisMaxQuery'],
'SolrDocument::__clone' => ['void'],
'SolrDocument::__construct' => ['void'],
'SolrDocument::__destruct' => ['void'],
'SolrDocument::__get' => ['SolrDocumentField', 'fieldname'=>'string'],
'SolrDocument::__isset' => ['bool', 'fieldname'=>'string'],
'SolrDocument::__set' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::__unset' => ['bool', 'fieldname'=>'string'],
'SolrDocument::addField' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::clear' => ['bool'],
'SolrDocument::current' => ['SolrDocumentField'],
'SolrDocument::deleteField' => ['bool', 'fieldname'=>'string'],
'SolrDocument::fieldExists' => ['bool', 'fieldname'=>'string'],
'SolrDocument::getChildDocuments' => ['SolrInputDocument[]'],
'SolrDocument::getChildDocumentsCount' => ['int'],
'SolrDocument::getField' => ['SolrDocumentField|false', 'fieldname'=>'string'],
'SolrDocument::getFieldCount' => ['int|false'],
'SolrDocument::getFieldNames' => ['array|false'],
'SolrDocument::getInputDocument' => ['SolrInputDocument'],
'SolrDocument::hasChildDocuments' => ['bool'],
'SolrDocument::key' => ['string'],
'SolrDocument::merge' => ['bool', 'sourcedoc'=>'solrdocument', 'overwrite='=>'bool'],
'SolrDocument::next' => ['void'],
'SolrDocument::offsetExists' => ['bool', 'fieldname'=>'string'],
'SolrDocument::offsetGet' => ['SolrDocumentField', 'fieldname'=>'string'],
'SolrDocument::offsetSet' => ['void', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::offsetUnset' => ['void', 'fieldname'=>'string'],
'SolrDocument::reset' => ['bool'],
'SolrDocument::rewind' => ['void'],
'SolrDocument::serialize' => ['string'],
'SolrDocument::sort' => ['bool', 'sortorderby'=>'int', 'sortdirection='=>'int'],
'SolrDocument::toArray' => ['array'],
'SolrDocument::unserialize' => ['void', 'serialized'=>'string'],
'SolrDocument::valid' => ['bool'],
'SolrDocumentField::__construct' => ['void'],
'SolrDocumentField::__destruct' => ['void'],
'SolrException::__clone' => ['void'],
'SolrException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrException::__toString' => ['string'],
'SolrException::__wakeup' => ['void'],
'SolrException::getCode' => ['int'],
'SolrException::getFile' => ['string'],
'SolrException::getInternalInfo' => ['array'],
'SolrException::getLine' => ['int'],
'SolrException::getMessage' => ['string'],
'SolrException::getPrevious' => ['Exception|Throwable'],
'SolrException::getTrace' => ['list<array<string,mixed>>'],
'SolrException::getTraceAsString' => ['string'],
'SolrGenericResponse::__construct' => ['void'],
'SolrGenericResponse::__destruct' => ['void'],
'SolrGenericResponse::getDigestedResponse' => ['string'],
'SolrGenericResponse::getHttpStatus' => ['int'],
'SolrGenericResponse::getHttpStatusMessage' => ['string'],
'SolrGenericResponse::getRawRequest' => ['string'],
'SolrGenericResponse::getRawRequestHeaders' => ['string'],
'SolrGenericResponse::getRawResponse' => ['string'],
'SolrGenericResponse::getRawResponseHeaders' => ['string'],
'SolrGenericResponse::getRequestUrl' => ['string'],
'SolrGenericResponse::getResponse' => ['SolrObject'],
'SolrGenericResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrGenericResponse::success' => ['bool'],
'SolrIllegalArgumentException::__clone' => ['void'],
'SolrIllegalArgumentException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrIllegalArgumentException::__toString' => ['string'],
'SolrIllegalArgumentException::__wakeup' => ['void'],
'SolrIllegalArgumentException::getCode' => ['int'],
'SolrIllegalArgumentException::getFile' => ['string'],
'SolrIllegalArgumentException::getInternalInfo' => ['array'],
'SolrIllegalArgumentException::getLine' => ['int'],
'SolrIllegalArgumentException::getMessage' => ['string'],
'SolrIllegalArgumentException::getPrevious' => ['Exception|Throwable'],
'SolrIllegalArgumentException::getTrace' => ['list<array<string,mixed>>'],
'SolrIllegalArgumentException::getTraceAsString' => ['string'],
'SolrIllegalOperationException::__clone' => ['void'],
'SolrIllegalOperationException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrIllegalOperationException::__toString' => ['string'],
'SolrIllegalOperationException::__wakeup' => ['void'],
'SolrIllegalOperationException::getCode' => ['int'],
'SolrIllegalOperationException::getFile' => ['string'],
'SolrIllegalOperationException::getInternalInfo' => ['array'],
'SolrIllegalOperationException::getLine' => ['int'],
'SolrIllegalOperationException::getMessage' => ['string'],
'SolrIllegalOperationException::getPrevious' => ['Exception|Throwable'],
'SolrIllegalOperationException::getTrace' => ['list<array<string,mixed>>'],
'SolrIllegalOperationException::getTraceAsString' => ['string'],
'SolrInputDocument::__clone' => ['void'],
'SolrInputDocument::__construct' => ['void'],
'SolrInputDocument::__destruct' => ['void'],
'SolrInputDocument::addChildDocument' => ['void', 'child'=>'SolrInputDocument'],
'SolrInputDocument::addChildDocuments' => ['void', 'docs'=>'array'],
'SolrInputDocument::addField' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string', 'fieldboostvalue='=>'float'],
'SolrInputDocument::clear' => ['bool'],
'SolrInputDocument::deleteField' => ['bool', 'fieldname'=>'string'],
'SolrInputDocument::fieldExists' => ['bool', 'fieldname'=>'string'],
'SolrInputDocument::getBoost' => ['float|false'],
'SolrInputDocument::getChildDocuments' => ['SolrInputDocument[]'],
'SolrInputDocument::getChildDocumentsCount' => ['int'],
'SolrInputDocument::getField' => ['SolrDocumentField|false', 'fieldname'=>'string'],
'SolrInputDocument::getFieldBoost' => ['float|false', 'fieldname'=>'string'],
'SolrInputDocument::getFieldCount' => ['int|false'],
'SolrInputDocument::getFieldNames' => ['array|false'],
'SolrInputDocument::hasChildDocuments' => ['bool'],
'SolrInputDocument::merge' => ['bool', 'sourcedoc'=>'SolrInputDocument', 'overwrite='=>'bool'],
'SolrInputDocument::reset' => ['bool'],
'SolrInputDocument::setBoost' => ['bool', 'documentboostvalue'=>'float'],
'SolrInputDocument::setFieldBoost' => ['bool', 'fieldname'=>'string', 'fieldboostvalue'=>'float'],
'SolrInputDocument::sort' => ['bool', 'sortorderby'=>'int', 'sortdirection='=>'int'],
'SolrInputDocument::toArray' => ['array|false'],
'SolrModifiableParams::__construct' => ['void'],
'SolrModifiableParams::__destruct' => ['void'],
'SolrModifiableParams::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrModifiableParams::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrModifiableParams::get' => ['mixed', 'param_name'=>'string'],
'SolrModifiableParams::getParam' => ['mixed', 'param_name'=>'string'],
'SolrModifiableParams::getParams' => ['array'],
'SolrModifiableParams::getPreparedParams' => ['array'],
'SolrModifiableParams::serialize' => ['string'],
'SolrModifiableParams::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrModifiableParams::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrModifiableParams::toString' => ['string', 'url_encode='=>'bool'],
'SolrModifiableParams::unserialize' => ['void', 'serialized'=>'string'],
'SolrObject::__construct' => ['void'],
'SolrObject::__destruct' => ['void'],
'SolrObject::getPropertyNames' => ['array'],
'SolrObject::offsetExists' => ['bool', 'property_name'=>'string'],
'SolrObject::offsetGet' => ['SolrDocumentField', 'property_name'=>'string'],
'SolrObject::offsetSet' => ['void', 'property_name'=>'string', 'property_value'=>'string'],
'SolrObject::offsetUnset' => ['void', 'property_name'=>'string'],
'SolrParams::__construct' => ['void'],
'SolrParams::add' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::addParam' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::get' => ['mixed', 'param_name'=>'string'],
'SolrParams::getParam' => ['mixed', 'param_name='=>'string'],
'SolrParams::getParams' => ['array'],
'SolrParams::getPreparedParams' => ['array'],
'SolrParams::serialize' => ['string'],
'SolrParams::set' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::setParam' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::toString' => ['string|false', 'url_encode='=>'bool'],
'SolrParams::unserialize' => ['void', 'serialized'=>'string'],
'SolrPingResponse::__construct' => ['void'],
'SolrPingResponse::__destruct' => ['void'],
'SolrPingResponse::getDigestedResponse' => ['string'],
'SolrPingResponse::getHttpStatus' => ['int'],
'SolrPingResponse::getHttpStatusMessage' => ['string'],
'SolrPingResponse::getRawRequest' => ['string'],
'SolrPingResponse::getRawRequestHeaders' => ['string'],
'SolrPingResponse::getRawResponse' => ['string'],
'SolrPingResponse::getRawResponseHeaders' => ['string'],
'SolrPingResponse::getRequestUrl' => ['string'],
'SolrPingResponse::getResponse' => ['string'],
'SolrPingResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrPingResponse::success' => ['bool'],
'SolrQuery::__construct' => ['void', 'q='=>'string'],
'SolrQuery::__destruct' => ['void'],
'SolrQuery::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrQuery::addExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::addExpandSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'string'],
'SolrQuery::addFacetDateField' => ['SolrQuery', 'datefield'=>'string'],
'SolrQuery::addFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::addFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addFacetQuery' => ['SolrQuery', 'facetquery'=>'string'],
'SolrQuery::addField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::addGroupField' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupFunction' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupQuery' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrQuery::addHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addMltField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addMltQueryField' => ['SolrQuery', 'field'=>'string', 'boost'=>'float'],
'SolrQuery::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrQuery::addSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrQuery::addStatsFacet' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::collapse' => ['SolrQuery', 'collapseFunction'=>'SolrCollapseFunction'],
'SolrQuery::get' => ['mixed', 'param_name'=>'string'],
'SolrQuery::getExpand' => ['bool'],
'SolrQuery::getExpandFilterQueries' => ['array'],
'SolrQuery::getExpandQuery' => ['array'],
'SolrQuery::getExpandRows' => ['int'],
'SolrQuery::getExpandSortFields' => ['array'],
'SolrQuery::getFacet' => ['?bool'],
'SolrQuery::getFacetDateEnd' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateFields' => ['array'],
'SolrQuery::getFacetDateGap' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateHardEnd' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateOther' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateStart' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetFields' => ['array'],
'SolrQuery::getFacetLimit' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetMethod' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetMinCount' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetMissing' => ['?bool', 'field_override='=>'string'],
'SolrQuery::getFacetOffset' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetPrefix' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetQueries' => ['?array'],
'SolrQuery::getFacetSort' => ['int', 'field_override='=>'string'],
'SolrQuery::getFields' => ['?array'],
'SolrQuery::getFilterQueries' => ['?array'],
'SolrQuery::getGroup' => ['bool'],
'SolrQuery::getGroupCachePercent' => ['int'],
'SolrQuery::getGroupFacet' => ['bool'],
'SolrQuery::getGroupFields' => ['array'],
'SolrQuery::getGroupFormat' => ['string'],
'SolrQuery::getGroupFunctions' => ['array'],
'SolrQuery::getGroupLimit' => ['int'],
'SolrQuery::getGroupMain' => ['bool'],
'SolrQuery::getGroupNGroups' => ['bool'],
'SolrQuery::getGroupOffset' => ['int'],
'SolrQuery::getGroupQueries' => ['array'],
'SolrQuery::getGroupSortFields' => ['array'],
'SolrQuery::getGroupTruncate' => ['bool'],
'SolrQuery::getHighlight' => ['bool'],
'SolrQuery::getHighlightAlternateField' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFields' => ['?array'],
'SolrQuery::getHighlightFormatter' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFragmenter' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFragsize' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightHighlightMultiTerm' => ['?bool'],
'SolrQuery::getHighlightMaxAlternateFieldLength' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightMaxAnalyzedChars' => ['?int'],
'SolrQuery::getHighlightMergeContiguous' => ['?bool', 'field_override='=>'string'],
'SolrQuery::getHighlightRegexMaxAnalyzedChars' => ['?int'],
'SolrQuery::getHighlightRegexPattern' => ['?string'],
'SolrQuery::getHighlightRegexSlop' => ['?float'],
'SolrQuery::getHighlightRequireFieldMatch' => ['?bool'],
'SolrQuery::getHighlightSimplePost' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightSimplePre' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightSnippets' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightUsePhraseHighlighter' => ['?bool'],
'SolrQuery::getMlt' => ['?bool'],
'SolrQuery::getMltBoost' => ['?bool'],
'SolrQuery::getMltCount' => ['?int'],
'SolrQuery::getMltFields' => ['?array'],
'SolrQuery::getMltMaxNumQueryTerms' => ['?int'],
'SolrQuery::getMltMaxNumTokens' => ['?int'],
'SolrQuery::getMltMaxWordLength' => ['?int'],
'SolrQuery::getMltMinDocFrequency' => ['?int'],
'SolrQuery::getMltMinTermFrequency' => ['?int'],
'SolrQuery::getMltMinWordLength' => ['?int'],
'SolrQuery::getMltQueryFields' => ['?array'],
'SolrQuery::getParam' => ['?mixed', 'param_name'=>'string'],
'SolrQuery::getParams' => ['?array'],
'SolrQuery::getPreparedParams' => ['?array'],
'SolrQuery::getQuery' => ['?string'],
'SolrQuery::getRows' => ['?int'],
'SolrQuery::getSortFields' => ['?array'],
'SolrQuery::getStart' => ['?int'],
'SolrQuery::getStats' => ['?bool'],
'SolrQuery::getStatsFacets' => ['?array'],
'SolrQuery::getStatsFields' => ['?array'],
'SolrQuery::getTerms' => ['?bool'],
'SolrQuery::getTermsField' => ['?string'],
'SolrQuery::getTermsIncludeLowerBound' => ['?bool'],
'SolrQuery::getTermsIncludeUpperBound' => ['?bool'],
'SolrQuery::getTermsLimit' => ['?int'],
'SolrQuery::getTermsLowerBound' => ['?string'],
'SolrQuery::getTermsMaxCount' => ['?int'],
'SolrQuery::getTermsMinCount' => ['?int'],
'SolrQuery::getTermsPrefix' => ['?string'],
'SolrQuery::getTermsReturnRaw' => ['?bool'],
'SolrQuery::getTermsSort' => ['?int'],
'SolrQuery::getTermsUpperBound' => ['?string'],
'SolrQuery::getTimeAllowed' => ['?int'],
'SolrQuery::removeExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::removeExpandSortField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetDateField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::removeFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetQuery' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::removeField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::removeHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeMltField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeMltQueryField' => ['SolrQuery', 'queryfield'=>'string'],
'SolrQuery::removeSortField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeStatsFacet' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::removeStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::serialize' => ['string'],
'SolrQuery::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrQuery::setEchoHandler' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setEchoParams' => ['SolrQuery', 'type'=>'string'],
'SolrQuery::setExpand' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setExpandQuery' => ['SolrQuery', 'q'=>'string'],
'SolrQuery::setExpandRows' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setExplainOther' => ['SolrQuery', 'query'=>'string'],
'SolrQuery::setFacet' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setFacetDateEnd' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetDateGap' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetDateHardEnd' => ['SolrQuery', 'value'=>'bool', 'field_override='=>'string'],
'SolrQuery::setFacetDateStart' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetEnumCacheMinDefaultFrequency' => ['SolrQuery', 'frequency'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetLimit' => ['SolrQuery', 'limit'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetMethod' => ['SolrQuery', 'method'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetMinCount' => ['SolrQuery', 'mincount'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetMissing' => ['SolrQuery', 'flag'=>'bool', 'field_override='=>'string'],
'SolrQuery::setFacetOffset' => ['SolrQuery', 'offset'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetPrefix' => ['SolrQuery', 'prefix'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetSort' => ['SolrQuery', 'facetsort'=>'int', 'field_override='=>'string'],
'SolrQuery::setGroup' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupCachePercent' => ['SolrQuery', 'percent'=>'int'],
'SolrQuery::setGroupFacet' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupFormat' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setGroupLimit' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setGroupMain' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setGroupNGroups' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupOffset' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setGroupTruncate' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setHighlight' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightAlternateField' => ['SolrQuery', 'field'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFormatter' => ['SolrQuery', 'formatter'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFragmenter' => ['SolrQuery', 'fragmenter'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFragsize' => ['SolrQuery', 'size'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightHighlightMultiTerm' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightMaxAlternateFieldLength' => ['SolrQuery', 'fieldlength'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightMaxAnalyzedChars' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setHighlightMergeContiguous' => ['SolrQuery', 'flag'=>'bool', 'field_override='=>'string'],
'SolrQuery::setHighlightRegexMaxAnalyzedChars' => ['SolrQuery', 'maxanalyzedchars'=>'int'],
'SolrQuery::setHighlightRegexPattern' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setHighlightRegexSlop' => ['SolrQuery', 'factor'=>'float'],
'SolrQuery::setHighlightRequireFieldMatch' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightSimplePost' => ['SolrQuery', 'simplepost'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightSimplePre' => ['SolrQuery', 'simplepre'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightSnippets' => ['SolrQuery', 'value'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightUsePhraseHighlighter' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMlt' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMltBoost' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMltCount' => ['SolrQuery', 'count'=>'int'],
'SolrQuery::setMltMaxNumQueryTerms' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setMltMaxNumTokens' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setMltMaxWordLength' => ['SolrQuery', 'maxwordlength'=>'int'],
'SolrQuery::setMltMinDocFrequency' => ['SolrQuery', 'mindocfrequency'=>'int'],
'SolrQuery::setMltMinTermFrequency' => ['SolrQuery', 'mintermfrequency'=>'int'],
'SolrQuery::setMltMinWordLength' => ['SolrQuery', 'minwordlength'=>'int'],
'SolrQuery::setOmitHeader' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrQuery::setQuery' => ['SolrQuery', 'query'=>'string'],
'SolrQuery::setRows' => ['SolrQuery', 'rows'=>'int'],
'SolrQuery::setShowDebugInfo' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setStart' => ['SolrQuery', 'start'=>'int'],
'SolrQuery::setStats' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTerms' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsField' => ['SolrQuery', 'fieldname'=>'string'],
'SolrQuery::setTermsIncludeLowerBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsIncludeUpperBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsLimit' => ['SolrQuery', 'limit'=>'int'],
'SolrQuery::setTermsLowerBound' => ['SolrQuery', 'lowerbound'=>'string'],
'SolrQuery::setTermsMaxCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrQuery::setTermsMinCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrQuery::setTermsPrefix' => ['SolrQuery', 'prefix'=>'string'],
'SolrQuery::setTermsReturnRaw' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsSort' => ['SolrQuery', 'sorttype'=>'int'],
'SolrQuery::setTermsUpperBound' => ['SolrQuery', 'upperbound'=>'string'],
'SolrQuery::setTimeAllowed' => ['SolrQuery', 'timeallowed'=>'int'],
'SolrQuery::toString' => ['string', 'url_encode='=>'bool'],
'SolrQuery::unserialize' => ['void', 'serialized'=>'string'],
'SolrQueryResponse::__construct' => ['void'],
'SolrQueryResponse::__destruct' => ['void'],
'SolrQueryResponse::getDigestedResponse' => ['string'],
'SolrQueryResponse::getHttpStatus' => ['int'],
'SolrQueryResponse::getHttpStatusMessage' => ['string'],
'SolrQueryResponse::getRawRequest' => ['string'],
'SolrQueryResponse::getRawRequestHeaders' => ['string'],
'SolrQueryResponse::getRawResponse' => ['string'],
'SolrQueryResponse::getRawResponseHeaders' => ['string'],
'SolrQueryResponse::getRequestUrl' => ['string'],
'SolrQueryResponse::getResponse' => ['SolrObject'],
'SolrQueryResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrQueryResponse::success' => ['bool'],
'SolrResponse::getDigestedResponse' => ['string'],
'SolrResponse::getHttpStatus' => ['int'],
'SolrResponse::getHttpStatusMessage' => ['string'],
'SolrResponse::getRawRequest' => ['string'],
'SolrResponse::getRawRequestHeaders' => ['string'],
'SolrResponse::getRawResponse' => ['string'],
'SolrResponse::getRawResponseHeaders' => ['string'],
'SolrResponse::getRequestUrl' => ['string'],
'SolrResponse::getResponse' => ['SolrObject'],
'SolrResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrResponse::success' => ['bool'],
'SolrServerException::__clone' => ['void'],
'SolrServerException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrServerException::__toString' => ['string'],
'SolrServerException::__wakeup' => ['void'],
'SolrServerException::getCode' => ['int'],
'SolrServerException::getFile' => ['string'],
'SolrServerException::getInternalInfo' => ['array'],
'SolrServerException::getLine' => ['int'],
'SolrServerException::getMessage' => ['string'],
'SolrServerException::getPrevious' => ['Exception|Throwable'],
'SolrServerException::getTrace' => ['list<array<string,mixed>>'],
'SolrServerException::getTraceAsString' => ['string'],
'SolrUpdateResponse::__construct' => ['void'],
'SolrUpdateResponse::__destruct' => ['void'],
'SolrUpdateResponse::getDigestedResponse' => ['string'],
'SolrUpdateResponse::getHttpStatus' => ['int'],
'SolrUpdateResponse::getHttpStatusMessage' => ['string'],
'SolrUpdateResponse::getRawRequest' => ['string'],
'SolrUpdateResponse::getRawRequestHeaders' => ['string'],
'SolrUpdateResponse::getRawResponse' => ['string'],
'SolrUpdateResponse::getRawResponseHeaders' => ['string'],
'SolrUpdateResponse::getRequestUrl' => ['string'],
'SolrUpdateResponse::getResponse' => ['SolrObject'],
'SolrUpdateResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrUpdateResponse::success' => ['bool'],
'SolrUtils::digestXmlResponse' => ['SolrObject', 'xmlresponse'=>'string', 'parse_mode='=>'int'],
'SolrUtils::escapeQueryChars' => ['string|false', 'string'=>'string'],
'SolrUtils::getSolrVersion' => ['string'],
'SolrUtils::queryPhrase' => ['string', 'string'=>'string'],
'sort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'soundex' => ['string', 'string'=>'string'],
'SphinxClient::__construct' => ['void'],
'SphinxClient::addQuery' => ['int', 'query'=>'string', 'index='=>'string', 'comment='=>'string'],
'SphinxClient::buildExcerpts' => ['array', 'docs'=>'array', 'index'=>'string', 'words'=>'string', 'opts='=>'array'],
'SphinxClient::buildKeywords' => ['array', 'query'=>'string', 'index'=>'string', 'hits'=>'bool'],
'SphinxClient::close' => ['bool'],
'SphinxClient::escapeString' => ['string', 'string'=>'string'],
'SphinxClient::getLastError' => ['string'],
'SphinxClient::getLastWarning' => ['string'],
'SphinxClient::open' => ['bool'],
'SphinxClient::query' => ['array', 'query'=>'string', 'index='=>'string', 'comment='=>'string'],
'SphinxClient::resetFilters' => ['void'],
'SphinxClient::resetGroupBy' => ['void'],
'SphinxClient::runQueries' => ['array'],
'SphinxClient::setArrayResult' => ['bool', 'array_result'=>'bool'],
'SphinxClient::setConnectTimeout' => ['bool', 'timeout'=>'float'],
'SphinxClient::setFieldWeights' => ['bool', 'weights'=>'array'],
'SphinxClient::setFilter' => ['bool', 'attribute'=>'string', 'values'=>'array', 'exclude='=>'bool'],
'SphinxClient::setFilterFloatRange' => ['bool', 'attribute'=>'string', 'min'=>'float', 'max'=>'float', 'exclude='=>'bool'],
'SphinxClient::setFilterRange' => ['bool', 'attribute'=>'string', 'min'=>'int', 'max'=>'int', 'exclude='=>'bool'],
'SphinxClient::setGeoAnchor' => ['bool', 'attrlat'=>'string', 'attrlong'=>'string', 'latitude'=>'float', 'longitude'=>'float'],
'SphinxClient::setGroupBy' => ['bool', 'attribute'=>'string', 'func'=>'int', 'groupsort='=>'string'],
'SphinxClient::setGroupDistinct' => ['bool', 'attribute'=>'string'],
'SphinxClient::setIDRange' => ['bool', 'min'=>'int', 'max'=>'int'],
'SphinxClient::setIndexWeights' => ['bool', 'weights'=>'array'],
'SphinxClient::setLimits' => ['bool', 'offset'=>'int', 'limit'=>'int', 'max_matches='=>'int', 'cutoff='=>'int'],
'SphinxClient::setMatchMode' => ['bool', 'mode'=>'int'],
'SphinxClient::setMaxQueryTime' => ['bool', 'qtime'=>'int'],
'SphinxClient::setOverride' => ['bool', 'attribute'=>'string', 'type'=>'int', 'values'=>'array'],
'SphinxClient::setRankingMode' => ['bool', 'ranker'=>'int'],
'SphinxClient::setRetries' => ['bool', 'count'=>'int', 'delay='=>'int'],
'SphinxClient::setSelect' => ['bool', 'clause'=>'string'],
'SphinxClient::setServer' => ['bool', 'server'=>'string', 'port'=>'int'],
'SphinxClient::setSortMode' => ['bool', 'mode'=>'int', 'sortby='=>'string'],
'SphinxClient::status' => ['array'],
'SphinxClient::updateAttributes' => ['int', 'index'=>'string', 'attributes'=>'array', 'values'=>'array', 'mva='=>'bool'],
'spl_autoload' => ['void', 'class'=>'string', 'file_extensions='=>'string'],
'spl_autoload_call' => ['void', 'class'=>'string'],
'spl_autoload_extensions' => ['string', 'file_extensions='=>'string'],
'spl_autoload_functions' => ['false|array'],
'spl_autoload_register' => ['bool', 'callback='=>'callable(string):void', 'throw='=>'bool', 'prepend='=>'bool'],
'spl_autoload_unregister' => ['bool', 'callback'=>'mixed'],
'spl_classes' => ['array'],
'spl_object_hash' => ['string', 'object'=>'object'],
'spl_object_id' => ['int', 'object'=>'object'],
'SplDoublyLinkedList::__construct' => ['void'],
'SplDoublyLinkedList::add' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplDoublyLinkedList::bottom' => ['mixed'],
'SplDoublyLinkedList::count' => ['int'],
'SplDoublyLinkedList::current' => ['mixed'],
'SplDoublyLinkedList::getIteratorMode' => ['int'],
'SplDoublyLinkedList::isEmpty' => ['bool'],
'SplDoublyLinkedList::key' => ['mixed'],
'SplDoublyLinkedList::next' => ['void'],
'SplDoublyLinkedList::offsetExists' => ['bool', 'index'=>'mixed'],
'SplDoublyLinkedList::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplDoublyLinkedList::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplDoublyLinkedList::offsetUnset' => ['void', 'index'=>'mixed'],
'SplDoublyLinkedList::pop' => ['mixed'],
'SplDoublyLinkedList::prev' => ['void'],
'SplDoublyLinkedList::push' => ['void', 'value'=>'mixed'],
'SplDoublyLinkedList::rewind' => ['void'],
'SplDoublyLinkedList::serialize' => ['string'],
'SplDoublyLinkedList::setIteratorMode' => ['void', 'flags'=>'int'],
'SplDoublyLinkedList::shift' => ['mixed'],
'SplDoublyLinkedList::top' => ['mixed'],
'SplDoublyLinkedList::unserialize' => ['void', 'serialized'=>'string'],
'SplDoublyLinkedList::unshift' => ['bool', 'value'=>'mixed'],
'SplDoublyLinkedList::valid' => ['bool'],
'SplEnum::__construct' => ['void', 'initial_value='=>'mixed', 'strict='=>'bool'],
'SplEnum::getConstList' => ['array', 'include_default='=>'bool'],
'SplFileInfo::__construct' => ['void', 'file_name'=>'string'],
'SplFileInfo::__toString' => ['string'],
'SplFileInfo::__wakeup' => ['void'],
'SplFileInfo::getATime' => ['int'],
'SplFileInfo::getBasename' => ['string', 'suffix='=>'string'],
'SplFileInfo::getCTime' => ['int'],
'SplFileInfo::getExtension' => ['string'],
'SplFileInfo::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileInfo::getFilename' => ['string'],
'SplFileInfo::getGroup' => ['int'],
'SplFileInfo::getInode' => ['int'],
'SplFileInfo::getLinkTarget' => ['string'],
'SplFileInfo::getMTime' => ['int'],
'SplFileInfo::getOwner' => ['int'],
'SplFileInfo::getPath' => ['string'],
'SplFileInfo::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileInfo::getPathname' => ['string'],
'SplFileInfo::getPerms' => ['int'],
'SplFileInfo::getRealPath' => ['string|false'],
'SplFileInfo::getSize' => ['int'],
'SplFileInfo::getType' => ['string'],
'SplFileInfo::isDir' => ['bool'],
'SplFileInfo::isExecutable' => ['bool'],
'SplFileInfo::isFile' => ['bool'],
'SplFileInfo::isLink' => ['bool'],
'SplFileInfo::isReadable' => ['bool'],
'SplFileInfo::isWritable' => ['bool'],
'SplFileInfo::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplFileInfo::setFileClass' => ['void', 'class_name='=>'string'],
'SplFileInfo::setInfoClass' => ['void', 'class_name='=>'string'],
'SplFileObject::__construct' => ['void', 'filename'=>'string', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>''],
'SplFileObject::__toString' => ['string'],
'SplFileObject::current' => ['string|array|false'],
'SplFileObject::eof' => ['bool'],
'SplFileObject::fflush' => ['bool'],
'SplFileObject::fgetc' => ['string|false'],
'SplFileObject::fgetcsv' => ['list<string>|array{0: null}|false|null', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::fgets' => ['string|false'],
'SplFileObject::fgetss' => ['string|false', 'allowable_tags='=>'string'],
'SplFileObject::flock' => ['bool', 'operation'=>'int', '&w_wouldblock='=>'int'],
'SplFileObject::fpassthru' => ['int|false'],
'SplFileObject::fputcsv' => ['int|false', 'fields'=>'array', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::fread' => ['string|false', 'length'=>'int'],
'SplFileObject::fscanf' => ['array|int', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'SplFileObject::fseek' => ['int', 'pos'=>'int', 'whence='=>'int'],
'SplFileObject::fstat' => ['array|false'],
'SplFileObject::ftell' => ['int|false'],
'SplFileObject::ftruncate' => ['bool', 'size'=>'int'],
'SplFileObject::fwrite' => ['int', 'string'=>'string', 'length='=>'int'],
'SplFileObject::getATime' => ['int'],
'SplFileObject::getBasename' => ['string', 'suffix='=>'string'],
'SplFileObject::getChildren' => ['null'],
'SplFileObject::getCsvControl' => ['array'],
'SplFileObject::getCTime' => ['int'],
'SplFileObject::getCurrentLine' => ['string|false'],
'SplFileObject::getExtension' => ['string'],
'SplFileObject::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileObject::getFilename' => ['string'],
'SplFileObject::getFlags' => ['int'],
'SplFileObject::getGroup' => ['int'],
'SplFileObject::getInode' => ['int'],
'SplFileObject::getLinkTarget' => ['string'],
'SplFileObject::getMaxLineLen' => ['int'],
'SplFileObject::getMTime' => ['int'],
'SplFileObject::getOwner' => ['int'],
'SplFileObject::getPath' => ['string'],
'SplFileObject::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileObject::getPathname' => ['string'],
'SplFileObject::getPerms' => ['int'],
'SplFileObject::getRealPath' => ['false|string'],
'SplFileObject::getSize' => ['int'],
'SplFileObject::getType' => ['string'],
'SplFileObject::hasChildren' => ['false'],
'SplFileObject::isDir' => ['bool'],
'SplFileObject::isExecutable' => ['bool'],
'SplFileObject::isFile' => ['bool'],
'SplFileObject::isLink' => ['bool'],
'SplFileObject::isReadable' => ['bool'],
'SplFileObject::isWritable' => ['bool'],
'SplFileObject::key' => ['int'],
'SplFileObject::next' => ['void'],
'SplFileObject::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplFileObject::rewind' => ['void'],
'SplFileObject::seek' => ['void', 'line_pos'=>'int'],
'SplFileObject::setCsvControl' => ['void', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::setFileClass' => ['void', 'class_name='=>'string'],
'SplFileObject::setFlags' => ['void', 'flags'=>'int'],
'SplFileObject::setInfoClass' => ['void', 'class_name='=>'string'],
'SplFileObject::setMaxLineLen' => ['void', 'max_len'=>'int'],
'SplFileObject::valid' => ['bool'],
'SplFixedArray::__construct' => ['void', 'size='=>'int'],
'SplFixedArray::__wakeup' => ['void'],
'SplFixedArray::count' => ['int'],
'SplFixedArray::current' => ['mixed'],
'SplFixedArray::fromArray' => ['SplFixedArray', 'data'=>'array', 'save_indexes='=>'bool'],
'SplFixedArray::getSize' => ['int'],
'SplFixedArray::key' => ['int'],
'SplFixedArray::next' => ['void'],
'SplFixedArray::offsetExists' => ['bool', 'index'=>'int'],
'SplFixedArray::offsetGet' => ['mixed', 'index'=>'int'],
'SplFixedArray::offsetSet' => ['void', 'index'=>'int', 'newval'=>'mixed'],
'SplFixedArray::offsetUnset' => ['void', 'index'=>'int'],
'SplFixedArray::rewind' => ['void'],
'SplFixedArray::setSize' => ['bool', 'size'=>'int'],
'SplFixedArray::toArray' => ['array'],
'SplFixedArray::valid' => ['bool'],
'SplHeap::__construct' => ['void'],
'SplHeap::compare' => ['int', 'value1'=>'mixed', 'value2'=>'mixed'],
'SplHeap::count' => ['int'],
'SplHeap::current' => ['mixed'],
'SplHeap::extract' => ['mixed'],
'SplHeap::insert' => ['bool', 'value'=>'mixed'],
'SplHeap::isCorrupted' => ['bool'],
'SplHeap::isEmpty' => ['bool'],
'SplHeap::key' => ['int'],
'SplHeap::next' => ['void'],
'SplHeap::recoverFromCorruption' => ['int'],
'SplHeap::rewind' => ['void'],
'SplHeap::top' => ['mixed'],
'SplHeap::valid' => ['bool'],
'SplMaxHeap::__construct' => ['void'],
'SplMaxHeap::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplMinHeap::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplMinHeap::count' => ['int'],
'SplMinHeap::current' => ['mixed'],
'SplMinHeap::extract' => ['mixed'],
'SplMinHeap::insert' => ['void', 'value'=>'mixed'],
'SplMinHeap::isCorrupted' => ['int'],
'SplMinHeap::isEmpty' => ['bool'],
'SplMinHeap::key' => ['mixed'],
'SplMinHeap::next' => ['void'],
'SplMinHeap::recoverFromCorruption' => ['void'],
'SplMinHeap::rewind' => ['void'],
'SplMinHeap::top' => ['mixed'],
'SplMinHeap::valid' => ['bool'],
'SplObjectStorage::__construct' => ['void'],
'SplObjectStorage::addAll' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::attach' => ['void', 'object'=>'object', 'inf='=>'mixed'],
'SplObjectStorage::contains' => ['bool', 'object'=>'object'],
'SplObjectStorage::count' => ['int'],
'SplObjectStorage::current' => ['object'],
'SplObjectStorage::detach' => ['void', 'object'=>'object'],
'SplObjectStorage::getHash' => ['string', 'object'=>'object'],
'SplObjectStorage::getInfo' => ['mixed'],
'SplObjectStorage::key' => ['int'],
'SplObjectStorage::next' => ['void'],
'SplObjectStorage::offsetExists' => ['bool', 'object'=>'object'],
'SplObjectStorage::offsetGet' => ['mixed', 'object'=>'object'],
'SplObjectStorage::offsetSet' => ['object', 'object'=>'object', 'data='=>'mixed'],
'SplObjectStorage::offsetUnset' => ['object', 'object'=>'object'],
'SplObjectStorage::removeAll' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::removeAllExcept' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::rewind' => ['void'],
'SplObjectStorage::serialize' => ['string'],
'SplObjectStorage::setInfo' => ['void', 'inf'=>'mixed'],
'SplObjectStorage::unserialize' => ['void', 'serialized'=>'string'],
'SplObjectStorage::valid' => ['bool'],
'SplObserver::update' => ['void', 'subject'=>'SplSubject'],
'SplPriorityQueue::__construct' => ['void'],
'SplPriorityQueue::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplPriorityQueue::count' => ['int'],
'SplPriorityQueue::current' => ['mixed'],
'SplPriorityQueue::extract' => ['mixed'],
'SplPriorityQueue::getExtractFlags' => ['int'],
'SplPriorityQueue::insert' => ['bool', 'value'=>'mixed', 'priority'=>'mixed'],
'SplPriorityQueue::isCorrupted' => ['bool'],
'SplPriorityQueue::isEmpty' => ['bool'],
'SplPriorityQueue::key' => ['mixed'],
'SplPriorityQueue::next' => ['void'],
'SplPriorityQueue::recoverFromCorruption' => ['void'],
'SplPriorityQueue::rewind' => ['void'],
'SplPriorityQueue::setExtractFlags' => ['void', 'flags'=>'int'],
'SplPriorityQueue::top' => ['mixed'],
'SplPriorityQueue::valid' => ['bool'],
'SplQueue::dequeue' => ['mixed'],
'SplQueue::enqueue' => ['void', 'value'=>'mixed'],
'SplQueue::getIteratorMode' => ['int'],
'SplQueue::isEmpty' => ['bool'],
'SplQueue::key' => ['mixed'],
'SplQueue::next' => ['void'],
'SplQueue::offsetExists' => ['bool', 'index'=>'mixed'],
'SplQueue::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplQueue::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplQueue::offsetUnset' => ['void', 'index'=>'mixed'],
'SplQueue::pop' => ['mixed'],
'SplQueue::prev' => ['void'],
'SplQueue::push' => ['void', 'value'=>'mixed'],
'SplQueue::rewind' => ['void'],
'SplQueue::serialize' => ['string'],
'SplQueue::setIteratorMode' => ['void', 'mode'=>'int'],
'SplQueue::shift' => ['mixed'],
'SplQueue::top' => ['mixed'],
'SplQueue::unserialize' => ['void', 'serialized'=>'string'],
'SplQueue::unshift' => ['bool', 'value'=>'mixed'],
'SplQueue::valid' => ['bool'],
'SplStack::__construct' => ['void'],
'SplStack::add' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplStack::bottom' => ['mixed'],
'SplStack::count' => ['int'],
'SplStack::current' => ['mixed'],
'SplStack::getIteratorMode' => ['int'],
'SplStack::isEmpty' => ['bool'],
'SplStack::key' => ['mixed'],
'SplStack::next' => ['void'],
'SplStack::offsetExists' => ['bool', 'index'=>'mixed'],
'SplStack::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplStack::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplStack::offsetUnset' => ['void', 'index'=>'mixed'],
'SplStack::pop' => ['mixed'],
'SplStack::prev' => ['void'],
'SplStack::push' => ['void', 'value'=>'mixed'],
'SplStack::rewind' => ['void'],
'SplStack::serialize' => ['string'],
'SplStack::setIteratorMode' => ['void', 'mode'=>'int'],
'SplStack::shift' => ['mixed'],
'SplStack::top' => ['mixed'],
'SplStack::unserialize' => ['void', 'serialized'=>'string'],
'SplStack::unshift' => ['bool', 'value'=>'mixed'],
'SplStack::valid' => ['bool'],
'SplSubject::attach' => ['void', 'observer'=>'SplObserver'],
'SplSubject::detach' => ['void', 'observer'=>'SplObserver'],
'SplSubject::notify' => ['void'],
'SplTempFileObject::__construct' => ['void', 'max_memory='=>'int'],
'SplTempFileObject::__toString' => ['string'],
'SplTempFileObject::_bad_state_ex' => [''],
'SplTempFileObject::current' => ['array|false|string'],
'SplTempFileObject::eof' => ['bool'],
'SplTempFileObject::fflush' => ['bool'],
'SplTempFileObject::fgetc' => ['false|string'],
'SplTempFileObject::fgetcsv' => ['list<string>|array{0: null}|false|null', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::fgets' => ['string'],
'SplTempFileObject::fgetss' => ['string', 'allowable_tags='=>'string'],
'SplTempFileObject::flock' => ['bool', 'operation'=>'int', '&wouldblock='=>'int'],
'SplTempFileObject::fpassthru' => ['int|false'],
'SplTempFileObject::fputcsv' => ['false|int', 'fields'=>'array', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::fread' => ['false|string', 'length'=>'int'],
'SplTempFileObject::fscanf' => ['bool', 'format'=>'string', '&...w_vars='=>'array<int,float>|array<int,int>|array<int,string>'],
'SplTempFileObject::fseek' => ['int', 'pos'=>'int', 'whence='=>'int'],
'SplTempFileObject::fstat' => ['array|false'],
'SplTempFileObject::ftell' => ['int'],
'SplTempFileObject::ftruncate' => ['bool', 'size'=>'int'],
'SplTempFileObject::fwrite' => ['int', 'string'=>'string', 'length='=>'int'],
'SplTempFileObject::getATime' => ['int'],
'SplTempFileObject::getBasename' => ['string', 'suffix='=>'string'],
'SplTempFileObject::getChildren' => ['null'],
'SplTempFileObject::getCsvControl' => ['array'],
'SplTempFileObject::getCTime' => ['int'],
'SplTempFileObject::getCurrentLine' => ['string'],
'SplTempFileObject::getExtension' => ['string'],
'SplTempFileObject::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplTempFileObject::getFilename' => ['string'],
'SplTempFileObject::getFlags' => ['int'],
'SplTempFileObject::getGroup' => ['int'],
'SplTempFileObject::getInode' => ['int'],
'SplTempFileObject::getLinkTarget' => ['string'],
'SplTempFileObject::getMaxLineLen' => ['int'],
'SplTempFileObject::getMTime' => ['int'],
'SplTempFileObject::getOwner' => ['int'],
'SplTempFileObject::getPath' => ['string'],
'SplTempFileObject::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplTempFileObject::getPathname' => ['string'],
'SplTempFileObject::getPerms' => ['int'],
'SplTempFileObject::getRealPath' => ['string'],
'SplTempFileObject::getSize' => ['int'],
'SplTempFileObject::getType' => ['string'],
'SplTempFileObject::hasChildren' => ['bool'],
'SplTempFileObject::isDir' => ['bool'],
'SplTempFileObject::isExecutable' => ['bool'],
'SplTempFileObject::isFile' => ['bool'],
'SplTempFileObject::isLink' => ['bool'],
'SplTempFileObject::isReadable' => ['bool'],
'SplTempFileObject::isWritable' => ['bool'],
'SplTempFileObject::key' => ['int'],
'SplTempFileObject::next' => ['void'],
'SplTempFileObject::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplTempFileObject::rewind' => ['void'],
'SplTempFileObject::seek' => ['void', 'line_pos'=>'int'],
'SplTempFileObject::setCsvControl' => ['void', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::setFileClass' => ['void', 'class_name='=>'string'],
'SplTempFileObject::setFlags' => ['void', 'flags'=>'int'],
'SplTempFileObject::setInfoClass' => ['void', 'class_name='=>'string'],
'SplTempFileObject::setMaxLineLen' => ['void', 'max_len'=>'int'],
'SplTempFileObject::valid' => ['bool'],
'SplType::__construct' => ['void', 'initial_value='=>'mixed', 'strict='=>'bool'],
'Spoofchecker::__construct' => ['void'],
'Spoofchecker::areConfusable' => ['bool', 's1'=>'string', 's2'=>'string', '&w_error='=>'string'],
'Spoofchecker::isSuspicious' => ['bool', 'text'=>'string', '&w_error='=>'string'],
'Spoofchecker::setAllowedLocales' => ['void', 'locale_list'=>'string'],
'Spoofchecker::setChecks' => ['void', 'checks'=>'long'],
'Spoofchecker::setRestrictionLevel' => ['void', 'restriction_level'=>'int'],
'sprintf' => ['string', 'format'=>'string', '...values='=>'string|int|float'],
'SQLite3::__construct' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryptionKey='=>'?string'],
'SQLite3::busyTimeout' => ['bool', 'milliseconds'=>'int'],
'SQLite3::changes' => ['int'],
'SQLite3::close' => ['bool'],
'SQLite3::createAggregate' => ['bool', 'name'=>'string', 'stepCallback'=>'callable', 'finalCallback'=>'callable', 'argCount='=>'int'],
'SQLite3::createCollation' => ['bool', 'name'=>'string', 'callback'=>'callable'],
'SQLite3::createFunction' => ['bool', 'name'=>'string', 'callback'=>'callable', 'argCount='=>'int', 'flags='=>'int'],
'SQLite3::enableExceptions' => ['bool', 'enable='=>'bool'],
'SQLite3::escapeString' => ['string', 'string'=>'string'],
'SQLite3::exec' => ['bool', 'query'=>'string'],
'SQLite3::lastErrorCode' => ['int'],
'SQLite3::lastErrorMsg' => ['string'],
'SQLite3::lastInsertRowID' => ['int'],
'SQLite3::loadExtension' => ['bool', 'name'=>'string'],
'SQLite3::open' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryptionKey='=>'?string'],
'SQLite3::openBlob' => ['resource|false', 'table'=>'string', 'column'=>'string', 'rowid'=>'int', 'database='=>'string', 'flags='=>'int'],
'SQLite3::prepare' => ['SQLite3Stmt|false', 'query'=>'string'],
'SQLite3::query' => ['SQLite3Result|false', 'query'=>'string'],
'SQLite3::querySingle' => ['array|int|string|bool|float|null|false', 'query'=>'string', 'entireRow='=>'bool'],
'SQLite3::version' => ['array'],
'SQLite3Result::__construct' => ['void'],
'SQLite3Result::columnName' => ['string', 'column'=>'int'],
'SQLite3Result::columnType' => ['int', 'column'=>'int'],
'SQLite3Result::fetchArray' => ['array|false', 'mode='=>'int'],
'SQLite3Result::finalize' => ['bool'],
'SQLite3Result::numColumns' => ['int'],
'SQLite3Result::reset' => ['bool'],
'SQLite3Stmt::__construct' => ['void', 'sqlite3'=>'sqlite3', 'query'=>'string'],
'SQLite3Stmt::bindParam' => ['bool', 'param'=>'string|int', '&rw_var'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::bindValue' => ['bool', 'param'=>'string|int', 'value'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::clear' => ['bool'],
'SQLite3Stmt::close' => ['bool'],
'SQLite3Stmt::execute' => ['false|SQLite3Result'],
'SQLite3Stmt::getSQL' => ['string', 'expand='=>'bool'],
'SQLite3Stmt::paramCount' => ['int'],
'SQLite3Stmt::readOnly' => ['bool'],
'SQLite3Stmt::reset' => ['bool'],
'sqlite_array_query' => ['array|false', 'dbhandle'=>'resource', 'query'=>'string', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_busy_timeout' => ['void', 'dbhandle'=>'resource', 'milliseconds'=>'int'],
'sqlite_changes' => ['int', 'dbhandle'=>'resource'],
'sqlite_close' => ['void', 'dbhandle'=>'resource'],
'sqlite_column' => ['mixed', 'result'=>'resource', 'index_or_name'=>'mixed', 'decode_binary='=>'bool'],
'sqlite_create_aggregate' => ['void', 'dbhandle'=>'resource', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'sqlite_create_function' => ['void', 'dbhandle'=>'resource', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'sqlite_current' => ['array|false', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_error_string' => ['string', 'error_code'=>'int'],
'sqlite_escape_string' => ['string', 'item'=>'string'],
'sqlite_exec' => ['bool', 'dbhandle'=>'resource', 'query'=>'string', 'error_msg='=>'string'],
'sqlite_factory' => ['SQLiteDatabase', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_fetch_all' => ['array', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_fetch_array' => ['array|false', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_fetch_column_types' => ['array|false', 'table_name'=>'string', 'dbhandle'=>'resource', 'result_type='=>'int'],
'sqlite_fetch_object' => ['object', 'result'=>'resource', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'sqlite_fetch_single' => ['string', 'result'=>'resource', 'decode_binary='=>'bool'],
'sqlite_fetch_string' => ['string', 'result'=>'resource', 'decode_binary'=>'bool'],
'sqlite_field_name' => ['string', 'result'=>'resource', 'field_index'=>'int'],
'sqlite_has_more' => ['bool', 'result'=>'resource'],
'sqlite_has_prev' => ['bool', 'result'=>'resource'],
'sqlite_key' => ['int', 'result'=>'resource'],
'sqlite_last_error' => ['int', 'dbhandle'=>'resource'],
'sqlite_last_insert_rowid' => ['int', 'dbhandle'=>'resource'],
'sqlite_libencoding' => ['string'],
'sqlite_libversion' => ['string'],
'sqlite_next' => ['bool', 'result'=>'resource'],
'sqlite_num_fields' => ['int', 'result'=>'resource'],
'sqlite_num_rows' => ['int', 'result'=>'resource'],
'sqlite_open' => ['resource|false', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_popen' => ['resource|false', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_prev' => ['bool', 'result'=>'resource'],
'sqlite_query' => ['resource|false', 'dbhandle'=>'resource', 'query'=>'resource|string', 'result_type='=>'int', 'error_msg='=>'string'],
'sqlite_rewind' => ['bool', 'result'=>'resource'],
'sqlite_seek' => ['bool', 'result'=>'resource', 'rownum'=>'int'],
'sqlite_single_query' => ['array', 'db'=>'resource', 'query'=>'string', 'first_row_only='=>'bool', 'decode_binary='=>'bool'],
'sqlite_udf_decode_binary' => ['string', 'data'=>'string'],
'sqlite_udf_encode_binary' => ['string', 'data'=>'string'],
'sqlite_unbuffered_query' => ['SQLiteUnbuffered|false', 'dbhandle'=>'resource', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'sqlite_valid' => ['bool', 'result'=>'resource'],
'SQLiteDatabase::__construct' => ['void', 'filename'=>'', 'mode='=>'int|mixed', '&error_message'=>''],
'SQLiteDatabase::arrayQuery' => ['array', 'query'=>'string', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteDatabase::busyTimeout' => ['int', 'milliseconds'=>'int'],
'SQLiteDatabase::changes' => ['int'],
'SQLiteDatabase::createAggregate' => ['', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'SQLiteDatabase::createFunction' => ['', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'SQLiteDatabase::exec' => ['bool', 'query'=>'string', 'error_msg='=>'string'],
'SQLiteDatabase::fetchColumnTypes' => ['array', 'table_name'=>'string', 'result_type='=>'int'],
'SQLiteDatabase::lastError' => ['int'],
'SQLiteDatabase::lastInsertRowid' => ['int'],
'SQLiteDatabase::query' => ['SQLiteResult|false', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'SQLiteDatabase::queryExec' => ['bool', 'query'=>'string', '&w_error_msg='=>'string'],
'SQLiteDatabase::singleQuery' => ['array', 'query'=>'string', 'first_row_only='=>'bool', 'decode_binary='=>'bool'],
'SQLiteDatabase::unbufferedQuery' => ['SQLiteUnbuffered|false', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'SQLiteException::__clone' => ['void'],
'SQLiteException::__construct' => ['void', 'message'=>'', 'code'=>'', 'previous'=>''],
'SQLiteException::__toString' => ['string'],
'SQLiteException::__wakeup' => ['void'],
'SQLiteException::getCode' => ['int'],
'SQLiteException::getFile' => ['string'],
'SQLiteException::getLine' => ['int'],
'SQLiteException::getMessage' => ['string'],
'SQLiteException::getPrevious' => ['RuntimeException|Throwable|null'],
'SQLiteException::getTrace' => ['list<array<string,mixed>>'],
'SQLiteException::getTraceAsString' => ['string'],
'SQLiteResult::__construct' => ['void'],
'SQLiteResult::column' => ['mixed', 'index_or_name'=>'', 'decode_binary='=>'bool'],
'SQLiteResult::count' => ['int'],
'SQLiteResult::current' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetch' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetchAll' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetchObject' => ['object', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'SQLiteResult::fetchSingle' => ['string', 'decode_binary='=>'bool'],
'SQLiteResult::fieldName' => ['string', 'field_index'=>'int'],
'SQLiteResult::hasPrev' => ['bool'],
'SQLiteResult::key' => ['mixed|null'],
'SQLiteResult::next' => ['bool'],
'SQLiteResult::numFields' => ['int'],
'SQLiteResult::numRows' => ['int'],
'SQLiteResult::prev' => ['bool'],
'SQLiteResult::rewind' => ['bool'],
'SQLiteResult::seek' => ['bool', 'rownum'=>'int'],
'SQLiteResult::valid' => ['bool'],
'SQLiteUnbuffered::column' => ['void', 'index_or_name'=>'', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::current' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetch' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchAll' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchObject' => ['object', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchSingle' => ['string', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fieldName' => ['string', 'field_index'=>'int'],
'SQLiteUnbuffered::next' => ['bool'],
'SQLiteUnbuffered::numFields' => ['int'],
'SQLiteUnbuffered::valid' => ['bool'],
'sqlsrv_begin_transaction' => ['bool', 'conn'=>'resource'],
'sqlsrv_cancel' => ['bool', 'stmt'=>'resource'],
'sqlsrv_client_info' => ['array|false', 'conn'=>'resource'],
'sqlsrv_close' => ['bool', 'conn'=>'?resource'],
'sqlsrv_commit' => ['bool', 'conn'=>'resource'],
'sqlsrv_configure' => ['bool', 'setting'=>'string', 'value'=>'mixed'],
'sqlsrv_connect' => ['resource|false', 'serverName'=>'string', 'connectionInfo='=>'array'],
'sqlsrv_errors' => ['?array', 'errorsOrWarnings='=>'int'],
'sqlsrv_execute' => ['bool', 'stmt'=>'resource'],
'sqlsrv_fetch' => ['?bool', 'stmt'=>'resource', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_fetch_array' => ['array|null|false', 'stmt'=>'resource', 'fetchType='=>'int', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_fetch_object' => ['object|null|false', 'stmt'=>'resource', 'className='=>'string', 'ctorParams='=>'array', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_field_metadata' => ['array|false', 'stmt'=>'resource'],
'sqlsrv_free_stmt' => ['bool', 'stmt'=>'resource'],
'sqlsrv_get_config' => ['mixed', 'setting'=>'string'],
'sqlsrv_get_field' => ['mixed', 'stmt'=>'resource', 'fieldIndex'=>'int', 'getAsType='=>'int'],
'sqlsrv_has_rows' => ['bool', 'stmt'=>'resource'],
'sqlsrv_next_result' => ['?bool', 'stmt'=>'resource'],
'sqlsrv_num_fields' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_num_rows' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_prepare' => ['resource|false', 'conn'=>'resource', 'sql'=>'string', 'params='=>'array', 'options='=>'array'],
'sqlsrv_query' => ['resource|false', 'conn'=>'resource', 'sql'=>'string', 'params='=>'array', 'options='=>'array'],
'sqlsrv_rollback' => ['bool', 'conn'=>'resource'],
'sqlsrv_rows_affected' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_send_stream_data' => ['bool', 'stmt'=>'resource'],
'sqlsrv_server_info' => ['array', 'conn'=>'resource'],
'sqrt' => ['float', 'num'=>'float'],
'srand' => ['void', 'seed='=>'int', 'mode='=>'int'],
'sscanf' => ['list<mixed>|int', 'string'=>'string', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'ssdeep_fuzzy_compare' => ['int', 'signature1'=>'string', 'signature2'=>'string'],
'ssdeep_fuzzy_hash' => ['string', 'to_hash'=>'string'],
'ssdeep_fuzzy_hash_filename' => ['string', 'file_name'=>'string'],
'ssh2_auth_agent' => ['bool', 'session'=>'resource', 'username'=>'string'],
'ssh2_auth_hostbased_file' => ['bool', 'session'=>'resource', 'username'=>'string', 'hostname'=>'string', 'pubkeyfile'=>'string', 'privkeyfile'=>'string', 'passphrase='=>'string', 'local_username='=>'string'],
'ssh2_auth_none' => ['bool|string[]', 'session'=>'resource', 'username'=>'string'],
'ssh2_auth_password' => ['bool', 'session'=>'resource', 'username'=>'string', 'password'=>'string'],
'ssh2_auth_pubkey_file' => ['bool', 'session'=>'resource', 'username'=>'string', 'pubkeyfile'=>'string', 'privkeyfile'=>'string', 'passphrase='=>'string'],
'ssh2_connect' => ['resource|false', 'host'=>'string', 'port='=>'int', 'methods='=>'array', 'callbacks='=>'array'],
'ssh2_disconnect' => ['bool', 'session'=>'resource'],
'ssh2_exec' => ['resource|false', 'session'=>'resource', 'command'=>'string', 'pty='=>'string', 'env='=>'array', 'width='=>'int', 'height='=>'int', 'width_height_type='=>'int'],
'ssh2_fetch_stream' => ['resource|false', 'channel'=>'resource', 'streamid'=>'int'],
'ssh2_fingerprint' => ['string|false', 'session'=>'resource', 'flags='=>'int'],
'ssh2_forward_accept' => ['resource|false', 'session'=>'resource'],
'ssh2_forward_listen' => ['resource|false', 'session'=>'resource', 'port'=>'int', 'host='=>'string', 'max_connections='=>'string'],
'ssh2_methods_negotiated' => ['array|false', 'session'=>'resource'],
'ssh2_poll' => ['int', '&polldes'=>'array', 'timeout='=>'int'],
'ssh2_publickey_add' => ['bool', 'pkey'=>'resource', 'algoname'=>'string', 'blob'=>'string', 'overwrite='=>'bool', 'attributes='=>'array'],
'ssh2_publickey_init' => ['resource|false', 'session'=>'resource'],
'ssh2_publickey_list' => ['array|false', 'pkey'=>'resource'],
'ssh2_publickey_remove' => ['bool', 'pkey'=>'resource', 'algoname'=>'string', 'blob'=>'string'],
'ssh2_scp_recv' => ['bool', 'session'=>'resource', 'remote_file'=>'string', 'local_file'=>'string'],
'ssh2_scp_send' => ['bool', 'session'=>'resource', 'local_file'=>'string', 'remote_file'=>'string', 'create_mode='=>'int'],
'ssh2_sftp' => ['resource|false', 'session'=>'resource'],
'ssh2_sftp_chmod' => ['bool', 'sftp'=>'resource', 'filename'=>'string', 'mode'=>'int'],
'ssh2_sftp_lstat' => ['array|false', 'sftp'=>'resource', 'path'=>'string'],
'ssh2_sftp_mkdir' => ['bool', 'sftp'=>'resource', 'dirname'=>'string', 'mode='=>'int', 'recursive='=>'bool'],
'ssh2_sftp_readlink' => ['string|false', 'sftp'=>'resource', 'link'=>'string'],
'ssh2_sftp_realpath' => ['string|false', 'sftp'=>'resource', 'filename'=>'string'],
'ssh2_sftp_rename' => ['bool', 'sftp'=>'resource', 'from'=>'string', 'to'=>'string'],
'ssh2_sftp_rmdir' => ['bool', 'sftp'=>'resource', 'dirname'=>'string'],
'ssh2_sftp_stat' => ['array|false', 'sftp'=>'resource', 'path'=>'string'],
'ssh2_sftp_symlink' => ['bool', 'sftp'=>'resource', 'target'=>'string', 'link'=>'string'],
'ssh2_sftp_unlink' => ['bool', 'sftp'=>'resource', 'filename'=>'string'],
'ssh2_shell' => ['resource|false', 'session'=>'resource', 'term_type='=>'string', 'env='=>'array', 'width='=>'int', 'height='=>'int', 'width_height_type='=>'int'],
'ssh2_tunnel' => ['resource|false', 'session'=>'resource', 'host'=>'string', 'port'=>'int'],
'stat' => ['array|false', 'filename'=>'string'],
'stats_absolute_deviation' => ['float', 'a'=>'array'],
'stats_cdf_beta' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_binomial' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_cauchy' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_chisquare' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_exponential' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_f' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_gamma' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_laplace' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_logistic' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_negative_binomial' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_chisquare' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_f' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'par4'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_normal' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_poisson' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_uniform' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_weibull' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_covariance' => ['float', 'a'=>'array', 'b'=>'array'],
'stats_den_uniform' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_beta' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_cauchy' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_chisquare' => ['float', 'x'=>'float', 'dfr'=>'float'],
'stats_dens_exponential' => ['float', 'x'=>'float', 'scale'=>'float'],
'stats_dens_f' => ['float', 'x'=>'float', 'dfr1'=>'float', 'dfr2'=>'float'],
'stats_dens_gamma' => ['float', 'x'=>'float', 'shape'=>'float', 'scale'=>'float'],
'stats_dens_laplace' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_logistic' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_negative_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_normal' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_pmf_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_pmf_hypergeometric' => ['float', 'n1'=>'float', 'n2'=>'float', 'N1'=>'float', 'N2'=>'float'],
'stats_dens_pmf_negative_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_pmf_poisson' => ['float', 'x'=>'float', 'lb'=>'float'],
'stats_dens_t' => ['float', 'x'=>'float', 'dfr'=>'float'],
'stats_dens_uniform' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_weibull' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_harmonic_mean' => ['float', 'a'=>'array'],
'stats_kurtosis' => ['float', 'a'=>'array'],
'stats_rand_gen_beta' => ['float', 'a'=>'float', 'b'=>'float'],
'stats_rand_gen_chisquare' => ['float', 'df'=>'float'],
'stats_rand_gen_exponential' => ['float', 'av'=>'float'],
'stats_rand_gen_f' => ['float', 'dfn'=>'float', 'dfd'=>'float'],
'stats_rand_gen_funiform' => ['float', 'low'=>'float', 'high'=>'float'],
'stats_rand_gen_gamma' => ['float', 'a'=>'float', 'r'=>'float'],
'stats_rand_gen_ibinomial' => ['int', 'n'=>'int', 'pp'=>'float'],
'stats_rand_gen_ibinomial_negative' => ['int', 'n'=>'int', 'p'=>'float'],
'stats_rand_gen_int' => ['int'],
'stats_rand_gen_ipoisson' => ['int', 'mu'=>'float'],
'stats_rand_gen_iuniform' => ['int', 'low'=>'int', 'high'=>'int'],
'stats_rand_gen_noncenral_chisquare' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_chisquare' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_f' => ['float', 'dfn'=>'float', 'dfd'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_t' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_normal' => ['float', 'av'=>'float', 'sd'=>'float'],
'stats_rand_gen_t' => ['float', 'df'=>'float'],
'stats_rand_get_seeds' => ['array'],
'stats_rand_phrase_to_seeds' => ['array', 'phrase'=>'string'],
'stats_rand_ranf' => ['float'],
'stats_rand_setall' => ['void', 'iseed1'=>'int', 'iseed2'=>'int'],
'stats_skew' => ['float', 'a'=>'array'],
'stats_standard_deviation' => ['float', 'a'=>'array', 'sample='=>'bool'],
'stats_stat_binomial_coef' => ['float', 'x'=>'int', 'n'=>'int'],
'stats_stat_correlation' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_factorial' => ['float', 'n'=>'int'],
'stats_stat_gennch' => ['float', 'n'=>'int'],
'stats_stat_independent_t' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_innerproduct' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_noncentral_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_stat_paired_t' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_percentile' => ['float', 'arr'=>'array', 'perc'=>'float'],
'stats_stat_powersum' => ['float', 'arr'=>'array', 'power'=>'float'],
'stats_variance' => ['float', 'a'=>'array', 'sample='=>'bool'],
'Stomp::__construct' => ['void', 'broker='=>'string', 'username='=>'string', 'password='=>'string', 'headers='=>'array'],
'Stomp::__destruct' => ['bool', 'link'=>''],
'Stomp::abort' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::ack' => ['bool', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'Stomp::begin' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::commit' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::error' => ['string', 'link'=>''],
'Stomp::getReadTimeout' => ['array', 'link'=>''],
'Stomp::getSessionId' => ['string', 'link'=>''],
'Stomp::hasFrame' => ['bool', 'link'=>''],
'Stomp::readFrame' => ['array', 'class_name='=>'string', 'link='=>''],
'Stomp::send' => ['bool', 'destination'=>'string', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'Stomp::setReadTimeout' => ['', 'seconds'=>'int', 'microseconds='=>'int', 'link='=>''],
'Stomp::subscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::unsubscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_abort' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_ack' => ['bool', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'stomp_begin' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_close' => ['bool', 'link'=>''],
'stomp_commit' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_connect' => ['resource', 'broker='=>'string', 'username='=>'string', 'password='=>'string', 'headers='=>'array'],
'stomp_connect_error' => ['string'],
'stomp_error' => ['string', 'link'=>''],
'stomp_get_read_timeout' => ['array', 'link'=>''],
'stomp_get_session_id' => ['string', 'link'=>''],
'stomp_has_frame' => ['bool', 'link'=>''],
'stomp_read_frame' => ['array', 'class_name='=>'string', 'link='=>''],
'stomp_send' => ['bool', 'destination'=>'string', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'stomp_set_read_timeout' => ['', 'seconds'=>'int', 'microseconds='=>'int', 'link='=>''],
'stomp_subscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_unsubscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_version' => ['string'],
'StompException::getDetails' => ['string'],
'StompFrame::__construct' => ['void', 'command='=>'string', 'headers='=>'array', 'body='=>'string'],
'str_contains' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_ends_with' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_getcsv' => ['non-empty-list<?string>', 'string'=>'string', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'str_ireplace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_count='=>'int'],
'str_pad' => ['string', 'string'=>'string', 'length'=>'int', 'pad_string='=>'string', 'pad_type='=>'int'],
'str_repeat' => ['string', 'string'=>'string', 'times'=>'int'],
'str_replace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_count='=>'int'],
'str_rot13' => ['string', 'string'=>'string'],
'str_shuffle' => ['string', 'string'=>'string'],
'str_split' => ['list<string>|false', 'string'=>'string', 'length='=>'int'],
'str_starts_with' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_word_count' => ['array<int, string>|int', 'string'=>'string', 'format='=>'int', 'characters='=>'string'],
'strcasecmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strchr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed', 'before_needle='=>'bool'],
'strcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strcoll' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strcspn' => ['int', 'string'=>'string', 'characters'=>'string', 'offset='=>'int', 'length='=>'int'],
'stream_bucket_append' => ['void', 'brigade'=>'resource', 'bucket'=>'object'],
'stream_bucket_make_writeable' => ['object', 'brigade'=>'resource'],
'stream_bucket_new' => ['object|false', 'stream'=>'resource', 'buffer'=>'string'],
'stream_bucket_prepend' => ['void', 'brigade'=>'resource', 'bucket'=>'object'],
'stream_context_create' => ['resource', 'options='=>'array', 'params='=>'array'],
'stream_context_get_default' => ['resource', 'options='=>'array'],
'stream_context_get_options' => ['array', 'stream_or_context'=>'resource'],
'stream_context_get_params' => ['array', 'context'=>'resource'],
'stream_context_set_default' => ['resource', 'options'=>'array'],
'stream_context_set_option' => ['bool', 'context'=>'', 'wrapper_or_options'=>'string', 'option_name'=>'string', 'value'=>''],
'stream_context_set_option\'1' => ['bool', 'context'=>'', 'wrapper_or_options'=>'array'],
'stream_context_set_params' => ['bool', 'context'=>'resource', 'params'=>'array'],
'stream_copy_to_stream' => ['int|false', 'from'=>'resource', 'to'=>'resource', 'length='=>'int', 'offset='=>'int'],
'stream_encoding' => ['bool', 'stream'=>'resource', 'encoding='=>'string'],
'stream_filter_append' => ['resource|false', 'stream'=>'resource', 'filter_name'=>'string', 'mode='=>'int', 'params='=>'mixed'],
'stream_filter_prepend' => ['resource|false', 'stream'=>'resource', 'filter_name'=>'string', 'mode='=>'int', 'params='=>'mixed'],
'stream_filter_register' => ['bool', 'filter_name'=>'string', 'class'=>'string'],
'stream_filter_remove' => ['bool', 'stream_filter'=>'resource'],
'stream_get_contents' => ['string|false', 'stream'=>'resource', 'length='=>'int', 'offset='=>'int'],
'stream_get_filters' => ['array'],
'stream_get_line' => ['string|false', 'stream'=>'resource', 'length'=>'int', 'ending='=>'string'],
'stream_get_meta_data' => ['array{timed_out:bool,blocked:bool,eof:bool,unread_bytes:int,stream_type:string,wrapper_type:string,wrapper_data:mixed,mode:string,seekable:bool,uri:string,mediatype:string}', 'stream'=>'resource'],
'stream_get_transports' => ['list<string>'],
'stream_get_wrappers' => ['list<string>'],
'stream_is_local' => ['bool', 'stream'=>'resource|string'],
'stream_isatty' => ['bool', 'stream'=>'resource'],
'stream_notification_callback' => ['callback', 'notification_code'=>'int', 'severity'=>'int', 'message'=>'string', 'message_code'=>'int', 'bytes_transferred'=>'int', 'bytes_max'=>'int'],
'stream_register_wrapper' => ['bool', 'protocol'=>'string', 'class'=>'string', 'flags='=>'int'],
'stream_resolve_include_path' => ['string|false', 'filename'=>'string'],
'stream_select' => ['int|false', '&rw_read'=>'resource[]', '&rw_write'=>'?resource[]', '&rw_except'=>'?resource[]', 'seconds'=>'?int', 'microseconds='=>'?int'],
'stream_set_blocking' => ['bool', 'stream'=>'resource', 'enable'=>'bool'],
'stream_set_chunk_size' => ['int|false', 'stream'=>'resource', 'size'=>'int'],
'stream_set_read_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'stream_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'stream_set_write_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'stream_socket_accept' => ['resource|false', 'socket'=>'resource', 'timeout='=>'float', '&w_peer_name='=>'string'],
'stream_socket_client' => ['resource|false', 'address'=>'string', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_enable_crypto' => ['int|bool', 'stream'=>'resource', 'enable'=>'bool', 'crypto_method='=>'int', 'session_stream='=>'resource'],
'stream_socket_get_name' => ['string', 'socket'=>'resource', 'remote'=>'bool'],
'stream_socket_pair' => ['resource[]|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'stream_socket_recvfrom' => ['string', 'socket'=>'resource', 'length'=>'int', 'flags='=>'int', '&w_address='=>'string'],
'stream_socket_sendto' => ['int', 'socket'=>'resource', 'data'=>'string', 'flags='=>'int', 'address='=>'string'],
'stream_socket_server' => ['resource|false', 'address'=>'string', '&w_error_code='=>'int', '&w_error_message='=>'string', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_shutdown' => ['bool', 'stream'=>'resource', 'mode'=>'int'],
'stream_supports_lock' => ['bool', 'stream'=>'resource'],
'stream_wrapper_register' => ['bool', 'protocol'=>'string', 'class'=>'string', 'flags='=>'int'],
'stream_wrapper_restore' => ['bool', 'protocol'=>'string'],
'stream_wrapper_unregister' => ['bool', 'protocol'=>'string'],
'streamWrapper::__construct' => ['void'],
'streamWrapper::__destruct' => ['void'],
'streamWrapper::dir_closedir' => ['bool'],
'streamWrapper::dir_opendir' => ['bool', 'path'=>'string', 'options'=>'int'],
'streamWrapper::dir_readdir' => ['string'],
'streamWrapper::dir_rewinddir' => ['bool'],
'streamWrapper::mkdir' => ['bool', 'path'=>'string', 'mode'=>'int', 'options'=>'int'],
'streamWrapper::rename' => ['bool', 'path_from'=>'string', 'path_to'=>'string'],
'streamWrapper::rmdir' => ['bool', 'path'=>'string', 'options'=>'int'],
'streamWrapper::stream_cast' => ['resource', 'cast_as'=>'int'],
'streamWrapper::stream_close' => ['void'],
'streamWrapper::stream_eof' => ['bool'],
'streamWrapper::stream_flush' => ['bool'],
'streamWrapper::stream_lock' => ['bool', 'operation'=>'mode'],
'streamWrapper::stream_metadata' => ['bool', 'path'=>'string', 'option'=>'int', 'value'=>'mixed'],
'streamWrapper::stream_open' => ['bool', 'path'=>'string', 'mode'=>'string', 'options'=>'int', 'opened_path'=>'string'],
'streamWrapper::stream_read' => ['string', 'count'=>'int'],
'streamWrapper::stream_seek' => ['bool', 'offset'=>'int', 'whence'=>'int'],
'streamWrapper::stream_set_option' => ['bool', 'option'=>'int', 'arg1'=>'int', 'arg2'=>'int'],
'streamWrapper::stream_stat' => ['array'],
'streamWrapper::stream_tell' => ['int'],
'streamWrapper::stream_truncate' => ['bool', 'new_size'=>'int'],
'streamWrapper::stream_write' => ['int', 'data'=>'string'],
'streamWrapper::unlink' => ['bool', 'path'=>'string'],
'streamWrapper::url_stat' => ['array', 'path'=>'string', 'flags'=>'int'],
'strftime' => ['string', 'format'=>'string', 'timestamp='=>'int'],
'strip_tags' => ['string', 'string'=>'string', 'allowed_tags='=>'string'],
'stripcslashes' => ['string', 'string'=>'string'],
'stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'stripslashes' => ['string', 'string'=>'string'],
'stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed', 'before_needle='=>'bool'],
'strlen' => ['int', 'string'=>'string'],
'strnatcasecmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strnatcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strncasecmp' => ['int', 'string1'=>'string', 'string2'=>'string', 'length'=>'int'],
'strncmp' => ['int', 'string1'=>'string', 'string2'=>'string', 'length'=>'int'],
'strpbrk' => ['string|false', 'string'=>'string', 'characters'=>'string'],
'strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'strptime' => ['array|false', 'timestamp'=>'string', 'format'=>'string'],
'strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed'],
'strrev' => ['string', 'string'=>'string'],
'strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'strspn' => ['int', 'string'=>'string', 'characters'=>'string', 'offset='=>'int', 'length='=>'int'],
'strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed', 'before_needle='=>'bool'],
'strtok' => ['string|false', 'string'=>'string', 'token'=>'string'],
'strtok\'1' => ['string|false', 'string'=>'string'],
'strtolower' => ['string', 'string'=>'string'],
'strtotime' => ['int|false', 'datetime'=>'string', 'baseTimestamp='=>'int'],
'strtoupper' => ['string', 'string'=>'string'],
'strtr' => ['string', 'string'=>'string', 'from'=>'string', 'to'=>'string'],
'strtr\'1' => ['string', 'string'=>'string', 'from'=>'array'],
'strval' => ['string', 'value'=>'mixed'],
'styleObj::__construct' => ['void', 'label'=>'labelObj', 'style'=>'styleObj'],
'styleObj::convertToString' => ['string'],
'styleObj::free' => ['void'],
'styleObj::getBinding' => ['string', 'stylebinding'=>'mixed'],
'styleObj::getGeomTransform' => ['string'],
'styleObj::ms_newStyleObj' => ['styleObj', 'class'=>'classObj', 'style'=>'styleObj'],
'styleObj::removeBinding' => ['int', 'stylebinding'=>'mixed'],
'styleObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'styleObj::setBinding' => ['int', 'stylebinding'=>'mixed', 'value'=>'string'],
'styleObj::setGeomTransform' => ['int', 'value'=>'string'],
'styleObj::updateFromString' => ['int', 'snippet'=>'string'],
'substr' => ['string|false', 'string'=>'string', 'offset'=>'int', 'length='=>'int'],
'substr_compare' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset'=>'int', 'length='=>'int', 'case_insensitive='=>'bool'],
'substr_count' => ['int', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'length='=>'int'],
'substr_replace' => ['string|string[]', 'string'=>'string|string[]', 'replace'=>'mixed', 'offset'=>'mixed', 'length='=>'mixed'],
'suhosin_encrypt_cookie' => ['string|false', 'name'=>'string', 'value'=>'string'],
'suhosin_get_raw_cookies' => ['array'],
'SVM::__construct' => ['void'],
'svm::crossvalidate' => ['float', 'problem'=>'array', 'number_of_folds'=>'int'],
'SVM::getOptions' => ['array'],
'SVM::setOptions' => ['bool', 'params'=>'array'],
'svm::train' => ['SVMModel', 'problem'=>'array', 'weights='=>'array'],
'SVMModel::__construct' => ['void', 'filename='=>'string'],
'SVMModel::checkProbabilityModel' => ['bool'],
'SVMModel::getLabels' => ['array'],
'SVMModel::getNrClass' => ['int'],
'SVMModel::getSvmType' => ['int'],
'SVMModel::getSvrProbability' => ['float'],
'SVMModel::load' => ['bool', 'filename'=>'string'],
'SVMModel::predict' => ['float', 'data'=>'array'],
'SVMModel::predict_probability' => ['float', 'data'=>'array'],
'SVMModel::save' => ['bool', 'filename'=>'string'],
'svn_add' => ['bool', 'path'=>'string', 'recursive='=>'bool', 'force='=>'bool'],
'svn_auth_get_parameter' => ['?string', 'key'=>'string'],
'svn_auth_set_parameter' => ['void', 'key'=>'string', 'value'=>'string'],
'svn_blame' => ['array', 'repository_url'=>'string', 'revision_no='=>'int'],
'svn_cat' => ['string', 'repos_url'=>'string', 'revision_no='=>'int'],
'svn_checkout' => ['bool', 'repos'=>'string', 'targetpath'=>'string', 'revision='=>'int', 'flags='=>'int'],
'svn_cleanup' => ['bool', 'workingdir'=>'string'],
'svn_client_version' => ['string'],
'svn_commit' => ['array', 'log'=>'string', 'targets'=>'array', 'dontrecurse='=>'bool'],
'svn_delete' => ['bool', 'path'=>'string', 'force='=>'bool'],
'svn_diff' => ['array', 'path1'=>'string', 'rev1'=>'int', 'path2'=>'string', 'rev2'=>'int'],
'svn_export' => ['bool', 'frompath'=>'string', 'topath'=>'string', 'working_copy='=>'bool', 'revision_no='=>'int'],
'svn_fs_abort_txn' => ['bool', 'txn'=>'resource'],
'svn_fs_apply_text' => ['resource', 'root'=>'resource', 'path'=>'string'],
'svn_fs_begin_txn2' => ['resource', 'repos'=>'resource', 'rev'=>'int'],
'svn_fs_change_node_prop' => ['bool', 'root'=>'resource', 'path'=>'string', 'name'=>'string', 'value'=>'string'],
'svn_fs_check_path' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_contents_changed' => ['bool', 'root1'=>'resource', 'path1'=>'string', 'root2'=>'resource', 'path2'=>'string'],
'svn_fs_copy' => ['bool', 'from_root'=>'resource', 'from_path'=>'string', 'to_root'=>'resource', 'to_path'=>'string'],
'svn_fs_delete' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_dir_entries' => ['array', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_file_contents' => ['resource', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_file_length' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_is_dir' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_is_file' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_make_dir' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_make_file' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_node_created_rev' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_node_prop' => ['string', 'fsroot'=>'resource', 'path'=>'string', 'propname'=>'string'],
'svn_fs_props_changed' => ['bool', 'root1'=>'resource', 'path1'=>'string', 'root2'=>'resource', 'path2'=>'string'],
'svn_fs_revision_prop' => ['string', 'fs'=>'resource', 'revnum'=>'int', 'propname'=>'string'],
'svn_fs_revision_root' => ['resource', 'fs'=>'resource', 'revnum'=>'int'],
'svn_fs_txn_root' => ['resource', 'txn'=>'resource'],
'svn_fs_youngest_rev' => ['int', 'fs'=>'resource'],
'svn_import' => ['bool', 'path'=>'string', 'url'=>'string', 'nonrecursive'=>'bool'],
'svn_log' => ['array', 'repos_url'=>'string', 'start_revision='=>'int', 'end_revision='=>'int', 'limit='=>'int', 'flags='=>'int'],
'svn_ls' => ['array', 'repos_url'=>'string', 'revision_no='=>'int', 'recurse='=>'bool', 'peg='=>'bool'],
'svn_mkdir' => ['bool', 'path'=>'string', 'log_message='=>'string'],
'svn_move' => ['mixed', 'src_path'=>'string', 'dst_path'=>'string', 'force='=>'bool'],
'svn_propget' => ['mixed', 'path'=>'string', 'property_name'=>'string', 'recurse='=>'bool', 'revision'=>'int'],
'svn_proplist' => ['mixed', 'path'=>'string', 'recurse='=>'bool', 'revision'=>'int'],
'svn_repos_create' => ['resource', 'path'=>'string', 'config='=>'array', 'fsconfig='=>'array'],
'svn_repos_fs' => ['resource', 'repos'=>'resource'],
'svn_repos_fs_begin_txn_for_commit' => ['resource', 'repos'=>'resource', 'rev'=>'int', 'author'=>'string', 'log_msg'=>'string'],
'svn_repos_fs_commit_txn' => ['int', 'txn'=>'resource'],
'svn_repos_hotcopy' => ['bool', 'repospath'=>'string', 'destpath'=>'string', 'cleanlogs'=>'bool'],
'svn_repos_open' => ['resource', 'path'=>'string'],
'svn_repos_recover' => ['bool', 'path'=>'string'],
'svn_revert' => ['bool', 'path'=>'string', 'recursive='=>'bool'],
'svn_status' => ['array', 'path'=>'string', 'flags='=>'int'],
'svn_update' => ['int|false', 'path'=>'string', 'revno='=>'int', 'recurse='=>'bool'],
'swf_actiongeturl' => ['', 'url'=>'string', 'target'=>'string'],
'swf_actiongotoframe' => ['', 'framenumber'=>'int'],
'swf_actiongotolabel' => ['', 'label'=>'string'],
'swf_actionnextframe' => [''],
'swf_actionplay' => [''],
'swf_actionprevframe' => [''],
'swf_actionsettarget' => ['', 'target'=>'string'],
'swf_actionstop' => [''],
'swf_actiontogglequality' => [''],
'swf_actionwaitforframe' => ['', 'framenumber'=>'int', 'skipcount'=>'int'],
'swf_addbuttonrecord' => ['', 'states'=>'int', 'shapeid'=>'int', 'depth'=>'int'],
'swf_addcolor' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_closefile' => ['', 'return_file='=>'int'],
'swf_definebitmap' => ['', 'objid'=>'int', 'image_name'=>'string'],
'swf_definefont' => ['', 'fontid'=>'int', 'fontname'=>'string'],
'swf_defineline' => ['', 'objid'=>'int', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'width'=>'float'],
'swf_definepoly' => ['', 'objid'=>'int', 'coords'=>'array', 'npoints'=>'int', 'width'=>'float'],
'swf_definerect' => ['', 'objid'=>'int', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'width'=>'float'],
'swf_definetext' => ['', 'objid'=>'int', 'string'=>'string', 'docenter'=>'int'],
'swf_endbutton' => [''],
'swf_enddoaction' => [''],
'swf_endshape' => [''],
'swf_endsymbol' => [''],
'swf_fontsize' => ['', 'size'=>'float'],
'swf_fontslant' => ['', 'slant'=>'float'],
'swf_fonttracking' => ['', 'tracking'=>'float'],
'swf_getbitmapinfo' => ['array', 'bitmapid'=>'int'],
'swf_getfontinfo' => ['array'],
'swf_getframe' => ['int'],
'swf_labelframe' => ['', 'name'=>'string'],
'swf_lookat' => ['', 'view_x'=>'float', 'view_y'=>'float', 'view_z'=>'float', 'reference_x'=>'float', 'reference_y'=>'float', 'reference_z'=>'float', 'twist'=>'float'],
'swf_modifyobject' => ['', 'depth'=>'int', 'how'=>'int'],
'swf_mulcolor' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_nextid' => ['int'],
'swf_oncondition' => ['', 'transition'=>'int'],
'swf_openfile' => ['', 'filename'=>'string', 'width'=>'float', 'height'=>'float', 'framerate'=>'float', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'swf_ortho' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float', 'zmin'=>'float', 'zmax'=>'float'],
'swf_ortho2' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float'],
'swf_perspective' => ['', 'fovy'=>'float', 'aspect'=>'float', 'near'=>'float', 'far'=>'float'],
'swf_placeobject' => ['', 'objid'=>'int', 'depth'=>'int'],
'swf_polarview' => ['', 'dist'=>'float', 'azimuth'=>'float', 'incidence'=>'float', 'twist'=>'float'],
'swf_popmatrix' => [''],
'swf_posround' => ['', 'round'=>'int'],
'swf_pushmatrix' => [''],
'swf_removeobject' => ['', 'depth'=>'int'],
'swf_rotate' => ['', 'angle'=>'float', 'axis'=>'string'],
'swf_scale' => ['', 'x'=>'float', 'y'=>'float', 'z'=>'float'],
'swf_setfont' => ['', 'fontid'=>'int'],
'swf_setframe' => ['', 'framenumber'=>'int'],
'swf_shapearc' => ['', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'ang1'=>'float', 'ang2'=>'float'],
'swf_shapecurveto' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'swf_shapecurveto3' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'swf_shapefillbitmapclip' => ['', 'bitmapid'=>'int'],
'swf_shapefillbitmaptile' => ['', 'bitmapid'=>'int'],
'swf_shapefilloff' => [''],
'swf_shapefillsolid' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_shapelinesolid' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float', 'width'=>'float'],
'swf_shapelineto' => ['', 'x'=>'float', 'y'=>'float'],
'swf_shapemoveto' => ['', 'x'=>'float', 'y'=>'float'],
'swf_showframe' => [''],
'swf_startbutton' => ['', 'objid'=>'int', 'type'=>'int'],
'swf_startdoaction' => [''],
'swf_startshape' => ['', 'objid'=>'int'],
'swf_startsymbol' => ['', 'objid'=>'int'],
'swf_textwidth' => ['float', 'string'=>'string'],
'swf_translate' => ['', 'x'=>'float', 'y'=>'float', 'z'=>'float'],
'swf_viewport' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float'],
'SWFAction::__construct' => ['void', 'script'=>'string'],
'SWFBitmap::__construct' => ['void', 'file'=>'', 'alphafile='=>''],
'SWFBitmap::getHeight' => ['float'],
'SWFBitmap::getWidth' => ['float'],
'SWFButton::__construct' => ['void'],
'SWFButton::addAction' => ['void', 'action'=>'swfaction', 'flags'=>'int'],
'SWFButton::addASound' => ['SWFSoundInstance', 'sound'=>'swfsound', 'flags'=>'int'],
'SWFButton::addShape' => ['void', 'shape'=>'swfshape', 'flags'=>'int'],
'SWFButton::setAction' => ['void', 'action'=>'swfaction'],
'SWFButton::setDown' => ['void', 'shape'=>'swfshape'],
'SWFButton::setHit' => ['void', 'shape'=>'swfshape'],
'SWFButton::setMenu' => ['void', 'flag'=>'int'],
'SWFButton::setOver' => ['void', 'shape'=>'swfshape'],
'SWFButton::setUp' => ['void', 'shape'=>'swfshape'],
'SWFDisplayItem::addAction' => ['void', 'action'=>'swfaction', 'flags'=>'int'],
'SWFDisplayItem::addColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFDisplayItem::endMask' => ['void'],
'SWFDisplayItem::getRot' => ['float'],
'SWFDisplayItem::getX' => ['float'],
'SWFDisplayItem::getXScale' => ['float'],
'SWFDisplayItem::getXSkew' => ['float'],
'SWFDisplayItem::getY' => ['float'],
'SWFDisplayItem::getYScale' => ['float'],
'SWFDisplayItem::getYSkew' => ['float'],
'SWFDisplayItem::move' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFDisplayItem::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFDisplayItem::multColor' => ['void', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'a='=>'float'],
'SWFDisplayItem::remove' => ['void'],
'SWFDisplayItem::rotate' => ['void', 'angle'=>'float'],
'SWFDisplayItem::rotateTo' => ['void', 'angle'=>'float'],
'SWFDisplayItem::scale' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFDisplayItem::scaleTo' => ['void', 'x'=>'float', 'y='=>'float'],
'SWFDisplayItem::setDepth' => ['void', 'depth'=>'int'],
'SWFDisplayItem::setMaskLevel' => ['void', 'level'=>'int'],
'SWFDisplayItem::setMatrix' => ['void', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'SWFDisplayItem::setName' => ['void', 'name'=>'string'],
'SWFDisplayItem::setRatio' => ['void', 'ratio'=>'float'],
'SWFDisplayItem::skewX' => ['void', 'ddegrees'=>'float'],
'SWFDisplayItem::skewXTo' => ['void', 'degrees'=>'float'],
'SWFDisplayItem::skewY' => ['void', 'ddegrees'=>'float'],
'SWFDisplayItem::skewYTo' => ['void', 'degrees'=>'float'],
'SWFFill::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFFill::rotateTo' => ['void', 'angle'=>'float'],
'SWFFill::scaleTo' => ['void', 'x'=>'float', 'y='=>'float'],
'SWFFill::skewXTo' => ['void', 'x'=>'float'],
'SWFFill::skewYTo' => ['void', 'y'=>'float'],
'SWFFont::__construct' => ['void', 'filename'=>'string'],
'SWFFont::getAscent' => ['float'],
'SWFFont::getDescent' => ['float'],
'SWFFont::getLeading' => ['float'],
'SWFFont::getShape' => ['string', 'code'=>'int'],
'SWFFont::getUTF8Width' => ['float', 'string'=>'string'],
'SWFFont::getWidth' => ['float', 'string'=>'string'],
'SWFFontChar::addChars' => ['void', 'char'=>'string'],
'SWFFontChar::addUTF8Chars' => ['void', 'char'=>'string'],
'SWFGradient::__construct' => ['void'],
'SWFGradient::addEntry' => ['void', 'ratio'=>'float', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int'],
'SWFMorph::__construct' => ['void'],
'SWFMorph::getShape1' => ['SWFShape'],
'SWFMorph::getShape2' => ['SWFShape'],
'SWFMovie::__construct' => ['void', 'version='=>'int'],
'SWFMovie::add' => ['mixed', 'instance'=>'object'],
'SWFMovie::addExport' => ['void', 'char'=>'swfcharacter', 'name'=>'string'],
'SWFMovie::addFont' => ['mixed', 'font'=>'swffont'],
'SWFMovie::importChar' => ['SWFSprite', 'libswf'=>'string', 'name'=>'string'],
'SWFMovie::importFont' => ['SWFFontChar', 'libswf'=>'string', 'name'=>'string'],
'SWFMovie::labelFrame' => ['void', 'label'=>'string'],
'SWFMovie::namedAnchor' => [''],
'SWFMovie::nextFrame' => ['void'],
'SWFMovie::output' => ['int', 'compression='=>'int'],
'SWFMovie::protect' => [''],
'SWFMovie::remove' => ['void', 'instance'=>'object'],
'SWFMovie::save' => ['int', 'filename'=>'string', 'compression='=>'int'],
'SWFMovie::saveToFile' => ['int', 'x'=>'resource', 'compression='=>'int'],
'SWFMovie::setbackground' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'SWFMovie::setDimension' => ['void', 'width'=>'float', 'height'=>'float'],
'SWFMovie::setFrames' => ['void', 'number'=>'int'],
'SWFMovie::setRate' => ['void', 'rate'=>'float'],
'SWFMovie::startSound' => ['SWFSoundInstance', 'sound'=>'swfsound'],
'SWFMovie::stopSound' => ['void', 'sound'=>'swfsound'],
'SWFMovie::streamMP3' => ['int', 'mp3file'=>'mixed', 'skip='=>'float'],
'SWFMovie::writeExports' => ['void'],
'SWFPrebuiltClip::__construct' => ['void', 'file'=>''],
'SWFShape::__construct' => ['void'],
'SWFShape::addFill' => ['SWFFill', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int', 'bitmap='=>'swfbitmap', 'flags='=>'int', 'gradient='=>'swfgradient'],
'SWFShape::addFill\'1' => ['SWFFill', 'bitmap'=>'SWFBitmap', 'flags='=>'int'],
'SWFShape::addFill\'2' => ['SWFFill', 'gradient'=>'SWFGradient', 'flags='=>'int'],
'SWFShape::drawArc' => ['void', 'r'=>'float', 'startangle'=>'float', 'endangle'=>'float'],
'SWFShape::drawCircle' => ['void', 'r'=>'float'],
'SWFShape::drawCubic' => ['int', 'bx'=>'float', 'by'=>'float', 'cx'=>'float', 'cy'=>'float', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawCubicTo' => ['int', 'bx'=>'float', 'by'=>'float', 'cx'=>'float', 'cy'=>'float', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawCurve' => ['int', 'controldx'=>'float', 'controldy'=>'float', 'anchordx'=>'float', 'anchordy'=>'float', 'targetdx='=>'float', 'targetdy='=>'float'],
'SWFShape::drawCurveTo' => ['int', 'controlx'=>'float', 'controly'=>'float', 'anchorx'=>'float', 'anchory'=>'float', 'targetx='=>'float', 'targety='=>'float'],
'SWFShape::drawGlyph' => ['void', 'font'=>'swffont', 'character'=>'string', 'size='=>'int'],
'SWFShape::drawLine' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawLineTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFShape::movePen' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::movePenTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFShape::setLeftFill' => ['', 'fill'=>'swfgradient', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFShape::setLine' => ['', 'shape'=>'swfshape', 'width'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFShape::setRightFill' => ['', 'fill'=>'swfgradient', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFSound' => ['SWFSound', 'filename'=>'string', 'flags='=>'int'],
'SWFSound::__construct' => ['void', 'filename'=>'string', 'flags='=>'int'],
'SWFSoundInstance::loopCount' => ['void', 'point'=>'int'],
'SWFSoundInstance::loopInPoint' => ['void', 'point'=>'int'],
'SWFSoundInstance::loopOutPoint' => ['void', 'point'=>'int'],
'SWFSoundInstance::noMultiple' => ['void'],
'SWFSprite::__construct' => ['void'],
'SWFSprite::add' => ['void', 'object'=>'object'],
'SWFSprite::labelFrame' => ['void', 'label'=>'string'],
'SWFSprite::nextFrame' => ['void'],
'SWFSprite::remove' => ['void', 'object'=>'object'],
'SWFSprite::setFrames' => ['void', 'number'=>'int'],
'SWFSprite::startSound' => ['SWFSoundInstance', 'sount'=>'swfsound'],
'SWFSprite::stopSound' => ['void', 'sount'=>'swfsound'],
'SWFText::__construct' => ['void'],
'SWFText::addString' => ['void', 'string'=>'string'],
'SWFText::addUTF8String' => ['void', 'text'=>'string'],
'SWFText::getAscent' => ['float'],
'SWFText::getDescent' => ['float'],
'SWFText::getLeading' => ['float'],
'SWFText::getUTF8Width' => ['float', 'string'=>'string'],
'SWFText::getWidth' => ['float', 'string'=>'string'],
'SWFText::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFText::setColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFText::setFont' => ['void', 'font'=>'swffont'],
'SWFText::setHeight' => ['void', 'height'=>'float'],
'SWFText::setSpacing' => ['void', 'spacing'=>'float'],
'SWFTextField::__construct' => ['void', 'flags='=>'int'],
'SWFTextField::addChars' => ['void', 'chars'=>'string'],
'SWFTextField::addString' => ['void', 'string'=>'string'],
'SWFTextField::align' => ['void', 'alignement'=>'int'],
'SWFTextField::setBounds' => ['void', 'width'=>'float', 'height'=>'float'],
'SWFTextField::setColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFTextField::setFont' => ['void', 'font'=>'swffont'],
'SWFTextField::setHeight' => ['void', 'height'=>'float'],
'SWFTextField::setIndentation' => ['void', 'width'=>'float'],
'SWFTextField::setLeftMargin' => ['void', 'width'=>'float'],
'SWFTextField::setLineSpacing' => ['void', 'height'=>'float'],
'SWFTextField::setMargins' => ['void', 'left'=>'float', 'right'=>'float'],
'SWFTextField::setName' => ['void', 'name'=>'string'],
'SWFTextField::setPadding' => ['void', 'padding'=>'float'],
'SWFTextField::setRightMargin' => ['void', 'width'=>'float'],
'SWFVideoStream::__construct' => ['void', 'file='=>'string'],
'SWFVideoStream::getNumFrames' => ['int'],
'SWFVideoStream::setDimension' => ['void', 'x'=>'int', 'y'=>'int'],
'Swish::__construct' => ['void', 'index_names'=>'string'],
'Swish::getMetaList' => ['array', 'index_name'=>'string'],
'Swish::getPropertyList' => ['array', 'index_name'=>'string'],
'Swish::prepare' => ['object', 'query='=>'string'],
'Swish::query' => ['object', 'query'=>'string'],
'SwishResult::getMetaList' => ['array'],
'SwishResult::stem' => ['array', 'word'=>'string'],
'SwishResults::getParsedWords' => ['array', 'index_name'=>'string'],
'SwishResults::getRemovedStopwords' => ['array', 'index_name'=>'string'],
'SwishResults::nextResult' => ['object'],
'SwishResults::seekResult' => ['int', 'position'=>'int'],
'SwishSearch::execute' => ['object', 'query='=>'string'],
'SwishSearch::resetLimit' => [''],
'SwishSearch::setLimit' => ['', 'property'=>'string', 'low'=>'string', 'high'=>'string'],
'SwishSearch::setPhraseDelimiter' => ['', 'delimiter'=>'string'],
'SwishSearch::setSort' => ['', 'sort'=>'string'],
'SwishSearch::setStructure' => ['', 'structure'=>'int'],
'swoole\async::dnsLookup' => ['void', 'hostname'=>'string', 'callback'=>'callable'],
'swoole\async::read' => ['bool', 'filename'=>'string', 'callback'=>'callable', 'chunk_size='=>'integer', 'offset='=>'integer'],
'swoole\async::readFile' => ['void', 'filename'=>'string', 'callback'=>'callable'],
'swoole\async::set' => ['void', 'settings'=>'array'],
'swoole\async::write' => ['void', 'filename'=>'string', 'content'=>'string', 'offset='=>'integer', 'callback='=>'callable'],
'swoole\async::writeFile' => ['void', 'filename'=>'string', 'content'=>'string', 'callback='=>'callable', 'flags='=>'string'],
'swoole\atomic::add' => ['integer', 'add_value='=>'integer'],
'swoole\atomic::cmpset' => ['integer', 'cmp_value'=>'integer', 'new_value'=>'integer'],
'swoole\atomic::get' => ['integer'],
'swoole\atomic::set' => ['integer', 'value'=>'integer'],
'swoole\atomic::sub' => ['integer', 'sub_value='=>'integer'],
'swoole\buffer::__destruct' => ['void'],
'swoole\buffer::__toString' => ['string'],
'swoole\buffer::append' => ['integer', 'data'=>'string'],
'swoole\buffer::clear' => ['void'],
'swoole\buffer::expand' => ['integer', 'size'=>'integer'],
'swoole\buffer::read' => ['string', 'offset'=>'integer', 'length'=>'integer'],
'swoole\buffer::recycle' => ['void'],
'swoole\buffer::substr' => ['string', 'offset'=>'integer', 'length='=>'integer', 'remove='=>'bool'],
'swoole\buffer::write' => ['void', 'offset'=>'integer', 'data'=>'string'],
'swoole\channel::__destruct' => ['void'],
'swoole\channel::pop' => ['mixed'],
'swoole\channel::push' => ['bool', 'data'=>'string'],
'swoole\channel::stats' => ['array'],
'swoole\client::__destruct' => ['void'],
'swoole\client::close' => ['bool', 'force='=>'bool'],
'swoole\client::connect' => ['bool', 'host'=>'string', 'port='=>'integer', 'timeout='=>'integer', 'flag='=>'integer'],
'swoole\client::getpeername' => ['array'],
'swoole\client::getsockname' => ['array'],
'swoole\client::isConnected' => ['bool'],
'swoole\client::on' => ['void', 'event'=>'string', 'callback'=>'callable'],
'swoole\client::pause' => ['void'],
'swoole\client::pipe' => ['void', 'socket'=>'string'],
'swoole\client::recv' => ['void', 'size='=>'string', 'flag='=>'string'],
'swoole\client::resume' => ['void'],
'swoole\client::send' => ['integer', 'data'=>'string', 'flag='=>'string'],
'swoole\client::sendfile' => ['bool', 'filename'=>'string', 'offset='=>'int'],
'swoole\client::sendto' => ['bool', 'ip'=>'string', 'port'=>'integer', 'data'=>'string'],
'swoole\client::set' => ['void', 'settings'=>'array'],
'swoole\client::sleep' => ['void'],
'swoole\client::wakeup' => ['void'],
'swoole\connection\iterator::count' => ['int'],
'swoole\connection\iterator::current' => ['Connection'],
'swoole\connection\iterator::key' => ['int'],
'swoole\connection\iterator::next' => ['Connection'],
'swoole\connection\iterator::offsetExists' => ['bool', 'index'=>'int'],
'swoole\connection\iterator::offsetGet' => ['Connection', 'index'=>'string'],
'swoole\connection\iterator::offsetSet' => ['void', 'offset'=>'int', 'connection'=>'mixed'],
'swoole\connection\iterator::offsetUnset' => ['void', 'offset'=>'int'],
'swoole\connection\iterator::rewind' => ['void'],
'swoole\connection\iterator::valid' => ['bool'],
'swoole\coroutine::call_user_func' => ['mixed', 'callback'=>'callable', 'parameter='=>'mixed', '...args='=>'mixed'],
'swoole\coroutine::call_user_func_array' => ['mixed', 'callback'=>'callable', 'param_array'=>'array'],
'swoole\coroutine::cli_wait' => ['ReturnType'],
'swoole\coroutine::create' => ['ReturnType'],
'swoole\coroutine::getuid' => ['ReturnType'],
'swoole\coroutine::resume' => ['ReturnType'],
'swoole\coroutine::suspend' => ['ReturnType'],
'swoole\coroutine\client::__destruct' => ['ReturnType'],
'swoole\coroutine\client::close' => ['ReturnType'],
'swoole\coroutine\client::connect' => ['ReturnType'],
'swoole\coroutine\client::getpeername' => ['ReturnType'],
'swoole\coroutine\client::getsockname' => ['ReturnType'],
'swoole\coroutine\client::isConnected' => ['ReturnType'],
'swoole\coroutine\client::recv' => ['ReturnType'],
'swoole\coroutine\client::send' => ['ReturnType'],
'swoole\coroutine\client::sendfile' => ['ReturnType'],
'swoole\coroutine\client::sendto' => ['ReturnType'],
'swoole\coroutine\client::set' => ['ReturnType'],
'swoole\coroutine\http\client::__destruct' => ['ReturnType'],
'swoole\coroutine\http\client::addFile' => ['ReturnType'],
'swoole\coroutine\http\client::close' => ['ReturnType'],
'swoole\coroutine\http\client::execute' => ['ReturnType'],
'swoole\coroutine\http\client::get' => ['ReturnType'],
'swoole\coroutine\http\client::getDefer' => ['ReturnType'],
'swoole\coroutine\http\client::isConnected' => ['ReturnType'],
'swoole\coroutine\http\client::post' => ['ReturnType'],
'swoole\coroutine\http\client::recv' => ['ReturnType'],
'swoole\coroutine\http\client::set' => ['ReturnType'],
'swoole\coroutine\http\client::setCookies' => ['ReturnType'],
'swoole\coroutine\http\client::setData' => ['ReturnType'],
'swoole\coroutine\http\client::setDefer' => ['ReturnType'],
'swoole\coroutine\http\client::setHeaders' => ['ReturnType'],
'swoole\coroutine\http\client::setMethod' => ['ReturnType'],
'swoole\coroutine\mysql::__destruct' => ['ReturnType'],
'swoole\coroutine\mysql::close' => ['ReturnType'],
'swoole\coroutine\mysql::connect' => ['ReturnType'],
'swoole\coroutine\mysql::getDefer' => ['ReturnType'],
'swoole\coroutine\mysql::query' => ['ReturnType'],
'swoole\coroutine\mysql::recv' => ['ReturnType'],
'swoole\coroutine\mysql::setDefer' => ['ReturnType'],
'swoole\event::add' => ['bool', 'fd'=>'int', 'read_callback'=>'callable', 'write_callback='=>'callable', 'events='=>'string'],
'swoole\event::defer' => ['void', 'callback'=>'mixed'],
'swoole\event::del' => ['bool', 'fd'=>'string'],
'swoole\event::exit' => ['void'],
'swoole\event::set' => ['bool', 'fd'=>'int', 'read_callback='=>'string', 'write_callback='=>'string', 'events='=>'string'],
'swoole\event::wait' => ['void'],
'swoole\event::write' => ['void', 'fd'=>'string', 'data'=>'string'],
'swoole\http\client::__destruct' => ['void'],
'swoole\http\client::addFile' => ['void', 'path'=>'string', 'name'=>'string', 'type='=>'string', 'filename='=>'string', 'offset='=>'string'],
'swoole\http\client::close' => ['void'],
'swoole\http\client::download' => ['void', 'path'=>'string', 'file'=>'string', 'callback'=>'callable', 'offset='=>'integer'],
'swoole\http\client::execute' => ['void', 'path'=>'string', 'callback'=>'string'],
'swoole\http\client::get' => ['void', 'path'=>'string', 'callback'=>'callable'],
'swoole\http\client::isConnected' => ['bool'],
'swoole\http\client::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\http\client::post' => ['void', 'path'=>'string', 'data'=>'string', 'callback'=>'callable'],
'swoole\http\client::push' => ['void', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string'],
'swoole\http\client::set' => ['void', 'settings'=>'array'],
'swoole\http\client::setCookies' => ['void', 'cookies'=>'array'],
'swoole\http\client::setData' => ['ReturnType', 'data'=>'string'],
'swoole\http\client::setHeaders' => ['void', 'headers'=>'array'],
'swoole\http\client::setMethod' => ['void', 'method'=>'string'],
'swoole\http\client::upgrade' => ['void', 'path'=>'string', 'callback'=>'string'],
'swoole\http\request::__destruct' => ['void'],
'swoole\http\request::rawcontent' => ['string'],
'swoole\http\response::__destruct' => ['void'],
'swoole\http\response::cookie' => ['string', 'name'=>'string', 'value='=>'string', 'expires='=>'string', 'path='=>'string', 'domain='=>'string', 'secure='=>'string', 'httponly='=>'string'],
'swoole\http\response::end' => ['void', 'content='=>'string'],
'swoole\http\response::gzip' => ['ReturnType', 'compress_level='=>'string'],
'swoole\http\response::header' => ['void', 'key'=>'string', 'value'=>'string', 'ucwords='=>'string'],
'swoole\http\response::initHeader' => ['ReturnType'],
'swoole\http\response::rawcookie' => ['ReturnType', 'name'=>'string', 'value='=>'string', 'expires='=>'string', 'path='=>'string', 'domain='=>'string', 'secure='=>'string', 'httponly='=>'string'],
'swoole\http\response::sendfile' => ['ReturnType', 'filename'=>'string', 'offset='=>'int'],
'swoole\http\response::status' => ['ReturnType', 'http_code'=>'string'],
'swoole\http\response::write' => ['void', 'content'=>'string'],
'swoole\http\server::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\http\server::start' => ['void'],
'swoole\lock::__destruct' => ['void'],
'swoole\lock::lock' => ['void'],
'swoole\lock::lock_read' => ['void'],
'swoole\lock::trylock' => ['void'],
'swoole\lock::trylock_read' => ['void'],
'swoole\lock::unlock' => ['void'],
'swoole\mmap::open' => ['ReturnType', 'filename'=>'string', 'size='=>'string', 'offset='=>'string'],
'swoole\mysql::__destruct' => ['void'],
'swoole\mysql::close' => ['void'],
'swoole\mysql::connect' => ['void', 'server_config'=>'array', 'callback'=>'callable'],
'swoole\mysql::getBuffer' => ['ReturnType'],
'swoole\mysql::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\mysql::query' => ['ReturnType', 'sql'=>'string', 'callback'=>'callable'],
'swoole\process::__destruct' => ['void'],
'swoole\process::alarm' => ['void', 'interval_usec'=>'integer'],
'swoole\process::close' => ['void'],
'swoole\process::daemon' => ['void', 'nochdir='=>'bool', 'noclose='=>'bool'],
'swoole\process::exec' => ['ReturnType', 'exec_file'=>'string', 'args'=>'string'],
'swoole\process::exit' => ['void', 'exit_code='=>'string'],
'swoole\process::freeQueue' => ['void'],
'swoole\process::kill' => ['void', 'pid'=>'integer', 'signal_no='=>'string'],
'swoole\process::name' => ['void', 'process_name'=>'string'],
'swoole\process::pop' => ['mixed', 'maxsize='=>'integer'],
'swoole\process::push' => ['bool', 'data'=>'string'],
'swoole\process::read' => ['string', 'maxsize='=>'integer'],
'swoole\process::signal' => ['void', 'signal_no'=>'string', 'callback'=>'callable'],
'swoole\process::start' => ['void'],
'swoole\process::statQueue' => ['array'],
'swoole\process::useQueue' => ['bool', 'key'=>'integer', 'mode='=>'integer'],
'swoole\process::wait' => ['array', 'blocking='=>'bool'],
'swoole\process::write' => ['integer', 'data'=>'string'],
'swoole\redis\server::format' => ['ReturnType', 'type'=>'string', 'value='=>'string'],
'swoole\redis\server::setHandler' => ['ReturnType', 'command'=>'string', 'callback'=>'string', 'number_of_string_param='=>'string', 'type_of_array_param='=>'string'],
'swoole\redis\server::start' => ['ReturnType'],
'swoole\serialize::pack' => ['ReturnType', 'data'=>'string', 'is_fast='=>'int'],
'swoole\serialize::unpack' => ['ReturnType', 'data'=>'string', 'args='=>'string'],
'swoole\server::addlistener' => ['void', 'host'=>'string', 'port'=>'integer', 'socket_type'=>'string'],
'swoole\server::addProcess' => ['bool', 'process'=>'swoole_process'],
'swoole\server::after' => ['ReturnType', 'after_time_ms'=>'integer', 'callback'=>'callable', 'param='=>'string'],
'swoole\server::bind' => ['bool', 'fd'=>'integer', 'uid'=>'integer'],
'swoole\server::close' => ['bool', 'fd'=>'integer', 'reset='=>'bool'],
'swoole\server::confirm' => ['bool', 'fd'=>'integer'],
'swoole\server::connection_info' => ['array', 'fd'=>'integer', 'reactor_id='=>'integer'],
'swoole\server::connection_list' => ['array', 'start_fd'=>'integer', 'pagesize='=>'integer'],
'swoole\server::defer' => ['void', 'callback'=>'callable'],
'swoole\server::exist' => ['bool', 'fd'=>'integer'],
'swoole\server::finish' => ['void', 'data'=>'string'],
'swoole\server::getClientInfo' => ['ReturnType', 'fd'=>'integer', 'reactor_id='=>'integer'],
'swoole\server::getClientList' => ['array', 'start_fd'=>'integer', 'pagesize='=>'integer'],
'swoole\server::getLastError' => ['integer'],
'swoole\server::heartbeat' => ['mixed', 'if_close_connection'=>'bool'],
'swoole\server::listen' => ['bool', 'host'=>'string', 'port'=>'integer', 'socket_type'=>'string'],
'swoole\server::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\server::pause' => ['void', 'fd'=>'integer'],
'swoole\server::protect' => ['void', 'fd'=>'integer', 'is_protected='=>'bool'],
'swoole\server::reload' => ['bool'],
'swoole\server::resume' => ['void', 'fd'=>'integer'],
'swoole\server::send' => ['bool', 'fd'=>'integer', 'data'=>'string', 'reactor_id='=>'integer'],
'swoole\server::sendfile' => ['bool', 'fd'=>'integer', 'filename'=>'string', 'offset='=>'integer'],
'swoole\server::sendMessage' => ['bool', 'worker_id'=>'integer', 'data'=>'string'],
'swoole\server::sendto' => ['bool', 'ip'=>'string', 'port'=>'integer', 'data'=>'string', 'server_socket='=>'string'],
'swoole\server::sendwait' => ['bool', 'fd'=>'integer', 'data'=>'string'],
'swoole\server::set' => ['ReturnType', 'settings'=>'array'],
'swoole\server::shutdown' => ['void'],
'swoole\server::start' => ['void'],
'swoole\server::stats' => ['array'],
'swoole\server::stop' => ['bool', 'worker_id='=>'integer'],
'swoole\server::task' => ['mixed', 'data'=>'string', 'dst_worker_id='=>'integer', 'callback='=>'callable'],
'swoole\server::taskwait' => ['void', 'data'=>'string', 'timeout='=>'float', 'worker_id='=>'integer'],
'swoole\server::taskWaitMulti' => ['void', 'tasks'=>'array', 'timeout_ms='=>'double'],
'swoole\server::tick' => ['void', 'interval_ms'=>'integer', 'callback'=>'callable'],
'swoole\server\port::__destruct' => ['void'],
'swoole\server\port::on' => ['ReturnType', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\server\port::set' => ['void', 'settings'=>'array'],
'swoole\table::column' => ['ReturnType', 'name'=>'string', 'type'=>'string', 'size='=>'integer'],
'swoole\table::count' => ['integer'],
'swoole\table::create' => ['void'],
'swoole\table::current' => ['array'],
'swoole\table::decr' => ['ReturnType', 'key'=>'string', 'column'=>'string', 'decrby='=>'integer'],
'swoole\table::del' => ['void', 'key'=>'string'],
'swoole\table::destroy' => ['void'],
'swoole\table::exist' => ['bool', 'key'=>'string'],
'swoole\table::get' => ['integer', 'row_key'=>'string', 'column_key'=>'string'],
'swoole\table::incr' => ['void', 'key'=>'string', 'column'=>'string', 'incrby='=>'integer'],
'swoole\table::key' => ['string'],
'swoole\table::next' => ['ReturnType'],
'swoole\table::rewind' => ['void'],
'swoole\table::set' => ['VOID', 'key'=>'string', 'value'=>'array'],
'swoole\table::valid' => ['bool'],
'swoole\timer::after' => ['void', 'after_time_ms'=>'int', 'callback'=>'callable'],
'swoole\timer::clear' => ['void', 'timer_id'=>'integer'],
'swoole\timer::exists' => ['bool', 'timer_id'=>'integer'],
'swoole\timer::tick' => ['void', 'interval_ms'=>'integer', 'callback'=>'callable', 'param='=>'string'],
'swoole\websocket\server::exist' => ['bool', 'fd'=>'integer'],
'swoole\websocket\server::on' => ['ReturnType', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\websocket\server::pack' => ['binary', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string', 'mask='=>'string'],
'swoole\websocket\server::push' => ['void', 'fd'=>'string', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string'],
'swoole\websocket\server::unpack' => ['string', 'data'=>'binary'],
'swoole_async_dns_lookup' => ['bool', 'hostname'=>'string', 'callback'=>'callable'],
'swoole_async_read' => ['bool', 'filename'=>'string', 'callback'=>'callable', 'chunk_size='=>'int', 'offset='=>'int'],
'swoole_async_readfile' => ['bool', 'filename'=>'string', 'callback'=>'string'],
'swoole_async_set' => ['void', 'settings'=>'array'],
'swoole_async_write' => ['bool', 'filename'=>'string', 'content'=>'string', 'offset='=>'int', 'callback='=>'callable'],
'swoole_async_writefile' => ['bool', 'filename'=>'string', 'content'=>'string', 'callback='=>'callable', 'flags='=>'int'],
'swoole_client_select' => ['int', 'read_array'=>'array', 'write_array'=>'array', 'error_array'=>'array', 'timeout='=>'float'],
'swoole_cpu_num' => ['int'],
'swoole_errno' => ['int'],
'swoole_event_add' => ['int', 'fd'=>'int', 'read_callback='=>'callable', 'write_callback='=>'callable', 'events='=>'int'],
'swoole_event_defer' => ['bool', 'callback'=>'callable'],
'swoole_event_del' => ['bool', 'fd'=>'int'],
'swoole_event_exit' => ['void'],
'swoole_event_set' => ['bool', 'fd'=>'int', 'read_callback='=>'callable', 'write_callback='=>'callable', 'events='=>'int'],
'swoole_event_wait' => ['void'],
'swoole_event_write' => ['bool', 'fd'=>'int', 'data'=>'string'],
'swoole_get_local_ip' => ['array'],
'swoole_last_error' => ['int'],
'swoole_load_module' => ['mixed', 'filename'=>'string'],
'swoole_select' => ['int', 'read_array'=>'array', 'write_array'=>'array', 'error_array'=>'array', 'timeout='=>'float'],
'swoole_set_process_name' => ['void', 'process_name'=>'string', 'size='=>'int'],
'swoole_strerror' => ['string', 'errno'=>'int', 'error_type='=>'int'],
'swoole_timer_after' => ['int', 'ms'=>'int', 'callback'=>'callable', 'param='=>'mixed'],
'swoole_timer_exists' => ['bool', 'timer_id'=>'int'],
'swoole_timer_tick' => ['int', 'ms'=>'int', 'callback'=>'callable', 'param='=>'mixed'],
'swoole_version' => ['string'],
'symbolObj::__construct' => ['void', 'map'=>'mapObj', 'symbolname'=>'string'],
'symbolObj::free' => ['void'],
'symbolObj::getPatternArray' => ['array'],
'symbolObj::getPointsArray' => ['array'],
'symbolObj::ms_newSymbolObj' => ['int', 'map'=>'mapObj', 'symbolname'=>'string'],
'symbolObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'symbolObj::setImagePath' => ['int', 'filename'=>'string'],
'symbolObj::setPattern' => ['int', 'int'=>'array'],
'symbolObj::setPoints' => ['int', 'double'=>'array'],
'symlink' => ['bool', 'target'=>'string', 'link'=>'string'],
'SyncEvent::__construct' => ['void', 'name='=>'string', 'manual='=>'bool'],
'SyncEvent::fire' => ['bool'],
'SyncEvent::reset' => ['bool'],
'SyncEvent::wait' => ['bool', 'wait='=>'int'],
'SyncMutex::__construct' => ['void', 'name='=>'string'],
'SyncMutex::lock' => ['bool', 'wait='=>'int'],
'SyncMutex::unlock' => ['bool', 'all='=>'bool'],
'SyncReaderWriter::__construct' => ['void', 'name='=>'string', 'autounlock='=>'bool'],
'SyncReaderWriter::readlock' => ['bool', 'wait='=>'int'],
'SyncReaderWriter::readunlock' => ['bool'],
'SyncReaderWriter::writelock' => ['bool', 'wait='=>'int'],
'SyncReaderWriter::writeunlock' => ['bool'],
'SyncSemaphore::__construct' => ['void', 'name='=>'string', 'initialval='=>'int', 'autounlock='=>'bool'],
'SyncSemaphore::lock' => ['bool', 'wait='=>'int'],
'SyncSemaphore::unlock' => ['bool', '&w_prevcount='=>'int'],
'SyncSharedMemory::__construct' => ['void', 'name'=>'string', 'size'=>'int'],
'SyncSharedMemory::first' => ['bool'],
'SyncSharedMemory::read' => ['string', 'start='=>'int', 'length='=>'int'],
'SyncSharedMemory::size' => ['int'],
'SyncSharedMemory::write' => ['int', 'string='=>'string', 'start='=>'int'],
'sys_get_temp_dir' => ['string'],
'sys_getloadavg' => ['array'],
'syslog' => ['bool', 'priority'=>'int', 'message'=>'string'],
'system' => ['string|false', 'command'=>'string', '&w_result_code='=>'int'],
'taint' => ['bool', '&rw_string'=>'string', '&...w_other_strings='=>'string'],
'tan' => ['float', 'num'=>'float'],
'tanh' => ['float', 'num'=>'float'],
'tcpwrap_check' => ['bool', 'daemon'=>'string', 'address'=>'string', 'user='=>'string', 'nodns='=>'bool'],
'tempnam' => ['string|false', 'directory'=>'string', 'prefix'=>'string'],
'textdomain' => ['string', 'domain'=>'string'],
'Thread::__construct' => ['void'],
'Thread::addRef' => ['void'],
'Thread::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Thread::count' => ['int'],
'Thread::delRef' => ['void'],
'Thread::detach' => ['void'],
'Thread::extend' => ['bool', 'class'=>'string'],
'Thread::getCreatorId' => ['int'],
'Thread::getCurrentThread' => ['Thread'],
'Thread::getCurrentThreadId' => ['int'],
'Thread::getRefCount' => ['int'],
'Thread::getTerminationInfo' => ['array'],
'Thread::getThreadId' => ['int'],
'Thread::globally' => ['mixed'],
'Thread::isGarbage' => ['bool'],
'Thread::isJoined' => ['bool'],
'Thread::isRunning' => ['bool'],
'Thread::isStarted' => ['bool'],
'Thread::isTerminated' => ['bool'],
'Thread::isWaiting' => ['bool'],
'Thread::join' => ['bool'],
'Thread::kill' => ['void'],
'Thread::lock' => ['bool'],
'Thread::merge' => ['bool', 'from'=>'', 'overwrite='=>'mixed'],
'Thread::notify' => ['bool'],
'Thread::notifyOne' => ['bool'],
'Thread::offsetExists' => ['bool', 'offset'=>'mixed'],
'Thread::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Thread::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Thread::offsetUnset' => ['void', 'offset'=>'mixed'],
'Thread::pop' => ['bool'],
'Thread::run' => ['void'],
'Thread::setGarbage' => ['void'],
'Thread::shift' => ['bool'],
'Thread::start' => ['bool', 'options='=>'int'],
'Thread::synchronized' => ['mixed', 'block'=>'Closure', '_='=>'mixed'],
'Thread::unlock' => ['bool'],
'Thread::wait' => ['bool', 'timeout='=>'int'],
'Threaded::__construct' => ['void'],
'Threaded::addRef' => ['void'],
'Threaded::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Threaded::count' => ['int'],
'Threaded::delRef' => ['void'],
'Threaded::extend' => ['bool', 'class'=>'string'],
'Threaded::from' => ['Threaded', 'run'=>'Closure', 'construct='=>'Closure', 'args='=>'array'],
'Threaded::getRefCount' => ['int'],
'Threaded::getTerminationInfo' => ['array'],
'Threaded::isGarbage' => ['bool'],
'Threaded::isRunning' => ['bool'],
'Threaded::isTerminated' => ['bool'],
'Threaded::isWaiting' => ['bool'],
'Threaded::lock' => ['bool'],
'Threaded::merge' => ['bool', 'from'=>'mixed', 'overwrite='=>'bool'],
'Threaded::notify' => ['bool'],
'Threaded::notifyOne' => ['bool'],
'Threaded::offsetExists' => ['bool', 'offset'=>'mixed'],
'Threaded::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Threaded::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Threaded::offsetUnset' => ['void', 'offset'=>'mixed'],
'Threaded::pop' => ['bool'],
'Threaded::run' => ['void'],
'Threaded::setGarbage' => ['void'],
'Threaded::shift' => ['mixed'],
'Threaded::synchronized' => ['mixed', 'block'=>'Closure', '...args='=>'mixed'],
'Threaded::unlock' => ['bool'],
'Threaded::wait' => ['bool', 'timeout='=>'int'],
'Throwable::__toString' => ['string'],
'Throwable::getCode' => ['int|string'],
'Throwable::getFile' => ['string'],
'Throwable::getLine' => ['int'],
'Throwable::getMessage' => ['string'],
'Throwable::getPrevious' => ['?Throwable'],
'Throwable::getTrace' => ['list<array<string,mixed>>'],
'Throwable::getTraceAsString' => ['string'],
'tidy::__construct' => ['void', 'filename='=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::body' => ['tidyNode'],
'tidy::cleanRepair' => ['bool'],
'tidy::diagnose' => ['bool'],
'tidy::getConfig' => ['array'],
'tidy::getHtmlVer' => ['int'],
'tidy::getOpt' => ['mixed', 'option'=>'string'],
'tidy::getOptDoc' => ['string', 'option'=>'string'],
'tidy::getRelease' => ['string'],
'tidy::getStatus' => ['int'],
'tidy::head' => ['tidyNode'],
'tidy::html' => ['tidyNode'],
'tidy::htmlver' => ['int'],
'tidy::isXhtml' => ['bool'],
'tidy::isXml' => ['bool'],
'tidy::parseFile' => ['bool', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::parseString' => ['bool', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::repairFile' => ['string', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::repairString' => ['string', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::root' => ['tidyNode'],
'tidy_access_count' => ['int', 'tidy'=>'tidy'],
'tidy_clean_repair' => ['bool', 'tidy'=>'tidy'],
'tidy_config_count' => ['int', 'tidy'=>'tidy'],
'tidy_diagnose' => ['bool', 'tidy'=>'tidy'],
'tidy_error_count' => ['int', 'tidy'=>'tidy'],
'tidy_get_body' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_config' => ['array', 'tidy'=>'tidy'],
'tidy_get_error_buffer' => ['string', 'tidy'=>'tidy'],
'tidy_get_head' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_html' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_html_ver' => ['int', 'tidy'=>'tidy'],
'tidy_get_opt_doc' => ['string', 'tidy'=>'tidy', 'option'=>'string'],
'tidy_get_output' => ['string', 'tidy'=>'tidy'],
'tidy_get_release' => ['string'],
'tidy_get_root' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_status' => ['int', 'tidy'=>'tidy'],
'tidy_getopt' => ['mixed', 'tidy'=>'string', 'option'=>'tidy'],
'tidy_is_xhtml' => ['bool', 'tidy'=>'tidy'],
'tidy_is_xml' => ['bool', 'tidy'=>'tidy'],
'tidy_load_config' => ['void', 'filename'=>'string', 'encoding'=>'string'],
'tidy_parse_file' => ['tidy', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy_parse_string' => ['tidy', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy_repair_file' => ['string', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy_repair_string' => ['string', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy_reset_config' => ['bool'],
'tidy_save_config' => ['bool', 'filename'=>'string'],
'tidy_set_encoding' => ['bool', 'encoding'=>'string'],
'tidy_setopt' => ['bool', 'option'=>'string', 'value'=>'mixed'],
'tidy_warning_count' => ['int', 'tidy'=>'tidy'],
'tidyNode::__construct' => ['void'],
'tidyNode::getParent' => ['tidyNode'],
'tidyNode::hasChildren' => ['bool'],
'tidyNode::hasSiblings' => ['bool'],
'tidyNode::isAsp' => ['bool'],
'tidyNode::isComment' => ['bool'],
'tidyNode::isHtml' => ['bool'],
'tidyNode::isJste' => ['bool'],
'tidyNode::isPhp' => ['bool'],
'tidyNode::isText' => ['bool'],
'time' => ['int'],
'time_nanosleep' => ['array{0:int,1:int}|bool', 'seconds'=>'int', 'nanoseconds'=>'int'],
'time_sleep_until' => ['bool', 'timestamp'=>'float'],
'timezone_abbreviations_list' => ['array<string, list<array{dst: bool, offset: int, timezone_id: string|null}>>|false'],
'timezone_identifiers_list' => ['list<string>|false', 'timezoneGroup='=>'int', 'countryCode='=>'?string'],
'timezone_location_get' => ['array|false', 'object'=>'DateTimeZone'],
'timezone_name_from_abbr' => ['string|false', 'abbr'=>'string', 'utcOffset='=>'int', 'isDST='=>'int'],
'timezone_name_get' => ['string', 'object'=>'DateTimeZone'],
'timezone_offset_get' => ['int|false', 'object'=>'DateTimeZone', 'datetime'=>'DateTimeInterface'],
'timezone_open' => ['DateTimeZone|false', 'timezone'=>'string'],
'timezone_transitions_get' => ['list<array{ts: int, time: string, offset: int, isdst: bool, abbr: string}>|false', 'object'=>'DateTimeZone', 'timestampBegin='=>'int', 'timestampEnd='=>'int'],
'timezone_version_get' => ['string'],
'tmpfile' => ['resource|false'],
'token_get_all' => ['list<string|array{0:int,1:string,2:int}>', 'code'=>'string', 'flags='=>'int'],
'token_name' => ['string', 'id'=>'int'],
'TokyoTyrant::__construct' => ['void', 'host='=>'string', 'port='=>'int', 'options='=>'array'],
'TokyoTyrant::add' => ['int|float', 'key'=>'string', 'increment'=>'float', 'type='=>'int'],
'TokyoTyrant::connect' => ['TokyoTyrant', 'host'=>'string', 'port='=>'int', 'options='=>'array'],
'TokyoTyrant::connectUri' => ['TokyoTyrant', 'uri'=>'string'],
'TokyoTyrant::copy' => ['TokyoTyrant', 'path'=>'string'],
'TokyoTyrant::ext' => ['string', 'name'=>'string', 'options'=>'int', 'key'=>'string', 'value'=>'string'],
'TokyoTyrant::fwmKeys' => ['array', 'prefix'=>'string', 'max_recs'=>'int'],
'TokyoTyrant::get' => ['array', 'keys'=>'mixed'],
'TokyoTyrant::getIterator' => ['TokyoTyrantIterator'],
'TokyoTyrant::num' => ['int'],
'TokyoTyrant::out' => ['string', 'keys'=>'mixed'],
'TokyoTyrant::put' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putCat' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putKeep' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putNr' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putShl' => ['mixed', 'key'=>'string', 'value'=>'string', 'width'=>'int'],
'TokyoTyrant::restore' => ['mixed', 'log_dir'=>'string', 'timestamp'=>'int', 'check_consistency='=>'bool'],
'TokyoTyrant::setMaster' => ['mixed', 'host'=>'string', 'port'=>'int', 'timestamp'=>'int', 'check_consistency='=>'bool'],
'TokyoTyrant::size' => ['int', 'key'=>'string'],
'TokyoTyrant::stat' => ['array'],
'TokyoTyrant::sync' => ['mixed'],
'TokyoTyrant::tune' => ['TokyoTyrant', 'timeout'=>'float', 'options='=>'int'],
'TokyoTyrant::vanish' => ['mixed'],
'TokyoTyrantIterator::__construct' => ['void', 'object'=>'mixed'],
'TokyoTyrantIterator::current' => ['mixed'],
'TokyoTyrantIterator::key' => ['mixed'],
'TokyoTyrantIterator::next' => ['mixed'],
'TokyoTyrantIterator::rewind' => ['void'],
'TokyoTyrantIterator::valid' => ['bool'],
'TokyoTyrantQuery::__construct' => ['void', 'table'=>'TokyoTyrantTable'],
'TokyoTyrantQuery::addCond' => ['mixed', 'name'=>'string', 'op'=>'int', 'expr'=>'string'],
'TokyoTyrantQuery::count' => ['int'],
'TokyoTyrantQuery::current' => ['array'],
'TokyoTyrantQuery::hint' => ['string'],
'TokyoTyrantQuery::key' => ['string'],
'TokyoTyrantQuery::metaSearch' => ['array', 'queries'=>'array', 'type'=>'int'],
'TokyoTyrantQuery::next' => ['array'],
'TokyoTyrantQuery::out' => ['TokyoTyrantQuery'],
'TokyoTyrantQuery::rewind' => ['bool'],
'TokyoTyrantQuery::search' => ['array'],
'TokyoTyrantQuery::setLimit' => ['mixed', 'max='=>'int', 'skip='=>'int'],
'TokyoTyrantQuery::setOrder' => ['mixed', 'name'=>'string', 'type'=>'int'],
'TokyoTyrantQuery::valid' => ['bool'],
'TokyoTyrantTable::add' => ['void', 'key'=>'string', 'increment'=>'mixed', 'type='=>'string'],
'TokyoTyrantTable::genUid' => ['int'],
'TokyoTyrantTable::get' => ['array', 'keys'=>'mixed'],
'TokyoTyrantTable::getIterator' => ['TokyoTyrantIterator'],
'TokyoTyrantTable::getQuery' => ['TokyoTyrantQuery'],
'TokyoTyrantTable::out' => ['void', 'keys'=>'mixed'],
'TokyoTyrantTable::put' => ['int', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putCat' => ['void', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putKeep' => ['void', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putNr' => ['void', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrantTable::putShl' => ['void', 'key'=>'string', 'value'=>'string', 'width'=>'int'],
'TokyoTyrantTable::setIndex' => ['mixed', 'column'=>'string', 'type'=>'int'],
'touch' => ['bool', 'filename'=>'string', 'mtime='=>'int', 'atime='=>'int'],
'trader_acos' => ['array', 'real'=>'array'],
'trader_ad' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array'],
'trader_add' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_adosc' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int'],
'trader_adx' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_adxr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_apo' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'mAType='=>'int'],
'trader_aroon' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_aroonosc' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_asin' => ['array', 'real'=>'array'],
'trader_atan' => ['array', 'real'=>'array'],
'trader_atr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_avgprice' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_bbands' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDevUp='=>'float', 'nbDevDn='=>'float', 'mAType='=>'int'],
'trader_beta' => ['array', 'real0'=>'array', 'real1'=>'array', 'timePeriod='=>'int'],
'trader_bop' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cci' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_cdl2crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3blackcrows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3inside' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3linestrike' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3outside' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3starsinsouth' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3whitesoldiers' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlabandonedbaby' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdladvanceblock' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlbelthold' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlbreakaway' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlclosingmarubozu' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlconcealbabyswall' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlcounterattack' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldarkcloudcover' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdldoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldragonflydoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlengulfing' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdleveningdojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdleveningstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlgapsidesidewhite' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlgravestonedoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhammer' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhangingman' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlharami' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlharamicross' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhighwave' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhikkake' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhikkakemod' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhomingpigeon' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlidentical3crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlinneck' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlinvertedhammer' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlkicking' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlkickingbylength' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlladderbottom' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdllongleggeddoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdllongline' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmarubozu' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmatchinglow' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmathold' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlmorningdojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlmorningstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlonneck' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlpiercing' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlrickshawman' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlrisefall3methods' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlseparatinglines' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlshootingstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlshortline' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlspinningtop' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlstalledpattern' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlsticksandwich' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltakuri' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltasukigap' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlthrusting' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltristar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlunique3river' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlupsidegap2crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlxsidegap3methods' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_ceil' => ['array', 'real'=>'array'],
'trader_cmo' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_correl' => ['array', 'real0'=>'array', 'real1'=>'array', 'timePeriod='=>'int'],
'trader_cos' => ['array', 'real'=>'array'],
'trader_cosh' => ['array', 'real'=>'array'],
'trader_dema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_div' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_dx' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_ema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_errno' => ['int'],
'trader_exp' => ['array', 'real'=>'array'],
'trader_floor' => ['array', 'real'=>'array'],
'trader_get_compat' => ['int'],
'trader_get_unstable_period' => ['int', 'functionId'=>'int'],
'trader_ht_dcperiod' => ['array', 'real'=>'array'],
'trader_ht_dcphase' => ['array', 'real'=>'array'],
'trader_ht_phasor' => ['array', 'real'=>'array'],
'trader_ht_sine' => ['array', 'real'=>'array'],
'trader_ht_trendline' => ['array', 'real'=>'array'],
'trader_ht_trendmode' => ['array', 'real'=>'array'],
'trader_kama' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_angle' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_intercept' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_slope' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_ln' => ['array', 'real'=>'array'],
'trader_log10' => ['array', 'real'=>'array'],
'trader_ma' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'mAType='=>'int'],
'trader_macd' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'signalPeriod='=>'int'],
'trader_macdext' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'fastMAType='=>'int', 'slowPeriod='=>'int', 'slowMAType='=>'int', 'signalPeriod='=>'int', 'signalMAType='=>'int'],
'trader_macdfix' => ['array', 'real'=>'array', 'signalPeriod='=>'int'],
'trader_mama' => ['array', 'real'=>'array', 'fastLimit='=>'float', 'slowLimit='=>'float'],
'trader_mavp' => ['array', 'real'=>'array', 'periods'=>'array', 'minPeriod='=>'int', 'maxPeriod='=>'int', 'mAType='=>'int'],
'trader_max' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_maxindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_medprice' => ['array', 'high'=>'array', 'low'=>'array'],
'trader_mfi' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array', 'timePeriod='=>'int'],
'trader_midpoint' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_midprice' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_min' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minmax' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minmaxindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minus_di' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_minus_dm' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_mom' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_mult' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_natr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_obv' => ['array', 'real'=>'array', 'volume'=>'array'],
'trader_plus_di' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_plus_dm' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_ppo' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'mAType='=>'int'],
'trader_roc' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocp' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocr' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocr100' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rsi' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_sar' => ['array', 'high'=>'array', 'low'=>'array', 'acceleration='=>'float', 'maximum='=>'float'],
'trader_sarext' => ['array', 'high'=>'array', 'low'=>'array', 'startValue='=>'float', 'offsetOnReverse='=>'float', 'accelerationInitLong='=>'float', 'accelerationLong='=>'float', 'accelerationMaxLong='=>'float', 'accelerationInitShort='=>'float', 'accelerationShort='=>'float', 'accelerationMaxShort='=>'float'],
'trader_set_compat' => ['void', 'compatId'=>'int'],
'trader_set_unstable_period' => ['void', 'functionId'=>'int', 'timePeriod'=>'int'],
'trader_sin' => ['array', 'real'=>'array'],
'trader_sinh' => ['array', 'real'=>'array'],
'trader_sma' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_sqrt' => ['array', 'real'=>'array'],
'trader_stddev' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDev='=>'float'],
'trader_stoch' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'fastK_Period='=>'int', 'slowK_Period='=>'int', 'slowK_MAType='=>'int', 'slowD_Period='=>'int', 'slowD_MAType='=>'int'],
'trader_stochf' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'fastK_Period='=>'int', 'fastD_Period='=>'int', 'fastD_MAType='=>'int'],
'trader_stochrsi' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'fastK_Period='=>'int', 'fastD_Period='=>'int', 'fastD_MAType='=>'int'],
'trader_sub' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_sum' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_t3' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'vFactor='=>'float'],
'trader_tan' => ['array', 'real'=>'array'],
'trader_tanh' => ['array', 'real'=>'array'],
'trader_tema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_trange' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_trima' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_trix' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_tsf' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_typprice' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_ultosc' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod1='=>'int', 'timePeriod2='=>'int', 'timePeriod3='=>'int'],
'trader_var' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDev='=>'float'],
'trader_wclprice' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_willr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_wma' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trait_exists' => ['?bool', 'trait'=>'string', 'autoload='=>'bool'],
'Transliterator::create' => ['?Transliterator', 'id'=>'string', 'direction='=>'int'],
'Transliterator::createFromRules' => ['?Transliterator', 'rules'=>'string', 'direction='=>'int'],
'Transliterator::createInverse' => ['Transliterator'],
'Transliterator::getErrorCode' => ['int'],
'Transliterator::getErrorMessage' => ['string'],
'Transliterator::listIDs' => ['array'],
'Transliterator::transliterate' => ['string|false', 'subject'=>'string', 'start='=>'int', 'end='=>'int'],
'transliterator_create' => ['?Transliterator', 'id'=>'string', 'direction='=>'int'],
'transliterator_create_from_rules' => ['?Transliterator', 'rules'=>'string', 'direction='=>'int'],
'transliterator_create_inverse' => ['Transliterator', 'transliterator'=>'Transliterator'],
'transliterator_get_error_code' => ['int', 'transliterator'=>'Transliterator'],
'transliterator_get_error_message' => ['string', 'transliterator'=>'Transliterator'],
'transliterator_list_ids' => ['array'],
'transliterator_transliterate' => ['string|false', 'transliterator'=>'Transliterator|string', 'string'=>'string', 'start='=>'int', 'end='=>'int'],
'trigger_error' => ['bool', 'message'=>'string', 'error_level='=>'256|512|1024|16384'],
'trim' => ['string', 'string'=>'string', 'characters='=>'string'],
'TypeError::__clone' => ['void'],
'TypeError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?TypeError'],
'TypeError::__toString' => ['string'],
'TypeError::getCode' => ['int'],
'TypeError::getFile' => ['string'],
'TypeError::getLine' => ['int'],
'TypeError::getMessage' => ['string'],
'TypeError::getPrevious' => ['Throwable|TypeError|null'],
'TypeError::getTrace' => ['list<array<string,mixed>>'],
'TypeError::getTraceAsString' => ['string'],
'uasort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'ucfirst' => ['string', 'string'=>'string'],
'UConverter::__construct' => ['void', 'destination_encoding='=>'string', 'source_encoding='=>'string'],
'UConverter::convert' => ['string', 'string'=>'string', 'reverse='=>'bool'],
'UConverter::fromUCallback' => ['mixed', 'reason'=>'int', 'source'=>'string', 'codePoint'=>'string', '&w_error'=>'int'],
'UConverter::getAliases' => ['array', 'name'=>'string'],
'UConverter::getAvailable' => ['array'],
'UConverter::getDestinationEncoding' => ['string'],
'UConverter::getDestinationType' => ['int'],
'UConverter::getErrorCode' => ['int'],
'UConverter::getErrorMessage' => ['string'],
'UConverter::getSourceEncoding' => ['string'],
'UConverter::getSourceType' => ['int'],
'UConverter::getStandards' => ['array'],
'UConverter::getSubstChars' => ['string'],
'UConverter::reasonText' => ['string', 'reason='=>'int'],
'UConverter::setDestinationEncoding' => ['bool', 'encoding'=>'string'],
'UConverter::setSourceEncoding' => ['bool', 'encoding'=>'string'],
'UConverter::setSubstChars' => ['bool', 'chars'=>'string'],
'UConverter::toUCallback' => ['mixed', 'reason'=>'int', 'source'=>'string', 'codeUnits'=>'string', '&w_error'=>'int'],
'UConverter::transcode' => ['string', 'string'=>'string', 'toEncoding'=>'string', 'fromEncoding'=>'string', 'options='=>'?array'],
'ucwords' => ['string', 'string'=>'string', 'separators='=>'string'],
'udm_add_search_limit' => ['bool', 'agent'=>'resource', 'var'=>'int', 'value'=>'string'],
'udm_alloc_agent' => ['resource', 'dbaddr'=>'string', 'dbmode='=>'string'],
'udm_alloc_agent_array' => ['resource', 'databases'=>'array'],
'udm_api_version' => ['int'],
'udm_cat_list' => ['array', 'agent'=>'resource', 'category'=>'string'],
'udm_cat_path' => ['array', 'agent'=>'resource', 'category'=>'string'],
'udm_check_charset' => ['bool', 'agent'=>'resource', 'charset'=>'string'],
'udm_check_stored' => ['int', 'agent'=>'', 'link'=>'int', 'doc_id'=>'string'],
'udm_clear_search_limits' => ['bool', 'agent'=>'resource'],
'udm_close_stored' => ['int', 'agent'=>'', 'link'=>'int'],
'udm_crc32' => ['int', 'agent'=>'resource', 'string'=>'string'],
'udm_errno' => ['int', 'agent'=>'resource'],
'udm_error' => ['string', 'agent'=>'resource'],
'udm_find' => ['resource', 'agent'=>'resource', 'query'=>'string'],
'udm_free_agent' => ['int', 'agent'=>'resource'],
'udm_free_ispell_data' => ['bool', 'agent'=>'int'],
'udm_free_res' => ['bool', 'res'=>'resource'],
'udm_get_doc_count' => ['int', 'agent'=>'resource'],
'udm_get_res_field' => ['string', 'res'=>'resource', 'row'=>'int', 'field'=>'int'],
'udm_get_res_param' => ['string', 'res'=>'resource', 'param'=>'int'],
'udm_hash32' => ['int', 'agent'=>'resource', 'string'=>'string'],
'udm_load_ispell_data' => ['bool', 'agent'=>'resource', 'var'=>'int', 'val1'=>'string', 'val2'=>'string', 'flag'=>'int'],
'udm_open_stored' => ['int', 'agent'=>'', 'storedaddr'=>'string'],
'udm_set_agent_param' => ['bool', 'agent'=>'resource', 'var'=>'int', 'val'=>'string'],
'ui\area::onDraw' => ['', 'pen'=>'UI\Draw\Pen', 'areaSize'=>'UI\Size', 'clipPoint'=>'UI\Point', 'clipSize'=>'UI\Size'],
'ui\area::onKey' => ['', 'key'=>'string', 'ext'=>'int', 'flags'=>'int'],
'ui\area::onMouse' => ['', 'areaPoint'=>'UI\Point', 'areaSize'=>'UI\Size', 'flags'=>'int'],
'ui\area::redraw' => [''],
'ui\area::scrollTo' => ['', 'point'=>'UI\Point', 'size'=>'UI\Size'],
'ui\area::setSize' => ['', 'size'=>'UI\Size'],
'ui\control::destroy' => [''],
'ui\control::disable' => [''],
'ui\control::enable' => [''],
'ui\control::getParent' => ['UI\Control'],
'ui\control::getTopLevel' => ['int'],
'ui\control::hide' => [''],
'ui\control::isEnabled' => ['bool'],
'ui\control::isVisible' => ['bool'],
'ui\control::setParent' => ['', 'parent'=>'UI\Control'],
'ui\control::show' => [''],
'ui\controls\box::append' => ['int', 'control'=>'Control', 'stretchy='=>'bool'],
'ui\controls\box::delete' => ['bool', 'index'=>'int'],
'ui\controls\box::getOrientation' => ['int'],
'ui\controls\box::isPadded' => ['bool'],
'ui\controls\box::setPadded' => ['', 'padded'=>'bool'],
'ui\controls\button::getText' => ['string'],
'ui\controls\button::onClick' => [''],
'ui\controls\button::setText' => ['', 'text'=>'string'],
'ui\controls\check::getText' => ['string'],
'ui\controls\check::isChecked' => ['bool'],
'ui\controls\check::onToggle' => [''],
'ui\controls\check::setChecked' => ['', 'checked'=>'bool'],
'ui\controls\check::setText' => ['', 'text'=>'string'],
'ui\controls\colorbutton::getColor' => ['UI\Color'],
'ui\controls\colorbutton::onChange' => [''],
'ui\controls\combo::append' => ['', 'text'=>'string'],
'ui\controls\combo::getSelected' => ['int'],
'ui\controls\combo::onSelected' => [''],
'ui\controls\combo::setSelected' => ['', 'index'=>'int'],
'ui\controls\editablecombo::append' => ['', 'text'=>'string'],
'ui\controls\editablecombo::getText' => ['string'],
'ui\controls\editablecombo::onChange' => [''],
'ui\controls\editablecombo::setText' => ['', 'text'=>'string'],
'ui\controls\entry::getText' => ['string'],
'ui\controls\entry::isReadOnly' => ['bool'],
'ui\controls\entry::onChange' => [''],
'ui\controls\entry::setReadOnly' => ['', 'readOnly'=>'bool'],
'ui\controls\entry::setText' => ['', 'text'=>'string'],
'ui\controls\form::append' => ['int', 'label'=>'string', 'control'=>'UI\Control', 'stretchy='=>'bool'],
'ui\controls\form::delete' => ['bool', 'index'=>'int'],
'ui\controls\form::isPadded' => ['bool'],
'ui\controls\form::setPadded' => ['', 'padded'=>'bool'],
'ui\controls\grid::append' => ['', 'control'=>'UI\Control', 'left'=>'int', 'top'=>'int', 'xspan'=>'int', 'yspan'=>'int', 'hexpand'=>'bool', 'halign'=>'int', 'vexpand'=>'bool', 'valign'=>'int'],
'ui\controls\grid::isPadded' => ['bool'],
'ui\controls\grid::setPadded' => ['', 'padding'=>'bool'],
'ui\controls\group::append' => ['', 'control'=>'UI\Control'],
'ui\controls\group::getTitle' => ['string'],
'ui\controls\group::hasMargin' => ['bool'],
'ui\controls\group::setMargin' => ['', 'margin'=>'bool'],
'ui\controls\group::setTitle' => ['', 'title'=>'string'],
'ui\controls\label::getText' => ['string'],
'ui\controls\label::setText' => ['', 'text'=>'string'],
'ui\controls\multilineentry::append' => ['', 'text'=>'string'],
'ui\controls\multilineentry::getText' => ['string'],
'ui\controls\multilineentry::isReadOnly' => ['bool'],
'ui\controls\multilineentry::onChange' => [''],
'ui\controls\multilineentry::setReadOnly' => ['', 'readOnly'=>'bool'],
'ui\controls\multilineentry::setText' => ['', 'text'=>'string'],
'ui\controls\progress::getValue' => ['int'],
'ui\controls\progress::setValue' => ['', 'value'=>'int'],
'ui\controls\radio::append' => ['', 'text'=>'string'],
'ui\controls\radio::getSelected' => ['int'],
'ui\controls\radio::onSelected' => [''],
'ui\controls\radio::setSelected' => ['', 'index'=>'int'],
'ui\controls\slider::getValue' => ['int'],
'ui\controls\slider::onChange' => [''],
'ui\controls\slider::setValue' => ['', 'value'=>'int'],
'ui\controls\spin::getValue' => ['int'],
'ui\controls\spin::onChange' => [''],
'ui\controls\spin::setValue' => ['', 'value'=>'int'],
'ui\controls\tab::append' => ['int', 'name'=>'string', 'control'=>'UI\Control'],
'ui\controls\tab::delete' => ['bool', 'index'=>'int'],
'ui\controls\tab::hasMargin' => ['bool', 'page'=>'int'],
'ui\controls\tab::insertAt' => ['', 'name'=>'string', 'page'=>'int', 'control'=>'UI\Control'],
'ui\controls\tab::pages' => ['int'],
'ui\controls\tab::setMargin' => ['', 'page'=>'int', 'margin'=>'bool'],
'ui\draw\brush::getColor' => ['UI\Draw\Color'],
'ui\draw\brush\gradient::delStop' => ['int', 'index'=>'int'],
'ui\draw\color::getChannel' => ['float', 'channel'=>'int'],
'ui\draw\color::setChannel' => ['void', 'channel'=>'int', 'value'=>'float'],
'ui\draw\matrix::invert' => [''],
'ui\draw\matrix::isInvertible' => ['bool'],
'ui\draw\matrix::multiply' => ['UI\Draw\Matrix', 'matrix'=>'UI\Draw\Matrix'],
'ui\draw\matrix::rotate' => ['', 'point'=>'UI\Point', 'amount'=>'float'],
'ui\draw\matrix::scale' => ['', 'center'=>'UI\Point', 'point'=>'UI\Point'],
'ui\draw\matrix::skew' => ['', 'point'=>'UI\Point', 'amount'=>'UI\Point'],
'ui\draw\matrix::translate' => ['', 'point'=>'UI\Point'],
'ui\draw\path::addRectangle' => ['', 'point'=>'UI\Point', 'size'=>'UI\Size'],
'ui\draw\path::arcTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::bezierTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::closeFigure' => [''],
'ui\draw\path::end' => [''],
'ui\draw\path::lineTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::newFigure' => ['', 'point'=>'UI\Point'],
'ui\draw\path::newFigureWithArc' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\pen::clip' => ['', 'path'=>'UI\Draw\Path'],
'ui\draw\pen::restore' => [''],
'ui\draw\pen::save' => [''],
'ui\draw\pen::transform' => ['', 'matrix'=>'UI\Draw\Matrix'],
'ui\draw\pen::write' => ['', 'point'=>'UI\Point', 'layout'=>'UI\Draw\Text\Layout'],
'ui\draw\stroke::getCap' => ['int'],
'ui\draw\stroke::getJoin' => ['int'],
'ui\draw\stroke::getMiterLimit' => ['float'],
'ui\draw\stroke::getThickness' => ['float'],
'ui\draw\stroke::setCap' => ['', 'cap'=>'int'],
'ui\draw\stroke::setJoin' => ['', 'join'=>'int'],
'ui\draw\stroke::setMiterLimit' => ['', 'limit'=>'float'],
'ui\draw\stroke::setThickness' => ['', 'thickness'=>'float'],
'ui\draw\text\font::getAscent' => ['float'],
'ui\draw\text\font::getDescent' => ['float'],
'ui\draw\text\font::getLeading' => ['float'],
'ui\draw\text\font::getUnderlinePosition' => ['float'],
'ui\draw\text\font::getUnderlineThickness' => ['float'],
'ui\draw\text\font\descriptor::getFamily' => ['string'],
'ui\draw\text\font\descriptor::getItalic' => ['int'],
'ui\draw\text\font\descriptor::getSize' => ['float'],
'ui\draw\text\font\descriptor::getStretch' => ['int'],
'ui\draw\text\font\descriptor::getWeight' => ['int'],
'ui\draw\text\font\fontfamilies' => ['array'],
'ui\draw\text\layout::setWidth' => ['', 'width'=>'float'],
'ui\executor::kill' => ['void'],
'ui\executor::onExecute' => ['void'],
'ui\menu::append' => ['UI\MenuItem', 'name'=>'string', 'type='=>'string'],
'ui\menu::appendAbout' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendCheck' => ['UI\MenuItem', 'name'=>'string', 'type='=>'string'],
'ui\menu::appendPreferences' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendQuit' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendSeparator' => [''],
'ui\menuitem::disable' => [''],
'ui\menuitem::enable' => [''],
'ui\menuitem::isChecked' => ['bool'],
'ui\menuitem::onClick' => [''],
'ui\menuitem::setChecked' => ['', 'checked'=>'bool'],
'ui\point::getX' => ['float'],
'ui\point::getY' => ['float'],
'ui\point::setX' => ['', 'point'=>'float'],
'ui\point::setY' => ['', 'point'=>'float'],
'ui\quit' => ['void'],
'ui\run' => ['void', 'flags='=>'int'],
'ui\size::getHeight' => ['float'],
'ui\size::getWidth' => ['float'],
'ui\size::setHeight' => ['', 'size'=>'float'],
'ui\size::setWidth' => ['', 'size'=>'float'],
'ui\window::add' => ['', 'control'=>'UI\Control'],
'ui\window::error' => ['', 'title'=>'string', 'msg'=>'string'],
'ui\window::getSize' => ['UI\Size'],
'ui\window::getTitle' => ['string'],
'ui\window::hasBorders' => ['bool'],
'ui\window::hasMargin' => ['bool'],
'ui\window::isFullScreen' => ['bool'],
'ui\window::msg' => ['', 'title'=>'string', 'msg'=>'string'],
'ui\window::onClosing' => ['int'],
'ui\window::open' => ['string'],
'ui\window::save' => ['string'],
'ui\window::setBorders' => ['', 'borders'=>'bool'],
'ui\window::setFullScreen' => ['', 'full'=>'bool'],
'ui\window::setMargin' => ['', 'margin'=>'bool'],
'ui\window::setSize' => ['', 'size'=>'UI\Size'],
'ui\window::setTitle' => ['', 'title'=>'string'],
'uksort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'umask' => ['int', 'mask='=>'int'],
'UnderflowException::__clone' => ['void'],
'UnderflowException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?UnderflowException'],
'UnderflowException::__toString' => ['string'],
'UnderflowException::getCode' => ['int'],
'UnderflowException::getFile' => ['string'],
'UnderflowException::getLine' => ['int'],
'UnderflowException::getMessage' => ['string'],
'UnderflowException::getPrevious' => ['Throwable|UnderflowException|null'],
'UnderflowException::getTrace' => ['list<array<string,mixed>>'],
'UnderflowException::getTraceAsString' => ['string'],
'UnexpectedValueException::__clone' => ['void'],
'UnexpectedValueException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?UnexpectedValueException'],
'UnexpectedValueException::__toString' => ['string'],
'UnexpectedValueException::getCode' => ['int'],
'UnexpectedValueException::getFile' => ['string'],
'UnexpectedValueException::getLine' => ['int'],
'UnexpectedValueException::getMessage' => ['string'],
'UnexpectedValueException::getPrevious' => ['Throwable|UnexpectedValueException|null'],
'UnexpectedValueException::getTrace' => ['list<array<string,mixed>>'],
'UnexpectedValueException::getTraceAsString' => ['string'],
'uniqid' => ['string', 'prefix='=>'string', 'more_entropy='=>'bool'],
'unixtojd' => ['int', 'timestamp='=>'int'],
'unlink' => ['bool', 'filename'=>'string', 'context='=>'resource'],
'unpack' => ['array|false', 'format'=>'string', 'string'=>'string', 'offset='=>'int'],
'unregister_tick_function' => ['void', 'callback'=>'callable'],
'unserialize' => ['mixed', 'data'=>'string', 'options='=>'array{allowed_classes?:string[]|bool}'],
'unset' => ['void', 'var='=>'mixed', '...args='=>'mixed'],
'untaint' => ['bool', '&rw_string'=>'string', '&...rw_strings='=>'string'],
'uopz_allow_exit' => ['void', 'allow'=>'bool'],
'uopz_backup' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_backup\'1' => ['void', 'function'=>'string'],
'uopz_compose' => ['void', 'name'=>'string', 'classes'=>'array', 'methods='=>'array', 'properties='=>'array', 'flags='=>'int'],
'uopz_copy' => ['Closure', 'class'=>'string', 'function'=>'string'],
'uopz_copy\'1' => ['Closure', 'function'=>'string'],
'uopz_delete' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_delete\'1' => ['void', 'function'=>'string'],
'uopz_extend' => ['bool', 'class'=>'string', 'parent'=>'string'],
'uopz_flags' => ['int', 'class'=>'string', 'function'=>'string', 'flags'=>'int'],
'uopz_flags\'1' => ['int', 'function'=>'string', 'flags'=>'int'],
'uopz_function' => ['void', 'class'=>'string', 'function'=>'string', 'handler'=>'Closure', 'modifiers='=>'int'],
'uopz_function\'1' => ['void', 'function'=>'string', 'handler'=>'Closure', 'modifiers='=>'int'],
'uopz_get_exit_status' => ['?int'],
'uopz_get_hook' => ['?Closure', 'class'=>'string', 'function'=>'string'],
'uopz_get_hook\'1' => ['?Closure', 'function'=>'string'],
'uopz_get_mock' => ['string|object|null', 'class'=>'string'],
'uopz_get_property' => ['mixed', 'class'=>'object|string', 'property'=>'string'],
'uopz_get_return' => ['mixed', 'class='=>'string', 'function='=>'string'],
'uopz_get_static' => ['?array', 'class'=>'string', 'function'=>'string'],
'uopz_implement' => ['bool', 'class'=>'string', 'interface'=>'string'],
'uopz_overload' => ['void', 'opcode'=>'int', 'callable'=>'Callable'],
'uopz_redefine' => ['bool', 'class'=>'string', 'constant'=>'string', 'value'=>'mixed'],
'uopz_redefine\'1' => ['bool', 'constant'=>'string', 'value'=>'mixed'],
'uopz_rename' => ['void', 'class'=>'string', 'function'=>'string', 'rename'=>'string'],
'uopz_rename\'1' => ['void', 'function'=>'string', 'rename'=>'string'],
'uopz_restore' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_restore\'1' => ['void', 'function'=>'string'],
'uopz_set_hook' => ['bool', 'class'=>'string', 'function'=>'string', 'hook'=>'Closure'],
'uopz_set_hook\'1' => ['bool', 'function'=>'string', 'hook'=>'Closure'],
'uopz_set_mock' => ['void', 'class'=>'string', 'mock'=>'object|string'],
'uopz_set_property' => ['void', 'class'=>'object|string', 'property'=>'string', 'value'=>'mixed'],
'uopz_set_return' => ['bool', 'class'=>'string', 'function'=>'string', 'value'=>'mixed', 'execute='=>'bool'],
'uopz_set_return\'1' => ['bool', 'function'=>'string', 'value'=>'mixed', 'execute='=>'bool'],
'uopz_set_static' => ['void', 'class'=>'string', 'function'=>'string', 'static'=>'array'],
'uopz_undefine' => ['bool', 'class'=>'string', 'constant'=>'string'],
'uopz_undefine\'1' => ['bool', 'constant'=>'string'],
'uopz_unset_hook' => ['bool', 'class'=>'string', 'function'=>'string'],
'uopz_unset_hook\'1' => ['bool', 'function'=>'string'],
'uopz_unset_mock' => ['void', 'class'=>'string'],
'uopz_unset_return' => ['bool', 'class='=>'string', 'function='=>'string'],
'uopz_unset_return\'1' => ['bool', 'function'=>'string'],
'urldecode' => ['string', 'string'=>'string'],
'urlencode' => ['string', 'string'=>'string'],
'use_soap_error_handler' => ['bool', 'enable='=>'bool'],
'user_error' => ['void', 'message'=>'string', 'error_level='=>'int'],
'usleep' => ['void', 'microseconds'=>'int'],
'usort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'utf8_decode' => ['string', 'string'=>'string'],
'utf8_encode' => ['string', 'string'=>'string'],
'V8Js::__construct' => ['void', 'object_name='=>'string', 'variables='=>'array', 'extensions='=>'array', 'report_uncaught_exceptions='=>'bool', 'snapshot_blob='=>'string'],
'V8Js::clearPendingException' => [''],
'V8Js::compileString' => ['resource', 'script'=>'', 'identifier='=>'string'],
'V8Js::createSnapshot' => ['false|string', 'embed_source'=>'string'],
'V8Js::executeScript' => ['', 'script'=>'resource', 'flags='=>'int', 'time_limit='=>'int', 'memory_limit='=>'int'],
'V8Js::executeString' => ['mixed', 'script'=>'string', 'identifier='=>'string', 'flags='=>'int'],
'V8Js::getExtensions' => ['string[]'],
'V8Js::getPendingException' => ['?V8JsException'],
'V8Js::registerExtension' => ['bool', 'extension_name'=>'string', 'script'=>'string', 'dependencies='=>'array', 'auto_enable='=>'bool'],
'V8Js::setAverageObjectSize' => ['', 'average_object_size'=>'int'],
'V8Js::setMemoryLimit' => ['', 'limit'=>'int'],
'V8Js::setModuleLoader' => ['', 'loader'=>'callable'],
'V8Js::setModuleNormaliser' => ['', 'normaliser'=>'callable'],
'V8Js::setTimeLimit' => ['', 'limit'=>'int'],
'V8JsException::getJsFileName' => ['string'],
'V8JsException::getJsLineNumber' => ['int'],
'V8JsException::getJsSourceLine' => ['int'],
'V8JsException::getJsTrace' => ['string'],
'V8JsScriptException::__clone' => ['void'],
'V8JsScriptException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'V8JsScriptException::__toString' => ['string'],
'V8JsScriptException::__wakeup' => ['void'],
'V8JsScriptException::getCode' => ['int'],
'V8JsScriptException::getFile' => ['string'],
'V8JsScriptException::getJsEndColumn' => ['int'],
'V8JsScriptException::getJsFileName' => ['string'],
'V8JsScriptException::getJsLineNumber' => ['int'],
'V8JsScriptException::getJsSourceLine' => ['string'],
'V8JsScriptException::getJsStartColumn' => ['int'],
'V8JsScriptException::getJsTrace' => ['string'],
'V8JsScriptException::getLine' => ['int'],
'V8JsScriptException::getMessage' => ['string'],
'V8JsScriptException::getPrevious' => ['Exception|Throwable'],
'V8JsScriptException::getTrace' => ['list<array<string,mixed>>'],
'V8JsScriptException::getTraceAsString' => ['string'],
'var_dump' => ['void', 'value'=>'mixed', '...values='=>'mixed'],
'var_export' => ['?string', 'value'=>'mixed', 'return='=>'bool'],
'VARIANT::__construct' => ['void', 'value='=>'mixed', 'type='=>'int', 'codepage='=>'int'],
'variant_abs' => ['mixed', 'value'=>'mixed'],
'variant_add' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_and' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_cast' => ['VARIANT', 'variant'=>'VARIANT', 'type'=>'int'],
'variant_cat' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_cmp' => ['int', 'left'=>'mixed', 'right'=>'mixed', 'locale_id='=>'int', 'flags='=>'int'],
'variant_date_from_timestamp' => ['VARIANT', 'timestamp'=>'int'],
'variant_date_to_timestamp' => ['int', 'variant'=>'VARIANT'],
'variant_div' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_eqv' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_fix' => ['mixed', 'value'=>'mixed'],
'variant_get_type' => ['int', 'variant'=>'VARIANT'],
'variant_idiv' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_imp' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_int' => ['mixed', 'value'=>'mixed'],
'variant_mod' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_mul' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_neg' => ['mixed', 'value'=>'mixed'],
'variant_not' => ['mixed', 'value'=>'mixed'],
'variant_or' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_pow' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_round' => ['mixed', 'value'=>'mixed', 'decimals'=>'int'],
'variant_set' => ['void', 'variant'=>'object', 'value'=>'mixed'],
'variant_set_type' => ['void', 'variant'=>'object', 'type'=>'int'],
'variant_sub' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_xor' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'VarnishAdmin::__construct' => ['void', 'args='=>'array'],
'VarnishAdmin::auth' => ['bool'],
'VarnishAdmin::ban' => ['int', 'vcl_regex'=>'string'],
'VarnishAdmin::banUrl' => ['int', 'vcl_regex'=>'string'],
'VarnishAdmin::clearPanic' => ['int'],
'VarnishAdmin::connect' => ['bool'],
'VarnishAdmin::disconnect' => ['bool'],
'VarnishAdmin::getPanic' => ['string'],
'VarnishAdmin::getParams' => ['array'],
'VarnishAdmin::isRunning' => ['bool'],
'VarnishAdmin::setCompat' => ['void', 'compat'=>'int'],
'VarnishAdmin::setHost' => ['void', 'host'=>'string'],
'VarnishAdmin::setIdent' => ['void', 'ident'=>'string'],
'VarnishAdmin::setParam' => ['int', 'name'=>'string', 'value'=>'string|int'],
'VarnishAdmin::setPort' => ['void', 'port'=>'int'],
'VarnishAdmin::setSecret' => ['void', 'secret'=>'string'],
'VarnishAdmin::setTimeout' => ['void', 'timeout'=>'int'],
'VarnishAdmin::start' => ['int'],
'VarnishAdmin::stop' => ['int'],
'VarnishLog::__construct' => ['void', 'args='=>'array'],
'VarnishLog::getLine' => ['array'],
'VarnishLog::getTagName' => ['string', 'index'=>'int'],
'VarnishStat::__construct' => ['void', 'args='=>'array'],
'VarnishStat::getSnapshot' => ['array'],
'version_compare' => ['bool', 'version1'=>'string', 'version2'=>'string', 'operator'=>'\'<\'|\'lt\'|\'<=\'|\'le\'|\'>\'|\'gt\'|\'>=\'|\'ge\'|\'==\'|\'=\'|\'eq\'|\'!=\'|\'<>\'|\'ne\''],
'version_compare\'1' => ['int', 'version1'=>'string', 'version2'=>'string'],
'vfprintf' => ['int', 'stream'=>'resource', 'format'=>'string', 'values'=>'array'],
'virtual' => ['bool', 'uri'=>'string'],
'vpopmail_add_alias_domain' => ['bool', 'domain'=>'string', 'aliasdomain'=>'string'],
'vpopmail_add_alias_domain_ex' => ['bool', 'olddomain'=>'string', 'newdomain'=>'string'],
'vpopmail_add_domain' => ['bool', 'domain'=>'string', 'dir'=>'string', 'uid'=>'int', 'gid'=>'int'],
'vpopmail_add_domain_ex' => ['bool', 'domain'=>'string', 'passwd'=>'string', 'quota='=>'string', 'bounce='=>'string', 'apop='=>'bool'],
'vpopmail_add_user' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'gecos='=>'string', 'apop='=>'bool'],
'vpopmail_alias_add' => ['bool', 'user'=>'string', 'domain'=>'string', 'alias'=>'string'],
'vpopmail_alias_del' => ['bool', 'user'=>'string', 'domain'=>'string'],
'vpopmail_alias_del_domain' => ['bool', 'domain'=>'string'],
'vpopmail_alias_get' => ['array', 'alias'=>'string', 'domain'=>'string'],
'vpopmail_alias_get_all' => ['array', 'domain'=>'string'],
'vpopmail_auth_user' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'apop='=>'string'],
'vpopmail_del_domain' => ['bool', 'domain'=>'string'],
'vpopmail_del_domain_ex' => ['bool', 'domain'=>'string'],
'vpopmail_del_user' => ['bool', 'user'=>'string', 'domain'=>'string'],
'vpopmail_error' => ['string'],
'vpopmail_passwd' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'apop='=>'bool'],
'vpopmail_set_user_quota' => ['bool', 'user'=>'string', 'domain'=>'string', 'quota'=>'string'],
'vprintf' => ['int', 'format'=>'string', 'values'=>'array'],
'vsprintf' => ['string', 'format'=>'string', 'values'=>'array'],
'Vtiful\Kernel\Excel::__construct' => ['void', 'config'=>'array'],
'Vtiful\Kernel\Excel::addSheet' => ['', 'sheetName'=>'string'],
'Vtiful\Kernel\Excel::autoFilter' => ['', 'scope'=>'string'],
'Vtiful\Kernel\Excel::constMemory' => ['', 'fileName'=>'string', 'sheetName='=>'string'],
'Vtiful\Kernel\Excel::data' => ['', 'data'=>'array'],
'Vtiful\Kernel\Excel::fileName' => ['', 'fileName'=>'string', 'sheetName='=>'string'],
'Vtiful\Kernel\Excel::getHandle' => [''],
'Vtiful\Kernel\Excel::header' => ['', 'headerData'=>'array'],
'Vtiful\Kernel\Excel::insertFormula' => ['', 'row'=>'int', 'column'=>'int', 'formula'=>'string'],
'Vtiful\Kernel\Excel::insertImage' => ['', 'row'=>'int', 'column'=>'int', 'localImagePath'=>'string'],
'Vtiful\Kernel\Excel::insertText' => ['', 'row'=>'int', 'column'=>'int', 'data'=>'string', 'format='=>'string'],
'Vtiful\Kernel\Excel::mergeCells' => ['', 'scope'=>'string', 'data'=>'string'],
'Vtiful\Kernel\Excel::output' => [''],
'Vtiful\Kernel\Excel::setColumn' => ['', 'range'=>'string', 'width'=>'float', 'format='=>'resource'],
'Vtiful\Kernel\Excel::setRow' => ['', 'range'=>'string', 'height'=>'float', 'format='=>'resource'],
'Vtiful\Kernel\Format::align' => ['', 'handle'=>'resource', 'style'=>'int'],
'Vtiful\Kernel\Format::bold' => ['', 'handle'=>'resource'],
'Vtiful\Kernel\Format::italic' => ['', 'handle'=>'resource'],
'Vtiful\Kernel\Format::underline' => ['', 'handle'=>'resource', 'style'=>'int'],
'w32api_deftype' => ['bool', 'typename'=>'string', 'member1_type'=>'string', 'member1_name'=>'string', '...args='=>'string'],
'w32api_init_dtype' => ['resource', 'typename'=>'string', 'value'=>'', '...args='=>''],
'w32api_invoke_function' => ['', 'funcname'=>'string', 'argument'=>'', '...args='=>''],
'w32api_register_function' => ['bool', 'library'=>'string', 'function_name'=>'string', 'return_type'=>'string'],
'w32api_set_call_method' => ['', 'method'=>'int'],
'wddx_add_vars' => ['bool', 'packet_id'=>'resource', 'var_names'=>'mixed', '...vars='=>'mixed'],
'wddx_deserialize' => ['mixed', 'packet'=>'string'],
'wddx_packet_end' => ['string', 'packet_id'=>'resource'],
'wddx_packet_start' => ['resource|false', 'comment='=>'string'],
'wddx_serialize_value' => ['string|false', 'value'=>'mixed', 'comment='=>'string'],
'wddx_serialize_vars' => ['string|false', 'var_name'=>'mixed', '...vars='=>'mixed'],
'WeakMap::__construct' => ['void'],
'WeakMap::count' => ['int'],
'WeakMap::current' => ['mixed'],
'WeakMap::key' => ['object'],
'WeakMap::next' => ['void'],
'WeakMap::offsetExists' => ['bool', 'object'=>'object'],
'WeakMap::offsetGet' => ['mixed', 'object'=>'object'],
'WeakMap::offsetSet' => ['void', 'object'=>'object', 'value'=>'mixed'],
'WeakMap::offsetUnset' => ['void', 'object'=>'object'],
'WeakMap::rewind' => ['void'],
'WeakMap::valid' => ['bool'],
'Weakref::acquire' => ['bool'],
'Weakref::get' => ['object'],
'Weakref::release' => ['bool'],
'Weakref::valid' => ['bool'],
'webObj::convertToString' => ['string'],
'webObj::free' => ['void'],
'webObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'webObj::updateFromString' => ['int', 'snippet'=>'string'],
'win32_continue_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_create_service' => ['int|false', 'details'=>'array', 'machine='=>'string'],
'win32_delete_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_get_last_control_message' => ['int'],
'win32_pause_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_ps_list_procs' => ['array'],
'win32_ps_stat_mem' => ['array'],
'win32_ps_stat_proc' => ['array', 'pid='=>'int'],
'win32_query_service_status' => ['array|false|int', 'servicename'=>'string', 'machine='=>'string'],
'win32_send_custom_control' => ['int', 'servicename'=>'string', 'control'=>'int', 'machine='=>'string'],
'win32_set_service_exit_code' => ['int', 'exitCode='=>'int'],
'win32_set_service_exit_mode' => ['bool', 'gracefulMode='=>'bool'],
'win32_set_service_status' => ['bool|int', 'status'=>'int', 'checkpoint='=>'int'],
'win32_start_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_start_service_ctrl_dispatcher' => ['bool|int', 'name'=>'string'],
'win32_stop_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'wincache_fcache_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_fcache_meminfo' => ['array|false'],
'wincache_lock' => ['bool', 'key'=>'string', 'isglobal='=>'bool'],
'wincache_ocache_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_ocache_meminfo' => ['array|false'],
'wincache_refresh_if_changed' => ['bool', 'files='=>'array'],
'wincache_rplist_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_rplist_meminfo' => ['array|false'],
'wincache_scache_info' => ['array|false', 'summaryonly='=>'bool'],
'wincache_scache_meminfo' => ['array|false'],
'wincache_ucache_add' => ['bool', 'key'=>'string', 'value'=>'mixed', 'ttl='=>'int'],
'wincache_ucache_add\'1' => ['bool', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'wincache_ucache_cas' => ['bool', 'key'=>'string', 'old_value'=>'int', 'new_value'=>'int'],
'wincache_ucache_clear' => ['bool'],
'wincache_ucache_dec' => ['int|false', 'key'=>'string', 'dec_by='=>'int', 'success='=>'bool'],
'wincache_ucache_delete' => ['bool', 'key'=>'mixed'],
'wincache_ucache_exists' => ['bool', 'key'=>'string'],
'wincache_ucache_get' => ['mixed', 'key'=>'mixed', '&w_success='=>'bool'],
'wincache_ucache_inc' => ['int|false', 'key'=>'string', 'inc_by='=>'int', 'success='=>'bool'],
'wincache_ucache_info' => ['array|false', 'summaryonly='=>'bool', 'key='=>'string'],
'wincache_ucache_meminfo' => ['array|false'],
'wincache_ucache_set' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int'],
'wincache_ucache_set\'1' => ['bool', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'wincache_unlock' => ['bool', 'key'=>'string'],
'wkhtmltox\image\converter::convert' => ['?string'],
'wkhtmltox\image\converter::getVersion' => ['string'],
'wkhtmltox\pdf\converter::add' => ['void', 'object'=>'wkhtmltox\PDF\Object'],
'wkhtmltox\pdf\converter::convert' => ['?string'],
'wkhtmltox\pdf\converter::getVersion' => ['string'],
'wordwrap' => ['string', 'string'=>'string', 'width='=>'int', 'break='=>'string', 'cut_long_words='=>'bool'],
'Worker::__construct' => ['void'],
'Worker::addRef' => ['void'],
'Worker::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Worker::collect' => ['int', 'collector='=>'Callable'],
'Worker::count' => ['int'],
'Worker::delRef' => ['void'],
'Worker::detach' => ['void'],
'Worker::extend' => ['bool', 'class'=>'string'],
'Worker::getCreatorId' => ['int'],
'Worker::getCurrentThread' => ['Thread'],
'Worker::getCurrentThreadId' => ['int'],
'Worker::getRefCount' => ['int'],
'Worker::getStacked' => ['int'],
'Worker::getTerminationInfo' => ['array'],
'Worker::getThreadId' => ['int'],
'Worker::globally' => ['mixed'],
'Worker::isGarbage' => ['bool'],
'Worker::isJoined' => ['bool'],
'Worker::isRunning' => ['bool'],
'Worker::isShutdown' => ['bool'],
'Worker::isStarted' => ['bool'],
'Worker::isTerminated' => ['bool'],
'Worker::isWaiting' => ['bool'],
'Worker::isWorking' => ['bool'],
'Worker::join' => ['bool'],
'Worker::kill' => ['bool'],
'Worker::lock' => ['bool'],
'Worker::merge' => ['bool', 'from'=>'', 'overwrite='=>'mixed'],
'Worker::notify' => ['bool'],
'Worker::notifyOne' => ['bool'],
'Worker::offsetExists' => ['bool', 'offset'=>'mixed'],
'Worker::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Worker::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Worker::offsetUnset' => ['void', 'offset'=>'mixed'],
'Worker::pop' => ['bool'],
'Worker::run' => ['void'],
'Worker::setGarbage' => ['void'],
'Worker::shift' => ['bool'],
'Worker::shutdown' => ['bool'],
'Worker::stack' => ['int', '&rw_work'=>'Threaded'],
'Worker::start' => ['bool', 'options='=>'int'],
'Worker::synchronized' => ['mixed', 'block'=>'Closure', '_='=>'mixed'],
'Worker::unlock' => ['bool'],
'Worker::unstack' => ['int', '&rw_work='=>'Threaded'],
'Worker::wait' => ['bool', 'timeout='=>'int'],
'xattr_get' => ['string', 'filename'=>'string', 'name'=>'string', 'flags='=>'int'],
'xattr_list' => ['array', 'filename'=>'string', 'flags='=>'int'],
'xattr_remove' => ['bool', 'filename'=>'string', 'name'=>'string', 'flags='=>'int'],
'xattr_set' => ['bool', 'filename'=>'string', 'name'=>'string', 'value'=>'string', 'flags='=>'int'],
'xattr_supported' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'xcache_asm' => ['string', 'filename'=>'string'],
'xcache_clear_cache' => ['void', 'type'=>'int', 'id='=>'int'],
'xcache_coredump' => ['string', 'op_type'=>'int'],
'xcache_count' => ['int', 'type'=>'int'],
'xcache_coverager_decode' => ['array', 'data'=>'string'],
'xcache_coverager_get' => ['array', 'clean='=>'bool'],
'xcache_coverager_start' => ['void', 'clean='=>'bool'],
'xcache_coverager_stop' => ['void', 'clean='=>'bool'],
'xcache_dasm_file' => ['string', 'filename'=>'string'],
'xcache_dasm_string' => ['string', 'code'=>'string'],
'xcache_dec' => ['int', 'name'=>'string', 'value='=>'int|mixed', 'ttl='=>'int'],
'xcache_decode' => ['bool', 'filename'=>'string'],
'xcache_encode' => ['string', 'filename'=>'string'],
'xcache_get' => ['mixed', 'name'=>'string'],
'xcache_get_data_type' => ['string', 'type'=>'int'],
'xcache_get_op_spec' => ['string', 'op_type'=>'int'],
'xcache_get_op_type' => ['string', 'op_type'=>'int'],
'xcache_get_opcode' => ['string', 'opcode'=>'int'],
'xcache_get_opcode_spec' => ['string', 'opcode'=>'int'],
'xcache_inc' => ['int', 'name'=>'string', 'value='=>'int|mixed', 'ttl='=>'int'],
'xcache_info' => ['array', 'type'=>'int', 'id'=>'int'],
'xcache_is_autoglobal' => ['string', 'name'=>'string'],
'xcache_isset' => ['bool', 'name'=>'string'],
'xcache_list' => ['array', 'type'=>'int', 'id'=>'int'],
'xcache_set' => ['bool', 'name'=>'string', 'value'=>'mixed', 'ttl='=>'int'],
'xcache_unset' => ['bool', 'name'=>'string'],
'xcache_unset_by_prefix' => ['bool', 'prefix'=>'string'],
'Xcom::__construct' => ['void', 'fabric_url='=>'string', 'fabric_token='=>'string', 'capability_token='=>'string'],
'Xcom::decode' => ['object', 'avro_msg'=>'string', 'json_schema'=>'string'],
'Xcom::encode' => ['string', 'data'=>'stdClass', 'avro_schema'=>'string'],
'Xcom::getDebugOutput' => ['string'],
'Xcom::getLastResponse' => ['string'],
'Xcom::getLastResponseInfo' => ['array'],
'Xcom::getOnboardingURL' => ['string', 'capability_name'=>'string', 'agreement_url'=>'string'],
'Xcom::send' => ['int', 'topic'=>'string', 'data'=>'mixed', 'json_schema='=>'string', 'http_headers='=>'array'],
'Xcom::sendAsync' => ['int', 'topic'=>'string', 'data'=>'mixed', 'json_schema='=>'string', 'http_headers='=>'array'],
'xdebug_break' => ['bool'],
'xdebug_call_class' => ['string', 'depth='=>'int'],
'xdebug_call_file' => ['string', 'depth='=>'int'],
'xdebug_call_function' => ['string', 'depth='=>'int'],
'xdebug_call_line' => ['int', 'depth='=>'int'],
'xdebug_clear_aggr_profiling_data' => ['bool'],
'xdebug_code_coverage_started' => ['bool'],
'xdebug_debug_zval' => ['void', '...varName'=>'string'],
'xdebug_debug_zval_stdout' => ['void', '...varName'=>'string'],
'xdebug_disable' => ['void'],
'xdebug_dump_aggr_profiling_data' => ['bool'],
'xdebug_dump_superglobals' => ['void'],
'xdebug_enable' => ['void'],
'xdebug_get_code_coverage' => ['array'],
'xdebug_get_collected_errors' => ['string', 'clean='=>'bool'],
'xdebug_get_declared_vars' => ['array'],
'xdebug_get_formatted_function_stack' => [''],
'xdebug_get_function_count' => ['int'],
'xdebug_get_function_stack' => ['array', 'message='=>'string', 'options='=>'int'],
'xdebug_get_headers' => ['array'],
'xdebug_get_monitored_functions' => ['array'],
'xdebug_get_profiler_filename' => ['string'],
'xdebug_get_stack_depth' => ['int'],
'xdebug_get_tracefile_name' => ['string'],
'xdebug_is_debugger_active' => ['bool'],
'xdebug_is_enabled' => ['bool'],
'xdebug_memory_usage' => ['int'],
'xdebug_peak_memory_usage' => ['int'],
'xdebug_print_function_stack' => ['array', 'message='=>'string', 'options='=>'int'],
'xdebug_set_filter' => ['void', 'group'=>'int', 'list_type'=>'int', 'configuration'=>'array'],
'xdebug_start_code_coverage' => ['void', 'options='=>'int'],
'xdebug_start_error_collection' => ['void'],
'xdebug_start_function_monitor' => ['void', 'list_of_functions_to_monitor'=>'string[]'],
'xdebug_start_trace' => ['void', 'trace_file'=>'', 'options='=>'int|mixed'],
'xdebug_stop_code_coverage' => ['void', 'cleanup='=>'bool'],
'xdebug_stop_error_collection' => ['void'],
'xdebug_stop_function_monitor' => ['void'],
'xdebug_stop_trace' => ['void'],
'xdebug_time_index' => ['float'],
'xdebug_var_dump' => ['void', '...var'=>''],
'xdiff_file_bdiff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_file_bdiff_size' => ['int', 'file'=>'string'],
'xdiff_file_bpatch' => ['bool', 'file'=>'string', 'patch'=>'string', 'dest'=>'string'],
'xdiff_file_diff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string', 'context='=>'int', 'minimal='=>'bool'],
'xdiff_file_diff_binary' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_file_merge3' => ['mixed', 'old_file'=>'string', 'new_file1'=>'string', 'new_file2'=>'string', 'dest'=>'string'],
'xdiff_file_patch' => ['mixed', 'file'=>'string', 'patch'=>'string', 'dest'=>'string', 'flags='=>'int'],
'xdiff_file_patch_binary' => ['bool', 'file'=>'string', 'patch'=>'string', 'dest'=>'string'],
'xdiff_file_rabdiff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_string_bdiff' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xdiff_string_bdiff_size' => ['int', 'patch'=>'string'],
'xdiff_string_bpatch' => ['string', 'string'=>'string', 'patch'=>'string'],
'xdiff_string_diff' => ['string', 'old_data'=>'string', 'new_data'=>'string', 'context='=>'int', 'minimal='=>'bool'],
'xdiff_string_diff_binary' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xdiff_string_merge3' => ['mixed', 'old_data'=>'string', 'new_data1'=>'string', 'new_data2'=>'string', 'error='=>'string'],
'xdiff_string_patch' => ['string', 'string'=>'string', 'patch'=>'string', 'flags='=>'int', '&w_error='=>'string'],
'xdiff_string_patch_binary' => ['string', 'string'=>'string', 'patch'=>'string'],
'xdiff_string_rabdiff' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xhprof_disable' => ['array'],
'xhprof_enable' => ['void', 'flags='=>'int', 'options='=>'array'],
'xhprof_sample_disable' => ['array'],
'xhprof_sample_enable' => ['void'],
'xml_error_string' => ['string', 'error_code'=>'int'],
'xml_get_current_byte_index' => ['int|false', 'parser'=>'resource'],
'xml_get_current_column_number' => ['int|false', 'parser'=>'resource'],
'xml_get_current_line_number' => ['int|false', 'parser'=>'resource'],
'xml_get_error_code' => ['int|false', 'parser'=>'resource'],
'xml_parse' => ['int', 'parser'=>'resource', 'data'=>'string', 'is_final='=>'bool'],
'xml_parse_into_struct' => ['int', 'parser'=>'resource', 'data'=>'string', '&w_values'=>'array', '&w_index='=>'array'],
'xml_parser_create' => ['resource', 'encoding='=>'string'],
'xml_parser_create_ns' => ['resource', 'encoding='=>'string', 'separator='=>'string'],
'xml_parser_free' => ['bool', 'parser'=>'resource'],
'xml_parser_get_option' => ['mixed|false', 'parser'=>'resource', 'option'=>'int'],
'xml_parser_set_option' => ['bool', 'parser'=>'resource', 'option'=>'int', 'value'=>'mixed'],
'xml_set_character_data_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'xml_set_default_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'xml_set_element_handler' => ['bool', 'parser'=>'resource', 'start_handler'=>'callable', 'end_handler'=>'callable'],
'xml_set_end_namespace_decl_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'xml_set_external_entity_ref_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'xml_set_notation_decl_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'xml_set_object' => ['bool', 'parser'=>'resource', 'object'=>'object'],
'xml_set_processing_instruction_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'xml_set_start_namespace_decl_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'xml_set_unparsed_entity_decl_handler' => ['bool', 'parser'=>'resource', 'handler'=>'callable'],
'XMLDiff\Base::__construct' => ['void', 'nsname'=>'string'],
'XMLDiff\Base::diff' => ['mixed', 'from'=>'mixed', 'to'=>'mixed'],
'XMLDiff\Base::merge' => ['mixed', 'src'=>'mixed', 'diff'=>'mixed'],
'XMLDiff\DOM::diff' => ['DOMDocument', 'from'=>'DOMDocument', 'to'=>'DOMDocument'],
'XMLDiff\DOM::merge' => ['DOMDocument', 'src'=>'DOMDocument', 'diff'=>'DOMDocument'],
'XMLDiff\File::diff' => ['string', 'from'=>'string', 'to'=>'string'],
'XMLDiff\File::merge' => ['string', 'src'=>'string', 'diff'=>'string'],
'XMLDiff\Memory::diff' => ['string', 'from'=>'string', 'to'=>'string'],
'XMLDiff\Memory::merge' => ['string', 'src'=>'string', 'diff'=>'string'],
'XMLReader::close' => ['bool'],
'XMLReader::expand' => ['DOMNode|false', 'basenode='=>'DOMNode'],
'XMLReader::getAttribute' => ['?string', 'name'=>'string'],
'XMLReader::getAttributeNo' => ['?string', 'index'=>'int'],
'XMLReader::getAttributeNs' => ['?string', 'name'=>'string', 'namespaceuri'=>'string'],
'XMLReader::getParserProperty' => ['bool', 'property'=>'int'],
'XMLReader::isValid' => ['bool'],
'XMLReader::lookupNamespace' => ['?string', 'prefix'=>'string'],
'XMLReader::moveToAttribute' => ['bool', 'name'=>'string'],
'XMLReader::moveToAttributeNo' => ['bool', 'index'=>'int'],
'XMLReader::moveToAttributeNs' => ['bool', 'localname'=>'string', 'namespaceuri'=>'string'],
'XMLReader::moveToElement' => ['bool'],
'XMLReader::moveToFirstAttribute' => ['bool'],
'XMLReader::moveToNextAttribute' => ['bool'],
'XMLReader::next' => ['bool', 'localname='=>'string'],
'XMLReader::open' => ['bool', 'uri'=>'string', 'encoding='=>'?string', 'options='=>'int'],
'XMLReader::read' => ['bool'],
'XMLReader::readInnerXML' => ['string'],
'XMLReader::readOuterXML' => ['string'],
'XMLReader::readString' => ['string'],
'XMLReader::setParserProperty' => ['bool', 'property'=>'int', 'value'=>'bool'],
'XMLReader::setRelaxNGSchema' => ['bool', 'filename'=>'string'],
'XMLReader::setRelaxNGSchemaSource' => ['bool', 'source'=>'string'],
'XMLReader::setSchema' => ['bool', 'filename'=>'string'],
'XMLReader::XML' => ['bool', 'source'=>'string', 'encoding='=>'?string', 'options='=>'int'],
'xmlrpc_decode' => ['mixed', 'xml'=>'string', 'encoding='=>'string'],
'xmlrpc_decode_request' => ['?array', 'xml'=>'string', '&w_method'=>'string', 'encoding='=>'string'],
'xmlrpc_encode' => ['string', 'value'=>'mixed'],
'xmlrpc_encode_request' => ['string', 'method'=>'string', 'params'=>'mixed', 'output_options='=>'array'],
'xmlrpc_get_type' => ['string', 'value'=>'mixed'],
'xmlrpc_is_fault' => ['bool', 'arg'=>'array'],
'xmlrpc_parse_method_descriptions' => ['array', 'xml'=>'string'],
'xmlrpc_server_add_introspection_data' => ['int', 'server'=>'resource', 'desc'=>'array'],
'xmlrpc_server_call_method' => ['string', 'server'=>'resource', 'xml'=>'string', 'user_data'=>'mixed', 'output_options='=>'array'],
'xmlrpc_server_create' => ['resource'],
'xmlrpc_server_destroy' => ['int', 'server'=>'resource'],
'xmlrpc_server_register_introspection_callback' => ['bool', 'server'=>'resource', 'function'=>'string'],
'xmlrpc_server_register_method' => ['bool', 'server'=>'resource', 'method_name'=>'string', 'function'=>'string'],
'xmlrpc_set_type' => ['bool', '&rw_value'=>'string|DateTime', 'type'=>'string'],
'XMLWriter::endAttribute' => ['bool'],
'XMLWriter::endCData' => ['bool'],
'XMLWriter::endComment' => ['bool'],
'XMLWriter::endDocument' => ['bool'],
'XMLWriter::endDTD' => ['bool', 'xmlwriter='=>''],
'XMLWriter::endDTDAttlist' => ['bool'],
'XMLWriter::endDTDElement' => ['bool'],
'XMLWriter::endDTDEntity' => ['bool'],
'XMLWriter::endElement' => ['bool'],
'XMLWriter::endPI' => ['bool'],
'XMLWriter::flush' => ['', 'empty='=>'bool', 'xmlwriter='=>''],
'XMLWriter::fullEndElement' => ['bool'],
'XMLWriter::openMemory' => ['bool'],
'XMLWriter::openURI' => ['bool', 'uri'=>'string'],
'XMLWriter::outputMemory' => ['string', 'flush='=>'bool', 'xmlwriter='=>''],
'XMLWriter::setIndent' => ['bool', 'indent'=>'bool'],
'XMLWriter::setIndentString' => ['bool', 'indentstring'=>'string'],
'XMLWriter::startAttribute' => ['bool', 'name'=>'string'],
'XMLWriter::startAttributeNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string'],
'XMLWriter::startCData' => ['bool'],
'XMLWriter::startComment' => ['bool'],
'XMLWriter::startDocument' => ['bool', 'version='=>'string', 'encoding='=>'string', 'standalone='=>'string'],
'XMLWriter::startDTD' => ['bool', 'qualifiedname'=>'string', 'publicid='=>'string', 'systemid='=>'string'],
'XMLWriter::startDTDAttlist' => ['bool', 'name'=>'string'],
'XMLWriter::startDTDElement' => ['bool', 'qualifiedname'=>'string'],
'XMLWriter::startDTDEntity' => ['bool', 'name'=>'string', 'isparam'=>'bool'],
'XMLWriter::startElement' => ['bool', 'name'=>'string'],
'XMLWriter::startElementNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string'],
'XMLWriter::startPI' => ['bool', 'target'=>'string'],
'XMLWriter::text' => ['bool', 'content'=>'string'],
'XMLWriter::writeAttribute' => ['bool', 'name'=>'string', 'value'=>'string'],
'XMLWriter::writeAttributeNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string', 'content'=>'string'],
'XMLWriter::writeCData' => ['bool', 'content'=>'string'],
'XMLWriter::writeComment' => ['bool', 'content'=>'string'],
'XMLWriter::writeDTD' => ['bool', 'name'=>'string', 'publicid='=>'string', 'systemid='=>'string', 'subset='=>'string'],
'XMLWriter::writeDTDAttlist' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDTDElement' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDTDEntity' => ['bool', 'name'=>'string', 'content'=>'string', 'pe'=>'bool', 'publicid'=>'string', 'sysid'=>'string', 'ndataid'=>'string'],
'XMLWriter::writeElement' => ['bool', 'name'=>'string', 'content='=>'?string'],
'XMLWriter::writeElementNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string', 'content='=>'?string'],
'XMLWriter::writePI' => ['bool', 'target'=>'string', 'content'=>'string'],
'XMLWriter::writeRaw' => ['bool', 'content'=>'string'],
'xmlwriter_end_attribute' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_cdata' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_comment' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_document' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_dtd' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_dtd_attlist' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_dtd_element' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_dtd_entity' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_element' => ['bool', 'writer'=>'resource'],
'xmlwriter_end_pi' => ['bool', 'writer'=>'resource'],
'xmlwriter_flush' => ['mixed', 'writer'=>'resource', 'empty='=>'bool'],
'xmlwriter_full_end_element' => ['bool', 'writer'=>'resource'],
'xmlwriter_open_memory' => ['resource'],
'xmlwriter_open_uri' => ['resource', 'uri'=>'string'],
'xmlwriter_output_memory' => ['string', 'writer'=>'resource', 'flush='=>'bool'],
'xmlwriter_set_indent' => ['bool', 'writer'=>'resource', 'enable'=>'bool'],
'xmlwriter_set_indent_string' => ['bool', 'writer'=>'resource', 'indentation'=>'string'],
'xmlwriter_start_attribute' => ['bool', 'writer'=>'resource', 'name'=>'string'],
'xmlwriter_start_attribute_ns' => ['bool', 'writer'=>'resource', 'prefix'=>'string', 'name'=>'string', 'namespace'=>'string'],
'xmlwriter_start_cdata' => ['bool', 'writer'=>'resource'],
'xmlwriter_start_comment' => ['bool', 'writer'=>'resource'],
'xmlwriter_start_document' => ['bool', 'writer'=>'resource', 'version='=>'string', 'encoding='=>'string', 'standalone='=>'string'],
'xmlwriter_start_dtd' => ['bool', 'writer'=>'resource', 'qualifiedName'=>'string', 'publicId='=>'string', 'systemId='=>'string'],
'xmlwriter_start_dtd_attlist' => ['bool', 'writer'=>'resource', 'name'=>'string'],
'xmlwriter_start_dtd_element' => ['bool', 'writer'=>'resource', 'qualifiedName'=>'string'],
'xmlwriter_start_dtd_entity' => ['bool', 'writer'=>'resource', 'name'=>'string', 'isParam'=>'bool'],
'xmlwriter_start_element' => ['bool', 'writer'=>'resource', 'name'=>'string'],
'xmlwriter_start_element_ns' => ['bool', 'writer'=>'resource', 'prefix'=>'string', 'name'=>'string', 'namespace'=>'string'],
'xmlwriter_start_pi' => ['bool', 'writer'=>'resource', 'target'=>'string'],
'xmlwriter_text' => ['bool', 'writer'=>'resource', 'content'=>'string'],
'xmlwriter_write_attribute' => ['bool', 'writer'=>'resource', 'name'=>'string', 'value'=>'string'],
'xmlwriter_write_attribute_ns' => ['bool', 'writer'=>'resource', 'prefix'=>'string', 'name'=>'string', 'namespace'=>'string', 'value'=>'string'],
'xmlwriter_write_cdata' => ['bool', 'writer'=>'resource', 'content'=>'string'],
'xmlwriter_write_comment' => ['bool', 'writer'=>'resource', 'content'=>'string'],
'xmlwriter_write_dtd' => ['bool', 'writer'=>'resource', 'name'=>'string', 'publicId='=>'string', 'systemId='=>'string', 'content='=>'string'],
'xmlwriter_write_dtd_attlist' => ['bool', 'writer'=>'resource', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_element' => ['bool', 'writer'=>'resource', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_entity' => ['bool', 'writer'=>'resource', 'name'=>'string', 'content'=>'string', 'isParam'=>'bool', 'publicId'=>'string', 'systemId'=>'string', 'notationData'=>'string'],
'xmlwriter_write_element' => ['bool', 'writer'=>'resource', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_element_ns' => ['bool', 'writer'=>'resource', 'prefix'=>'string', 'name'=>'string', 'namespace'=>'string', 'content'=>'string'],
'xmlwriter_write_pi' => ['bool', 'writer'=>'resource', 'target'=>'string', 'content'=>'string'],
'xmlwriter_write_raw' => ['bool', 'writer'=>'resource', 'content'=>'string'],
'xpath_new_context' => ['XPathContext', 'dom_document'=>'DOMDocument'],
'xpath_register_ns' => ['bool', 'xpath_context'=>'xpathcontext', 'prefix'=>'string', 'uri'=>'string'],
'xpath_register_ns_auto' => ['bool', 'xpath_context'=>'xpathcontext', 'context_node='=>'object'],
'xptr_new_context' => ['XPathContext'],
'xsl_xsltprocessor_get_parameter' => ['string', 'namespace'=>'string', 'name'=>'string'],
'xsl_xsltprocessor_get_security_prefs' => ['int'],
'xsl_xsltprocessor_has_exslt_support' => ['bool'],
'xsl_xsltprocessor_register_php_functions' => ['', 'restrict'=>''],
'xsl_xsltprocessor_remove_parameter' => ['bool', 'namespace'=>'string', 'name'=>'string'],
'xsl_xsltprocessor_set_parameter' => ['bool', 'namespace'=>'string', 'name'=>'', 'value'=>'string'],
'xsl_xsltprocessor_set_profiling' => ['bool', 'filename'=>'string'],
'xsl_xsltprocessor_set_security_prefs' => ['int', 'securityprefs'=>'int'],
'xsl_xsltprocessor_transform_to_uri' => ['int', 'doc'=>'DOMDocument', 'uri'=>'string'],
'xsl_xsltprocessor_transform_to_xml' => ['string', 'doc'=>'DOMDocument'],
'xslt_backend_info' => ['string'],
'xslt_backend_name' => ['string'],
'xslt_backend_version' => ['string'],
'xslt_create' => ['resource'],
'xslt_errno' => ['int', 'xh'=>''],
'xslt_error' => ['string', 'xh'=>''],
'xslt_free' => ['', 'xh'=>''],
'xslt_getopt' => ['int', 'processor'=>''],
'xslt_process' => ['', 'xh'=>'', 'xmlcontainer'=>'string', 'xslcontainer'=>'string', 'resultcontainer='=>'string', 'arguments='=>'array', 'parameters='=>'array'],
'xslt_set_base' => ['', 'xh'=>'', 'uri'=>'string'],
'xslt_set_encoding' => ['', 'xh'=>'', 'encoding'=>'string'],
'xslt_set_error_handler' => ['', 'xh'=>'', 'handler'=>''],
'xslt_set_log' => ['', 'xh'=>'', 'log='=>''],
'xslt_set_object' => ['bool', 'processor'=>'', 'object'=>'object'],
'xslt_set_sax_handler' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_set_sax_handlers' => ['', 'processor'=>'', 'handlers'=>'array'],
'xslt_set_scheme_handler' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_set_scheme_handlers' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_setopt' => ['', 'processor'=>'', 'newmask'=>'int'],
'XSLTProcessor::getParameter' => ['string|false', 'namespace'=>'string', 'name'=>'string'],
'XsltProcessor::getSecurityPrefs' => ['int'],
'XSLTProcessor::hasExsltSupport' => ['bool'],
'XSLTProcessor::importStylesheet' => ['bool', 'stylesheet'=>'object'],
'XSLTProcessor::registerPHPFunctions' => ['void', 'functions='=>'mixed'],
'XSLTProcessor::removeParameter' => ['bool', 'namespace'=>'string', 'name'=>'string'],
'XSLTProcessor::setParameter' => ['bool', 'namespace'=>'string', 'name'=>'string', 'value'=>'string'],
'XSLTProcessor::setParameter\'1' => ['bool', 'namespace'=>'string', 'options'=>'array'],
'XSLTProcessor::setProfiling' => ['bool', 'filename'=>'string'],
'XsltProcessor::setSecurityPrefs' => ['int', 'preferences'=>'int'],
'XSLTProcessor::transformToDoc' => ['DOMDocument|false', 'document'=>'DOMNode'],
'XSLTProcessor::transformToURI' => ['int', 'document'=>'DOMDocument', 'uri'=>'string'],
'XSLTProcessor::transformToXML' => ['string|false', 'document'=>'DOMDocument'],
'yac::__construct' => ['void', 'prefix='=>'string'],
'yac::__get' => ['mixed', 'key'=>'string'],
'yac::__set' => ['mixed', 'key'=>'string', 'value'=>'mixed'],
'yac::delete' => ['bool', 'keys'=>'string|array', 'ttl='=>'int'],
'yac::dump' => ['mixed', 'num'=>'int'],
'yac::flush' => ['bool'],
'yac::get' => ['mixed', 'key'=>'string|array', 'cas='=>'int'],
'yac::info' => ['array'],
'Yaconf::get' => ['mixed', 'name'=>'string', 'default_value='=>'mixed'],
'Yaconf::has' => ['bool', 'name'=>'string'],
'Yaf\Action_Abstract::__clone' => ['void'],
'Yaf\Action_Abstract::__construct' => ['void', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract', 'view'=>'Yaf\View_Interface', 'invokeArgs='=>'?array'],
'Yaf\Action_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::execute' => ['mixed'],
'Yaf\Action_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::getController' => ['Yaf\Controller_Abstract'],
'Yaf\Action_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf\Action_Abstract::getInvokeArgs' => ['array'],
'Yaf\Action_Abstract::getModuleName' => ['string'],
'Yaf\Action_Abstract::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Action_Abstract::getResponse' => ['Yaf\Response_Abstract'],
'Yaf\Action_Abstract::getView' => ['Yaf\View_Interface'],
'Yaf\Action_Abstract::getViewpath' => ['string'],
'Yaf\Action_Abstract::init' => [''],
'Yaf\Action_Abstract::initView' => ['Yaf\Response_Abstract', 'options='=>'?array'],
'Yaf\Action_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf\Action_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf\Application::__clone' => ['void'],
'Yaf\Application::__construct' => ['void', 'config'=>'array|string', 'envrion='=>'string'],
'Yaf\Application::__destruct' => ['void'],
'Yaf\Application::__sleep' => ['string[]'],
'Yaf\Application::__wakeup' => ['void'],
'Yaf\Application::app' => ['?Yaf\Application'],
'Yaf\Application::bootstrap' => ['Yaf\Application', 'bootstrap='=>'?Yaf\Bootstrap_Abstract'],
'Yaf\Application::clearLastError' => ['void'],
'Yaf\Application::environ' => ['string'],
'Yaf\Application::execute' => ['void', 'entry'=>'callable', '_='=>'string'],
'Yaf\Application::getAppDirectory' => ['string'],
'Yaf\Application::getConfig' => ['Yaf\Config_Abstract'],
'Yaf\Application::getDispatcher' => ['Yaf\Dispatcher'],
'Yaf\Application::getLastErrorMsg' => ['string'],
'Yaf\Application::getLastErrorNo' => ['int'],
'Yaf\Application::getModules' => ['array'],
'Yaf\Application::run' => ['void'],
'Yaf\Application::setAppDirectory' => ['Yaf\Application', 'directory'=>'string'],
'Yaf\Config\Ini::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf\Config\Ini::__get' => ['', 'name='=>'mixed'],
'Yaf\Config\Ini::__isset' => ['', 'name'=>'string'],
'Yaf\Config\Ini::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Config\Ini::count' => ['int'],
'Yaf\Config\Ini::current' => ['mixed'],
'Yaf\Config\Ini::get' => ['mixed', 'name='=>'mixed'],
'Yaf\Config\Ini::key' => ['int|string'],
'Yaf\Config\Ini::next' => ['void'],
'Yaf\Config\Ini::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Config\Ini::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Config\Ini::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Config\Ini::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Config\Ini::readonly' => ['bool'],
'Yaf\Config\Ini::rewind' => ['void'],
'Yaf\Config\Ini::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config\Ini::toArray' => ['array'],
'Yaf\Config\Ini::valid' => ['bool'],
'Yaf\Config\Simple::__construct' => ['void', 'array'=>'array', 'readonly='=>'string'],
'Yaf\Config\Simple::__get' => ['', 'name='=>'mixed'],
'Yaf\Config\Simple::__isset' => ['', 'name'=>'string'],
'Yaf\Config\Simple::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Config\Simple::count' => ['int'],
'Yaf\Config\Simple::current' => ['mixed'],
'Yaf\Config\Simple::get' => ['mixed', 'name='=>'mixed'],
'Yaf\Config\Simple::key' => ['int|string'],
'Yaf\Config\Simple::next' => ['void'],
'Yaf\Config\Simple::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Config\Simple::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Config\Simple::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Config\Simple::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Config\Simple::readonly' => ['bool'],
'Yaf\Config\Simple::rewind' => ['void'],
'Yaf\Config\Simple::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config\Simple::toArray' => ['array'],
'Yaf\Config\Simple::valid' => ['bool'],
'Yaf\Config_Abstract::__construct' => ['void'],
'Yaf\Config_Abstract::get' => ['mixed', 'name='=>'string'],
'Yaf\Config_Abstract::readonly' => ['bool'],
'Yaf\Config_Abstract::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config_Abstract::toArray' => ['array'],
'Yaf\Controller_Abstract::__clone' => ['void'],
'Yaf\Controller_Abstract::__construct' => ['void', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract', 'view'=>'Yaf\View_Interface', 'invokeArgs='=>'?array'],
'Yaf\Controller_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf\Controller_Abstract::getInvokeArgs' => ['array'],
'Yaf\Controller_Abstract::getModuleName' => ['string'],
'Yaf\Controller_Abstract::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Controller_Abstract::getResponse' => ['Yaf\Response_Abstract'],
'Yaf\Controller_Abstract::getView' => ['Yaf\View_Interface'],
'Yaf\Controller_Abstract::getViewpath' => ['string'],
'Yaf\Controller_Abstract::init' => [''],
'Yaf\Controller_Abstract::initView' => ['Yaf\Response_Abstract', 'options='=>'?array'],
'Yaf\Controller_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf\Controller_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf\Dispatcher::__clone' => ['void'],
'Yaf\Dispatcher::__construct' => ['void'],
'Yaf\Dispatcher::__sleep' => ['list<string>'],
'Yaf\Dispatcher::__wakeup' => ['void'],
'Yaf\Dispatcher::autoRender' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::catchException' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::disableView' => ['bool'],
'Yaf\Dispatcher::dispatch' => ['Yaf\Response_Abstract', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Dispatcher::enableView' => ['Yaf\Dispatcher'],
'Yaf\Dispatcher::flushInstantly' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::getApplication' => ['Yaf\Application'],
'Yaf\Dispatcher::getInstance' => ['Yaf\Dispatcher'],
'Yaf\Dispatcher::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Dispatcher::getRouter' => ['Yaf\Router'],
'Yaf\Dispatcher::initView' => ['Yaf\View_Interface', 'templates_dir'=>'string', 'options='=>'?array'],
'Yaf\Dispatcher::registerPlugin' => ['Yaf\Dispatcher', 'plugin'=>'Yaf\Plugin_Abstract'],
'Yaf\Dispatcher::returnResponse' => ['Yaf\Dispatcher', 'flag'=>'bool'],
'Yaf\Dispatcher::setDefaultAction' => ['Yaf\Dispatcher', 'action'=>'string'],
'Yaf\Dispatcher::setDefaultController' => ['Yaf\Dispatcher', 'controller'=>'string'],
'Yaf\Dispatcher::setDefaultModule' => ['Yaf\Dispatcher', 'module'=>'string'],
'Yaf\Dispatcher::setErrorHandler' => ['Yaf\Dispatcher', 'callback'=>'callable', 'error_types'=>'int'],
'Yaf\Dispatcher::setRequest' => ['Yaf\Dispatcher', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Dispatcher::setView' => ['Yaf\Dispatcher', 'view'=>'Yaf\View_Interface'],
'Yaf\Dispatcher::throwException' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Loader::__clone' => ['void'],
'Yaf\Loader::__construct' => ['void'],
'Yaf\Loader::__sleep' => ['list<string>'],
'Yaf\Loader::__wakeup' => ['void'],
'Yaf\Loader::autoload' => ['bool', 'class_name'=>'string'],
'Yaf\Loader::clearLocalNamespace' => [''],
'Yaf\Loader::getInstance' => ['Yaf\Loader', 'local_library_path='=>'string', 'global_library_path='=>'string'],
'Yaf\Loader::getLibraryPath' => ['string', 'is_global='=>'bool'],
'Yaf\Loader::getLocalNamespace' => ['string'],
'Yaf\Loader::import' => ['bool', 'file'=>'string'],
'Yaf\Loader::isLocalName' => ['bool', 'class_name'=>'string'],
'Yaf\Loader::registerLocalNamespace' => ['bool', 'name_prefix'=>'string|string[]'],
'Yaf\Loader::setLibraryPath' => ['Yaf\Loader', 'directory'=>'string', 'global='=>'bool'],
'Yaf\Plugin_Abstract::dispatchLoopShutdown' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::dispatchLoopStartup' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::postDispatch' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::preDispatch' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::preResponse' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::routerShutdown' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::routerStartup' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Registry::__clone' => ['void'],
'Yaf\Registry::__construct' => ['void'],
'Yaf\Registry::del' => ['bool|void', 'name'=>'string'],
'Yaf\Registry::get' => ['mixed', 'name'=>'string'],
'Yaf\Registry::has' => ['bool', 'name'=>'string'],
'Yaf\Registry::set' => ['bool', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Request\Http::__clone' => ['void'],
'Yaf\Request\Http::__construct' => ['void', 'request_uri'=>'string', 'base_uri'=>'string'],
'Yaf\Request\Http::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf\Request\Http::getActionName' => ['string'],
'Yaf\Request\Http::getBaseUri' => ['string'],
'Yaf\Request\Http::getControllerName' => ['string'],
'Yaf\Request\Http::getCookie' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getException' => ['Yaf\Exception'],
'Yaf\Request\Http::getFiles' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getLanguage' => ['string'],
'Yaf\Request\Http::getMethod' => ['string'],
'Yaf\Request\Http::getModuleName' => ['string'],
'Yaf\Request\Http::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getParams' => ['array'],
'Yaf\Request\Http::getPost' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getQuery' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getRequest' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getRequestUri' => ['string'],
'Yaf\Request\Http::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::isCli' => ['bool'],
'Yaf\Request\Http::isDispatched' => ['bool'],
'Yaf\Request\Http::isGet' => ['bool'],
'Yaf\Request\Http::isHead' => ['bool'],
'Yaf\Request\Http::isOptions' => ['bool'],
'Yaf\Request\Http::isPost' => ['bool'],
'Yaf\Request\Http::isPut' => ['bool'],
'Yaf\Request\Http::isRouted' => ['bool'],
'Yaf\Request\Http::isXmlHttpRequest' => ['bool'],
'Yaf\Request\Http::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request\Http::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request\Http::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request\Http::setDispatched' => ['bool'],
'Yaf\Request\Http::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request\Http::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request\Http::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request\Http::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Request\Simple::__clone' => ['void'],
'Yaf\Request\Simple::__construct' => ['void', 'method'=>'string', 'controller'=>'string', 'action'=>'string', 'params='=>'string'],
'Yaf\Request\Simple::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getActionName' => ['string'],
'Yaf\Request\Simple::getBaseUri' => ['string'],
'Yaf\Request\Simple::getControllerName' => ['string'],
'Yaf\Request\Simple::getCookie' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::getException' => ['Yaf\Exception'],
'Yaf\Request\Simple::getFiles' => ['array', 'name='=>'mixed', 'default='=>'null'],
'Yaf\Request\Simple::getLanguage' => ['string'],
'Yaf\Request\Simple::getMethod' => ['string'],
'Yaf\Request\Simple::getModuleName' => ['string'],
'Yaf\Request\Simple::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::getParams' => ['array'],
'Yaf\Request\Simple::getPost' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getQuery' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getRequest' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getRequestUri' => ['string'],
'Yaf\Request\Simple::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::isCli' => ['bool'],
'Yaf\Request\Simple::isDispatched' => ['bool'],
'Yaf\Request\Simple::isGet' => ['bool'],
'Yaf\Request\Simple::isHead' => ['bool'],
'Yaf\Request\Simple::isOptions' => ['bool'],
'Yaf\Request\Simple::isPost' => ['bool'],
'Yaf\Request\Simple::isPut' => ['bool'],
'Yaf\Request\Simple::isRouted' => ['bool'],
'Yaf\Request\Simple::isXmlHttpRequest' => ['bool'],
'Yaf\Request\Simple::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request\Simple::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request\Simple::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request\Simple::setDispatched' => ['bool'],
'Yaf\Request\Simple::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request\Simple::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request\Simple::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request\Simple::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Request_Abstract::getActionName' => ['string'],
'Yaf\Request_Abstract::getBaseUri' => ['string'],
'Yaf\Request_Abstract::getControllerName' => ['string'],
'Yaf\Request_Abstract::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::getException' => ['Yaf\Exception'],
'Yaf\Request_Abstract::getLanguage' => ['string'],
'Yaf\Request_Abstract::getMethod' => ['string'],
'Yaf\Request_Abstract::getModuleName' => ['string'],
'Yaf\Request_Abstract::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::getParams' => ['array'],
'Yaf\Request_Abstract::getRequestUri' => ['string'],
'Yaf\Request_Abstract::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::isCli' => ['bool'],
'Yaf\Request_Abstract::isDispatched' => ['bool'],
'Yaf\Request_Abstract::isGet' => ['bool'],
'Yaf\Request_Abstract::isHead' => ['bool'],
'Yaf\Request_Abstract::isOptions' => ['bool'],
'Yaf\Request_Abstract::isPost' => ['bool'],
'Yaf\Request_Abstract::isPut' => ['bool'],
'Yaf\Request_Abstract::isRouted' => ['bool'],
'Yaf\Request_Abstract::isXmlHttpRequest' => ['bool'],
'Yaf\Request_Abstract::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request_Abstract::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request_Abstract::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request_Abstract::setDispatched' => ['bool'],
'Yaf\Request_Abstract::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request_Abstract::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request_Abstract::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request_Abstract::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Response\Cli::__clone' => ['void'],
'Yaf\Response\Cli::__construct' => ['void'],
'Yaf\Response\Cli::__destruct' => ['void'],
'Yaf\Response\Cli::__toString' => ['string'],
'Yaf\Response\Cli::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Cli::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response\Cli::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response\Cli::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Cli::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::__clone' => ['void'],
'Yaf\Response\Http::__construct' => ['void'],
'Yaf\Response\Http::__destruct' => ['void'],
'Yaf\Response\Http::__toString' => ['string'],
'Yaf\Response\Http::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response\Http::clearHeaders' => ['Yaf\Response_Abstract|false', 'name='=>'string'],
'Yaf\Response\Http::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response\Http::getHeader' => ['mixed', 'name='=>'string'],
'Yaf\Response\Http::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::response' => ['bool'],
'Yaf\Response\Http::setAllHeaders' => ['bool', 'headers'=>'array'],
'Yaf\Response\Http::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::setHeader' => ['bool', 'name'=>'string', 'value'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'Yaf\Response\Http::setRedirect' => ['bool', 'url'=>'string'],
'Yaf\Response_Abstract::__clone' => ['void'],
'Yaf\Response_Abstract::__construct' => ['void'],
'Yaf\Response_Abstract::__destruct' => ['void'],
'Yaf\Response_Abstract::__toString' => ['void'],
'Yaf\Response_Abstract::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response_Abstract::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response_Abstract::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response_Abstract::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response_Abstract::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Route\Map::__construct' => ['void', 'controller_prefer='=>'bool', 'delimiter='=>'string'],
'Yaf\Route\Map::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Map::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Regex::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'map='=>'?array', 'verify='=>'?array', 'reverse='=>'string'],
'Yaf\Route\Regex::addConfig' => ['Yaf\Router|bool', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Route\Regex::addRoute' => ['Yaf\Router|bool', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Route\Regex::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Regex::getCurrentRoute' => ['string'],
'Yaf\Route\Regex::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Route\Regex::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Route\Regex::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Rewrite::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'verify='=>'?array', 'reverse='=>'string'],
'Yaf\Route\Rewrite::addConfig' => ['Yaf\Router|bool', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Route\Rewrite::addRoute' => ['Yaf\Router|bool', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Route\Rewrite::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Rewrite::getCurrentRoute' => ['string'],
'Yaf\Route\Rewrite::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Route\Rewrite::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Route\Rewrite::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Simple::__construct' => ['void', 'module_name'=>'string', 'controller_name'=>'string', 'action_name'=>'string'],
'Yaf\Route\Simple::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Simple::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Supervar::__construct' => ['void', 'supervar_name'=>'string'],
'Yaf\Route\Supervar::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Supervar::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route_Interface::__construct' => ['Yaf\Route_Interface'],
'Yaf\Route_Interface::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route_Interface::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route_Static::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route_Static::match' => ['bool', 'uri'=>'string'],
'Yaf\Route_Static::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Router::__construct' => ['void'],
'Yaf\Router::addConfig' => ['Yaf\Router|false', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Router::addRoute' => ['Yaf\Router|false', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Router::getCurrentRoute' => ['string'],
'Yaf\Router::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Router::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Router::route' => ['Yaf\Router|false', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Session::__clone' => ['void'],
'Yaf\Session::__construct' => ['void'],
'Yaf\Session::__get' => ['void', 'name'=>''],
'Yaf\Session::__isset' => ['void', 'name'=>''],
'Yaf\Session::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Session::__sleep' => ['list<string>'],
'Yaf\Session::__unset' => ['void', 'name'=>''],
'Yaf\Session::__wakeup' => ['void'],
'Yaf\Session::count' => ['int'],
'Yaf\Session::current' => ['mixed'],
'Yaf\Session::del' => ['Yaf\Session|false', 'name'=>'string'],
'Yaf\Session::get' => ['mixed', 'name'=>'string'],
'Yaf\Session::getInstance' => ['Yaf\Session'],
'Yaf\Session::has' => ['bool', 'name'=>'string'],
'Yaf\Session::key' => ['int|string'],
'Yaf\Session::next' => ['void'],
'Yaf\Session::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Session::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Session::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Session::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Session::rewind' => ['void'],
'Yaf\Session::set' => ['Yaf\Session|false', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Session::start' => ['Yaf\Session'],
'Yaf\Session::valid' => ['bool'],
'Yaf\View\Simple::__construct' => ['void', 'template_dir'=>'string', 'options='=>'?array'],
'Yaf\View\Simple::__get' => ['mixed', 'name='=>'null'],
'Yaf\View\Simple::__isset' => ['', 'name'=>'string'],
'Yaf\View\Simple::__set' => ['void', 'name'=>'string', 'value='=>'mixed'],
'Yaf\View\Simple::assign' => ['Yaf\View\Simple', 'name'=>'array|string', 'value='=>'mixed'],
'Yaf\View\Simple::assignRef' => ['Yaf\View\Simple', 'name'=>'string', '&value'=>'mixed'],
'Yaf\View\Simple::clear' => ['Yaf\View\Simple', 'name='=>'string'],
'Yaf\View\Simple::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View\Simple::eval' => ['bool|void', 'tpl_str'=>'string', 'vars='=>'?array'],
'Yaf\View\Simple::getScriptPath' => ['string'],
'Yaf\View\Simple::render' => ['string|void', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View\Simple::setScriptPath' => ['Yaf\View\Simple', 'template_dir'=>'string'],
'Yaf\View_Interface::assign' => ['bool', 'name'=>'array|string', 'value'=>'mixed'],
'Yaf\View_Interface::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View_Interface::getScriptPath' => ['string'],
'Yaf\View_Interface::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View_Interface::setScriptPath' => ['void', 'template_dir'=>'string'],
'Yaf_Action_Abstract::__clone' => ['void'],
'Yaf_Action_Abstract::__construct' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract', 'view'=>'Yaf_View_Interface', 'invokeArgs='=>'?array'],
'Yaf_Action_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::execute' => ['mixed', 'arg='=>'mixed', '...args='=>'mixed'],
'Yaf_Action_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::getController' => ['Yaf_Controller_Abstract'],
'Yaf_Action_Abstract::getControllerName' => ['string'],
'Yaf_Action_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf_Action_Abstract::getInvokeArgs' => ['array'],
'Yaf_Action_Abstract::getModuleName' => ['string'],
'Yaf_Action_Abstract::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Action_Abstract::getResponse' => ['Yaf_Response_Abstract'],
'Yaf_Action_Abstract::getView' => ['Yaf_View_Interface'],
'Yaf_Action_Abstract::getViewpath' => ['string'],
'Yaf_Action_Abstract::init' => [''],
'Yaf_Action_Abstract::initView' => ['Yaf_Response_Abstract', 'options='=>'?array'],
'Yaf_Action_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf_Action_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf_Application::__clone' => ['void'],
'Yaf_Application::__construct' => ['void', 'config'=>'mixed', 'envrion='=>'string'],
'Yaf_Application::__destruct' => ['void'],
'Yaf_Application::__sleep' => ['list<string>'],
'Yaf_Application::__wakeup' => ['void'],
'Yaf_Application::app' => ['?Yaf_Application'],
'Yaf_Application::bootstrap' => ['Yaf_Application', 'bootstrap='=>'Yaf_Bootstrap_Abstract'],
'Yaf_Application::clearLastError' => ['Yaf_Application'],
'Yaf_Application::environ' => ['string'],
'Yaf_Application::execute' => ['void', 'entry'=>'callable', '...args'=>'string'],
'Yaf_Application::getAppDirectory' => ['Yaf_Application'],
'Yaf_Application::getConfig' => ['Yaf_Config_Abstract'],
'Yaf_Application::getDispatcher' => ['Yaf_Dispatcher'],
'Yaf_Application::getLastErrorMsg' => ['string'],
'Yaf_Application::getLastErrorNo' => ['int'],
'Yaf_Application::getModules' => ['array'],
'Yaf_Application::run' => ['void'],
'Yaf_Application::setAppDirectory' => ['Yaf_Application', 'directory'=>'string'],
'Yaf_Config_Abstract::__construct' => ['void'],
'Yaf_Config_Abstract::get' => ['mixed', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Abstract::readonly' => ['bool'],
'Yaf_Config_Abstract::set' => ['Yaf_Config_Abstract'],
'Yaf_Config_Abstract::toArray' => ['array'],
'Yaf_Config_Ini::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf_Config_Ini::__get' => ['void', 'name='=>'string'],
'Yaf_Config_Ini::__isset' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::__set' => ['void', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Ini::count' => ['void'],
'Yaf_Config_Ini::current' => ['void'],
'Yaf_Config_Ini::get' => ['mixed', 'name='=>'mixed'],
'Yaf_Config_Ini::key' => ['void'],
'Yaf_Config_Ini::next' => ['void'],
'Yaf_Config_Ini::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Ini::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::readonly' => ['void'],
'Yaf_Config_Ini::rewind' => ['void'],
'Yaf_Config_Ini::set' => ['Yaf_Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Ini::toArray' => ['array'],
'Yaf_Config_Ini::valid' => ['void'],
'Yaf_Config_Simple::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf_Config_Simple::__get' => ['void', 'name='=>'string'],
'Yaf_Config_Simple::__isset' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::__set' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Simple::count' => ['void'],
'Yaf_Config_Simple::current' => ['void'],
'Yaf_Config_Simple::get' => ['mixed', 'name='=>'mixed'],
'Yaf_Config_Simple::key' => ['void'],
'Yaf_Config_Simple::next' => ['void'],
'Yaf_Config_Simple::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Simple::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::readonly' => ['void'],
'Yaf_Config_Simple::rewind' => ['void'],
'Yaf_Config_Simple::set' => ['Yaf_Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Simple::toArray' => ['array'],
'Yaf_Config_Simple::valid' => ['void'],
'Yaf_Controller_Abstract::__clone' => ['void'],
'Yaf_Controller_Abstract::__construct' => ['void'],
'Yaf_Controller_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward' => ['void', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward\'1' => ['void', 'controller'=>'string', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward\'2' => ['void', 'module'=>'string', 'controller'=>'string', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::getInvokeArg' => ['void', 'name'=>'string'],
'Yaf_Controller_Abstract::getInvokeArgs' => ['void'],
'Yaf_Controller_Abstract::getModuleName' => ['string'],
'Yaf_Controller_Abstract::getName' => ['string'],
'Yaf_Controller_Abstract::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Controller_Abstract::getResponse' => ['Yaf_Response_Abstract'],
'Yaf_Controller_Abstract::getView' => ['Yaf_View_Interface'],
'Yaf_Controller_Abstract::getViewpath' => ['void'],
'Yaf_Controller_Abstract::init' => ['void'],
'Yaf_Controller_Abstract::initView' => ['void', 'options='=>'array'],
'Yaf_Controller_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf_Controller_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::setViewpath' => ['void', 'view_directory'=>'string'],
'Yaf_Dispatcher::__clone' => ['void'],
'Yaf_Dispatcher::__construct' => ['void'],
'Yaf_Dispatcher::__sleep' => ['list<string>'],
'Yaf_Dispatcher::__wakeup' => ['void'],
'Yaf_Dispatcher::autoRender' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::catchException' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::disableView' => ['bool'],
'Yaf_Dispatcher::dispatch' => ['Yaf_Response_Abstract', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Dispatcher::enableView' => ['Yaf_Dispatcher'],
'Yaf_Dispatcher::flushInstantly' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::getApplication' => ['Yaf_Application'],
'Yaf_Dispatcher::getDefaultAction' => ['string'],
'Yaf_Dispatcher::getDefaultController' => ['string'],
'Yaf_Dispatcher::getDefaultModule' => ['string'],
'Yaf_Dispatcher::getInstance' => ['Yaf_Dispatcher'],
'Yaf_Dispatcher::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Dispatcher::getRouter' => ['Yaf_Router'],
'Yaf_Dispatcher::initView' => ['Yaf_View_Interface', 'templates_dir'=>'string', 'options='=>'array'],
'Yaf_Dispatcher::registerPlugin' => ['Yaf_Dispatcher', 'plugin'=>'Yaf_Plugin_Abstract'],
'Yaf_Dispatcher::returnResponse' => ['Yaf_Dispatcher', 'flag'=>'bool'],
'Yaf_Dispatcher::setDefaultAction' => ['Yaf_Dispatcher', 'action'=>'string'],
'Yaf_Dispatcher::setDefaultController' => ['Yaf_Dispatcher', 'controller'=>'string'],
'Yaf_Dispatcher::setDefaultModule' => ['Yaf_Dispatcher', 'module'=>'string'],
'Yaf_Dispatcher::setErrorHandler' => ['Yaf_Dispatcher', 'callback'=>'callable', 'error_types'=>'int'],
'Yaf_Dispatcher::setRequest' => ['Yaf_Dispatcher', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Dispatcher::setView' => ['Yaf_Dispatcher', 'view'=>'Yaf_View_Interface'],
'Yaf_Dispatcher::throwException' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Exception::__construct' => ['void'],
'Yaf_Exception::getPrevious' => ['void'],
'Yaf_Loader::__clone' => ['void'],
'Yaf_Loader::__construct' => ['void'],
'Yaf_Loader::__sleep' => ['list<string>'],
'Yaf_Loader::__wakeup' => ['void'],
'Yaf_Loader::autoload' => ['void'],
'Yaf_Loader::clearLocalNamespace' => ['void'],
'Yaf_Loader::getInstance' => ['Yaf_Loader'],
'Yaf_Loader::getLibraryPath' => ['Yaf_Loader', 'is_global='=>'bool'],
'Yaf_Loader::getLocalNamespace' => ['void'],
'Yaf_Loader::getNamespacePath' => ['string', 'namespaces'=>'string'],
'Yaf_Loader::import' => ['bool'],
'Yaf_Loader::isLocalName' => ['bool'],
'Yaf_Loader::registerLocalNamespace' => ['void', 'prefix'=>'mixed'],
'Yaf_Loader::registerNamespace' => ['bool', 'namespaces'=>'string|array', 'path='=>'string'],
'Yaf_Loader::setLibraryPath' => ['Yaf_Loader', 'directory'=>'string', 'is_global='=>'bool'],
'Yaf_Plugin_Abstract::dispatchLoopShutdown' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::dispatchLoopStartup' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::postDispatch' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::preDispatch' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::preResponse' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::routerShutdown' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::routerStartup' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Registry::__clone' => ['void'],
'Yaf_Registry::__construct' => ['void'],
'Yaf_Registry::del' => ['void', 'name'=>'string'],
'Yaf_Registry::get' => ['mixed', 'name'=>'string'],
'Yaf_Registry::has' => ['bool', 'name'=>'string'],
'Yaf_Registry::set' => ['bool', 'name'=>'string', 'value'=>'string'],
'Yaf_Request_Abstract::clearParams' => ['bool'],
'Yaf_Request_Abstract::getActionName' => ['void'],
'Yaf_Request_Abstract::getBaseUri' => ['void'],
'Yaf_Request_Abstract::getControllerName' => ['void'],
'Yaf_Request_Abstract::getEnv' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::getException' => ['void'],
'Yaf_Request_Abstract::getLanguage' => ['void'],
'Yaf_Request_Abstract::getMethod' => ['void'],
'Yaf_Request_Abstract::getModuleName' => ['void'],
'Yaf_Request_Abstract::getParam' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::getParams' => ['void'],
'Yaf_Request_Abstract::getRequestUri' => ['void'],
'Yaf_Request_Abstract::getServer' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::isCli' => ['void'],
'Yaf_Request_Abstract::isDispatched' => ['void'],
'Yaf_Request_Abstract::isGet' => ['void'],
'Yaf_Request_Abstract::isHead' => ['void'],
'Yaf_Request_Abstract::isOptions' => ['void'],
'Yaf_Request_Abstract::isPost' => ['void'],
'Yaf_Request_Abstract::isPut' => ['void'],
'Yaf_Request_Abstract::isRouted' => ['void'],
'Yaf_Request_Abstract::isXmlHttpRequest' => ['void'],
'Yaf_Request_Abstract::setActionName' => ['void', 'action'=>'string'],
'Yaf_Request_Abstract::setBaseUri' => ['bool', 'uir'=>'string'],
'Yaf_Request_Abstract::setControllerName' => ['void', 'controller'=>'string'],
'Yaf_Request_Abstract::setDispatched' => ['void'],
'Yaf_Request_Abstract::setModuleName' => ['void', 'module'=>'string'],
'Yaf_Request_Abstract::setParam' => ['void', 'name'=>'string', 'value='=>'string'],
'Yaf_Request_Abstract::setRequestUri' => ['void', 'uir'=>'string'],
'Yaf_Request_Abstract::setRouted' => ['void', 'flag='=>'string'],
'Yaf_Request_Http::__clone' => ['void'],
'Yaf_Request_Http::__construct' => ['void'],
'Yaf_Request_Http::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getActionName' => ['string'],
'Yaf_Request_Http::getBaseUri' => ['string'],
'Yaf_Request_Http::getControllerName' => ['string'],
'Yaf_Request_Http::getCookie' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::getException' => ['Yaf_Exception'],
'Yaf_Request_Http::getFiles' => ['void'],
'Yaf_Request_Http::getLanguage' => ['string'],
'Yaf_Request_Http::getMethod' => ['string'],
'Yaf_Request_Http::getModuleName' => ['string'],
'Yaf_Request_Http::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::getParams' => ['array'],
'Yaf_Request_Http::getPost' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getQuery' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getRaw' => ['mixed'],
'Yaf_Request_Http::getRequest' => ['void'],
'Yaf_Request_Http::getRequestUri' => ['string'],
'Yaf_Request_Http::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::isCli' => ['bool'],
'Yaf_Request_Http::isDispatched' => ['bool'],
'Yaf_Request_Http::isGet' => ['bool'],
'Yaf_Request_Http::isHead' => ['bool'],
'Yaf_Request_Http::isOptions' => ['bool'],
'Yaf_Request_Http::isPost' => ['bool'],
'Yaf_Request_Http::isPut' => ['bool'],
'Yaf_Request_Http::isRouted' => ['bool'],
'Yaf_Request_Http::isXmlHttpRequest' => ['bool'],
'Yaf_Request_Http::setActionName' => ['Yaf_Request_Abstract|bool', 'action'=>'string'],
'Yaf_Request_Http::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf_Request_Http::setControllerName' => ['Yaf_Request_Abstract|bool', 'controller'=>'string'],
'Yaf_Request_Http::setDispatched' => ['bool'],
'Yaf_Request_Http::setModuleName' => ['Yaf_Request_Abstract|bool', 'module'=>'string'],
'Yaf_Request_Http::setParam' => ['Yaf_Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf_Request_Http::setRequestUri' => ['', 'uri'=>'string'],
'Yaf_Request_Http::setRouted' => ['Yaf_Request_Abstract|bool'],
'Yaf_Request_Simple::__clone' => ['void'],
'Yaf_Request_Simple::__construct' => ['void'],
'Yaf_Request_Simple::get' => ['void'],
'Yaf_Request_Simple::getActionName' => ['string'],
'Yaf_Request_Simple::getBaseUri' => ['string'],
'Yaf_Request_Simple::getControllerName' => ['string'],
'Yaf_Request_Simple::getCookie' => ['void'],
'Yaf_Request_Simple::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::getException' => ['Yaf_Exception'],
'Yaf_Request_Simple::getFiles' => ['void'],
'Yaf_Request_Simple::getLanguage' => ['string'],
'Yaf_Request_Simple::getMethod' => ['string'],
'Yaf_Request_Simple::getModuleName' => ['string'],
'Yaf_Request_Simple::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::getParams' => ['array'],
'Yaf_Request_Simple::getPost' => ['void'],
'Yaf_Request_Simple::getQuery' => ['void'],
'Yaf_Request_Simple::getRequest' => ['void'],
'Yaf_Request_Simple::getRequestUri' => ['string'],
'Yaf_Request_Simple::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::isCli' => ['bool'],
'Yaf_Request_Simple::isDispatched' => ['bool'],
'Yaf_Request_Simple::isGet' => ['bool'],
'Yaf_Request_Simple::isHead' => ['bool'],
'Yaf_Request_Simple::isOptions' => ['bool'],
'Yaf_Request_Simple::isPost' => ['bool'],
'Yaf_Request_Simple::isPut' => ['bool'],
'Yaf_Request_Simple::isRouted' => ['bool'],
'Yaf_Request_Simple::isXmlHttpRequest' => ['void'],
'Yaf_Request_Simple::setActionName' => ['Yaf_Request_Abstract|bool', 'action'=>'string'],
'Yaf_Request_Simple::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf_Request_Simple::setControllerName' => ['Yaf_Request_Abstract|bool', 'controller'=>'string'],
'Yaf_Request_Simple::setDispatched' => ['bool'],
'Yaf_Request_Simple::setModuleName' => ['Yaf_Request_Abstract|bool', 'module'=>'string'],
'Yaf_Request_Simple::setParam' => ['Yaf_Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf_Request_Simple::setRequestUri' => ['', 'uri'=>'string'],
'Yaf_Request_Simple::setRouted' => ['Yaf_Request_Abstract|bool'],
'Yaf_Response_Abstract::__clone' => ['void'],
'Yaf_Response_Abstract::__construct' => ['void'],
'Yaf_Response_Abstract::__destruct' => ['void'],
'Yaf_Response_Abstract::__toString' => ['string'],
'Yaf_Response_Abstract::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Abstract::clearHeaders' => ['void'],
'Yaf_Response_Abstract::getBody' => ['mixed', 'key='=>'string'],
'Yaf_Response_Abstract::getHeader' => ['void'],
'Yaf_Response_Abstract::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::response' => ['void'],
'Yaf_Response_Abstract::setAllHeaders' => ['void'],
'Yaf_Response_Abstract::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::setHeader' => ['void'],
'Yaf_Response_Abstract::setRedirect' => ['void'],
'Yaf_Response_Cli::__clone' => ['void'],
'Yaf_Response_Cli::__construct' => ['void'],
'Yaf_Response_Cli::__destruct' => ['void'],
'Yaf_Response_Cli::__toString' => ['string'],
'Yaf_Response_Cli::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Cli::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Cli::getBody' => ['mixed', 'key='=>'?string'],
'Yaf_Response_Cli::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Cli::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::__clone' => ['void'],
'Yaf_Response_Http::__construct' => ['void'],
'Yaf_Response_Http::__destruct' => ['void'],
'Yaf_Response_Http::__toString' => ['string'],
'Yaf_Response_Http::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Http::clearHeaders' => ['Yaf_Response_Abstract|false', 'name='=>'string'],
'Yaf_Response_Http::getBody' => ['mixed', 'key='=>'?string'],
'Yaf_Response_Http::getHeader' => ['mixed', 'name='=>'string'],
'Yaf_Response_Http::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::response' => ['bool'],
'Yaf_Response_Http::setAllHeaders' => ['bool', 'headers'=>'array'],
'Yaf_Response_Http::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::setHeader' => ['bool', 'name'=>'string', 'value'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'Yaf_Response_Http::setRedirect' => ['bool', 'url'=>'string'],
'Yaf_Route_Interface::__construct' => ['void'],
'Yaf_Route_Interface::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Interface::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Map::__construct' => ['void', 'controller_prefer='=>'string', 'delimiter='=>'string'],
'Yaf_Route_Map::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Map::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Regex::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'map='=>'array', 'verify='=>'array', 'reverse='=>'string'],
'Yaf_Route_Regex::addConfig' => ['Yaf_Router|bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Route_Regex::addRoute' => ['Yaf_Router|bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Route_Regex::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Regex::getCurrentRoute' => ['string'],
'Yaf_Route_Regex::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Route_Regex::getRoutes' => ['Yaf_Route_Interface[]'],
'Yaf_Route_Regex::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Rewrite::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'verify='=>'array'],
'Yaf_Route_Rewrite::addConfig' => ['Yaf_Router|bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Route_Rewrite::addRoute' => ['Yaf_Router|bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Route_Rewrite::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Rewrite::getCurrentRoute' => ['string'],
'Yaf_Route_Rewrite::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Route_Rewrite::getRoutes' => ['Yaf_Route_Interface[]'],
'Yaf_Route_Rewrite::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Simple::__construct' => ['void', 'module_name'=>'string', 'controller_name'=>'string', 'action_name'=>'string'],
'Yaf_Route_Simple::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Simple::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Static::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Static::match' => ['void', 'uri'=>'string'],
'Yaf_Route_Static::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Supervar::__construct' => ['void', 'supervar_name'=>'string'],
'Yaf_Route_Supervar::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Supervar::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Router::__construct' => ['void'],
'Yaf_Router::addConfig' => ['bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Router::addRoute' => ['bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Router::getCurrentRoute' => ['string'],
'Yaf_Router::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Router::getRoutes' => ['mixed'],
'Yaf_Router::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Session::__clone' => ['void'],
'Yaf_Session::__construct' => ['void'],
'Yaf_Session::__get' => ['void', 'name'=>'string'],
'Yaf_Session::__isset' => ['void', 'name'=>'string'],
'Yaf_Session::__set' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Session::__sleep' => ['list<string>'],
'Yaf_Session::__unset' => ['void', 'name'=>'string'],
'Yaf_Session::__wakeup' => ['void'],
'Yaf_Session::count' => ['void'],
'Yaf_Session::current' => ['void'],
'Yaf_Session::del' => ['void', 'name'=>'string'],
'Yaf_Session::get' => ['mixed', 'name'=>'string'],
'Yaf_Session::getInstance' => ['void'],
'Yaf_Session::has' => ['void', 'name'=>'string'],
'Yaf_Session::key' => ['void'],
'Yaf_Session::next' => ['void'],
'Yaf_Session::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Session::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Session::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Session::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Session::rewind' => ['void'],
'Yaf_Session::set' => ['Yaf_Session|bool', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Session::start' => ['void'],
'Yaf_Session::valid' => ['void'],
'Yaf_View_Interface::assign' => ['bool', 'name'=>'string', 'value='=>'string'],
'Yaf_View_Interface::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Interface::getScriptPath' => ['string'],
'Yaf_View_Interface::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Interface::setScriptPath' => ['void', 'template_dir'=>'string'],
'Yaf_View_Simple::__construct' => ['void', 'tempalte_dir'=>'string', 'options='=>'array'],
'Yaf_View_Simple::__get' => ['void', 'name='=>'string'],
'Yaf_View_Simple::__isset' => ['void', 'name'=>'string'],
'Yaf_View_Simple::__set' => ['void', 'name'=>'string', 'value'=>'mixed'],
'Yaf_View_Simple::assign' => ['bool', 'name'=>'string', 'value='=>'mixed'],
'Yaf_View_Simple::assignRef' => ['bool', 'name'=>'string', '&rw_value'=>'mixed'],
'Yaf_View_Simple::clear' => ['bool', 'name='=>'string'],
'Yaf_View_Simple::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::eval' => ['string', 'tpl_content'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::getScriptPath' => ['string'],
'Yaf_View_Simple::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::setScriptPath' => ['bool', 'template_dir'=>'string'],
'yaml_emit' => ['string', 'data'=>'mixed', 'encoding='=>'int', 'linebreak='=>'int'],
'yaml_emit_file' => ['bool', 'filename'=>'string', 'data'=>'mixed', 'encoding='=>'int', 'linebreak='=>'int'],
'yaml_parse' => ['mixed|false', 'input'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'yaml_parse_file' => ['mixed|false', 'filename'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'yaml_parse_url' => ['mixed|false', 'url'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'Yar_Client::__call' => ['void', 'method'=>'string', 'parameters'=>'array'],
'Yar_Client::__construct' => ['void', 'url'=>'string'],
'Yar_Client::setOpt' => ['Yar_Client|false', 'name'=>'int', 'value'=>'mixed'],
'Yar_Client_Exception::__clone' => ['void'],
'Yar_Client_Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'Yar_Client_Exception::__toString' => ['string'],
'Yar_Client_Exception::__wakeup' => ['void'],
'Yar_Client_Exception::getCode' => ['int'],
'Yar_Client_Exception::getFile' => ['string'],
'Yar_Client_Exception::getLine' => ['int'],
'Yar_Client_Exception::getMessage' => ['string'],
'Yar_Client_Exception::getPrevious' => ['?Exception|?Throwable'],
'Yar_Client_Exception::getTrace' => ['list<array<string,mixed>>'],
'Yar_Client_Exception::getTraceAsString' => ['string'],
'Yar_Client_Exception::getType' => ['string'],
'Yar_Concurrent_Client::call' => ['int', 'uri'=>'string', 'method'=>'string', 'parameters'=>'array', 'callback='=>'callable'],
'Yar_Concurrent_Client::loop' => ['bool', 'callback='=>'callable', 'error_callback='=>'callable'],
'Yar_Concurrent_Client::reset' => ['bool'],
'Yar_Server::__construct' => ['void', 'object'=>'Object'],
'Yar_Server::handle' => ['bool'],
'Yar_Server_Exception::__clone' => ['void'],
'Yar_Server_Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'Yar_Server_Exception::__toString' => ['string'],
'Yar_Server_Exception::__wakeup' => ['void'],
'Yar_Server_Exception::getCode' => ['int'],
'Yar_Server_Exception::getFile' => ['string'],
'Yar_Server_Exception::getLine' => ['int'],
'Yar_Server_Exception::getMessage' => ['string'],
'Yar_Server_Exception::getPrevious' => ['?Exception|?Throwable'],
'Yar_Server_Exception::getTrace' => ['list<array<string,mixed>>'],
'Yar_Server_Exception::getTraceAsString' => ['string'],
'Yar_Server_Exception::getType' => ['string'],
'yaz_addinfo' => ['string', 'id'=>'resource'],
'yaz_ccl_conf' => ['void', 'id'=>'resource', 'config'=>'array'],
'yaz_ccl_parse' => ['bool', 'id'=>'resource', 'query'=>'string', '&w_result'=>'array'],
'yaz_close' => ['bool', 'id'=>'resource'],
'yaz_connect' => ['mixed', 'zurl'=>'string', 'options='=>'mixed'],
'yaz_database' => ['bool', 'id'=>'resource', 'databases'=>'string'],
'yaz_element' => ['bool', 'id'=>'resource', 'elementset'=>'string'],
'yaz_errno' => ['int', 'id'=>'resource'],
'yaz_error' => ['string', 'id'=>'resource'],
'yaz_es' => ['void', 'id'=>'resource', 'type'=>'string', 'args'=>'array'],
'yaz_es_result' => ['array', 'id'=>'resource'],
'yaz_get_option' => ['string', 'id'=>'resource', 'name'=>'string'],
'yaz_hits' => ['int', 'id'=>'resource', 'searchresult='=>'array'],
'yaz_itemorder' => ['void', 'id'=>'resource', 'args'=>'array'],
'yaz_present' => ['bool', 'id'=>'resource'],
'yaz_range' => ['void', 'id'=>'resource', 'start'=>'int', 'number'=>'int'],
'yaz_record' => ['string', 'id'=>'resource', 'pos'=>'int', 'type'=>'string'],
'yaz_scan' => ['void', 'id'=>'resource', 'type'=>'string', 'startterm'=>'string', 'flags='=>'array'],
'yaz_scan_result' => ['array', 'id'=>'resource', 'result='=>'array'],
'yaz_schema' => ['void', 'id'=>'resource', 'schema'=>'string'],
'yaz_search' => ['bool', 'id'=>'resource', 'type'=>'string', 'query'=>'string'],
'yaz_set_option' => ['', 'id'=>'', 'name'=>'string', 'value'=>'string', 'options'=>'array'],
'yaz_sort' => ['void', 'id'=>'resource', 'criteria'=>'string'],
'yaz_syntax' => ['void', 'id'=>'resource', 'syntax'=>'string'],
'yaz_wait' => ['mixed', '&rw_options='=>'array'],
'yp_all' => ['void', 'domain'=>'string', 'map'=>'string', 'callback'=>'string'],
'yp_cat' => ['array', 'domain'=>'string', 'map'=>'string'],
'yp_err_string' => ['string', 'errorcode'=>'int'],
'yp_errno' => ['int'],
'yp_first' => ['array', 'domain'=>'string', 'map'=>'string'],
'yp_get_default_domain' => ['string'],
'yp_master' => ['string', 'domain'=>'string', 'map'=>'string'],
'yp_match' => ['string', 'domain'=>'string', 'map'=>'string', 'key'=>'string'],
'yp_next' => ['array', 'domain'=>'string', 'map'=>'string', 'key'=>'string'],
'yp_order' => ['int', 'domain'=>'string', 'map'=>'string'],
'zem_get_extension_info_by_id' => [''],
'zem_get_extension_info_by_name' => [''],
'zem_get_extensions_info' => [''],
'zem_get_license_info' => [''],
'zend_current_obfuscation_level' => ['int'],
'zend_disk_cache_clear' => ['bool', 'namespace='=>'mixed|string'],
'zend_disk_cache_delete' => ['mixed|null', 'key'=>'string'],
'zend_disk_cache_fetch' => ['mixed|null', 'key'=>'string'],
'zend_disk_cache_store' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int|mixed'],
'zend_get_id' => ['array', 'all_ids='=>'all_ids|false'],
'zend_is_configuration_changed' => [''],
'zend_loader_current_file' => ['string'],
'zend_loader_enabled' => ['bool'],
'zend_loader_file_encoded' => ['bool'],
'zend_loader_file_licensed' => ['array'],
'zend_loader_install_license' => ['bool', 'license_file'=>'string', 'override'=>'bool'],
'zend_logo_guid' => ['string'],
'zend_obfuscate_class_name' => ['string', 'class_name'=>'string'],
'zend_obfuscate_function_name' => ['string', 'function_name'=>'string'],
'zend_optimizer_version' => ['string'],
'zend_runtime_obfuscate' => ['void'],
'zend_send_buffer' => ['null|false', 'buffer'=>'string', 'mime_type='=>'string', 'custom_headers='=>'string'],
'zend_send_file' => ['null|false', 'filename'=>'string', 'mime_type='=>'string', 'custom_headers='=>'string'],
'zend_set_configuration_changed' => [''],
'zend_shm_cache_clear' => ['bool', 'namespace='=>'mixed|string'],
'zend_shm_cache_delete' => ['mixed|null', 'key'=>'string'],
'zend_shm_cache_fetch' => ['mixed|null', 'key'=>'string'],
'zend_shm_cache_store' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int|mixed'],
'zend_thread_id' => ['int'],
'zend_version' => ['string'],
'ZendAPI_Job::addJobToQueue' => ['int', 'jobqueue_url'=>'string', 'password'=>'string'],
'ZendAPI_Job::getApplicationID' => [''],
'ZendAPI_Job::getEndTime' => [''],
'ZendAPI_Job::getGlobalVariables' => [''],
'ZendAPI_Job::getHost' => [''],
'ZendAPI_Job::getID' => [''],
'ZendAPI_Job::getInterval' => [''],
'ZendAPI_Job::getJobDependency' => [''],
'ZendAPI_Job::getJobName' => [''],
'ZendAPI_Job::getJobPriority' => [''],
'ZendAPI_Job::getJobStatus' => ['int'],
'ZendAPI_Job::getLastPerformedStatus' => ['int'],
'ZendAPI_Job::getOutput' => ['An'],
'ZendAPI_Job::getPreserved' => [''],
'ZendAPI_Job::getProperties' => ['array'],
'ZendAPI_Job::getScheduledTime' => [''],
'ZendAPI_Job::getScript' => [''],
'ZendAPI_Job::getTimeToNextRepeat' => ['int'],
'ZendAPI_Job::getUserVariables' => [''],
'ZendAPI_Job::setApplicationID' => ['', 'app_id'=>''],
'ZendAPI_Job::setGlobalVariables' => ['', 'vars'=>''],
'ZendAPI_Job::setJobDependency' => ['', 'job_id'=>''],
'ZendAPI_Job::setJobName' => ['', 'name'=>''],
'ZendAPI_Job::setJobPriority' => ['', 'priority'=>'int'],
'ZendAPI_Job::setPreserved' => ['', 'preserved'=>''],
'ZendAPI_Job::setRecurrenceData' => ['', 'interval'=>'', 'end_time='=>'mixed'],
'ZendAPI_Job::setScheduledTime' => ['', 'timestamp'=>''],
'ZendAPI_Job::setScript' => ['', 'script'=>''],
'ZendAPI_Job::setUserVariables' => ['', 'vars'=>''],
'ZendAPI_Job::ZendAPI_Job' => ['Job', 'script'=>'script'],
'ZendAPI_Queue::addJob' => ['int', '&job'=>'Job'],
'ZendAPI_Queue::getAllApplicationIDs' => ['array'],
'ZendAPI_Queue::getAllhosts' => ['array'],
'ZendAPI_Queue::getHistoricJobs' => ['array', 'status'=>'int', 'start_time'=>'', 'end_time'=>'', 'index'=>'int', 'count'=>'int', '&total'=>'int'],
'ZendAPI_Queue::getJob' => ['Job', 'job_id'=>'int'],
'ZendAPI_Queue::getJobsInQueue' => ['array', 'filter_options='=>'array', 'max_jobs='=>'int', 'with_globals_and_output='=>'bool'],
'ZendAPI_Queue::getLastError' => ['string'],
'ZendAPI_Queue::getNumOfJobsInQueue' => ['int', 'filter_options='=>'array'],
'ZendAPI_Queue::getStatistics' => ['array'],
'ZendAPI_Queue::isScriptExists' => ['bool', 'path'=>'string'],
'ZendAPI_Queue::isSuspend' => ['bool'],
'ZendAPI_Queue::login' => ['bool', 'password'=>'string', 'application_id='=>'int'],
'ZendAPI_Queue::removeJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::requeueJob' => ['bool', 'job'=>'Job'],
'ZendAPI_Queue::resumeJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::resumeQueue' => ['bool'],
'ZendAPI_Queue::setMaxHistoryTime' => ['bool'],
'ZendAPI_Queue::suspendJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::suspendQueue' => ['bool'],
'ZendAPI_Queue::updateJob' => ['int', '&job'=>'Job'],
'ZendAPI_Queue::zendapi_queue' => ['ZendAPI_Queue', 'queue_url'=>'string'],
'zip_close' => ['void', 'zip'=>'resource'],
'zip_entry_close' => ['bool', 'zip_ent'=>'resource'],
'zip_entry_compressedsize' => ['int', 'zip_entry'=>'resource'],
'zip_entry_compressionmethod' => ['string', 'zip_entry'=>'resource'],
'zip_entry_filesize' => ['int', 'zip_entry'=>'resource'],
'zip_entry_name' => ['string', 'zip_entry'=>'resource'],
'zip_entry_open' => ['bool', 'zip_dp'=>'resource', 'zip_entry'=>'resource', 'mode='=>'string'],
'zip_entry_read' => ['string|false', 'zip_entry'=>'resource', 'len='=>'int'],
'zip_open' => ['resource|int|false', 'filename'=>'string'],
'zip_read' => ['resource', 'zip'=>'resource'],
'ZipArchive::addEmptyDir' => ['bool', 'dirname'=>'string'],
'ZipArchive::addFile' => ['bool', 'filepath'=>'string', 'entryname='=>'string', 'start='=>'int', 'length='=>'int'],
'ZipArchive::addFromString' => ['bool', 'entryname'=>'string', 'content'=>'string'],
'ZipArchive::addGlob' => ['bool', 'pattern'=>'string', 'flags='=>'int', 'options='=>'array'],
'ZipArchive::addPattern' => ['bool', 'pattern'=>'string', 'path='=>'string', 'options='=>'array'],
'ZipArchive::close' => ['bool'],
'ZipArchive::count' => ['int'],
'ZipArchive::createEmptyDir' => ['bool', 'dirname'=>'string'],
'ZipArchive::deleteIndex' => ['bool', 'index'=>'int'],
'ZipArchive::deleteName' => ['bool', 'name'=>'string'],
'ZipArchive::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string[]|string'],
'ZipArchive::getArchiveComment' => ['string|false', 'flags='=>'int'],
'ZipArchive::getCommentIndex' => ['string|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::getCommentName' => ['string|false', 'name'=>'string', 'flags='=>'int'],
'ZipArchive::getExternalAttributesIndex' => ['bool', 'index'=>'int', '&w_opsys'=>'int', '&w_attr'=>'int', 'flags='=>'int'],
'ZipArchive::getExternalAttributesName' => ['bool', 'name'=>'string', '&w_opsys'=>'int', '&w_attr'=>'int', 'flags='=>'int'],
'ZipArchive::getFromIndex' => ['string|false', 'index'=>'int', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::getFromName' => ['string|false', 'entryname'=>'string', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::getNameIndex' => ['string|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::getStatusString' => ['string|false'],
'ZipArchive::getStream' => ['resource|false', 'entryname'=>'string'],
'ZipArchive::isCompressionMethodSupported' => ['bool', 'method'=>'int', 'encode='=>'bool'],
'ZipArchive::isEncryptionMethodSupported' => ['bool', 'method'=>'int', 'encode='=>'bool'],
'ZipArchive::locateName' => ['int|false', 'filename'=>'string', 'flags='=>'int'],
'ZipArchive::open' => ['int|bool', 'source'=>'string', 'flags='=>'int'],
'ZipArchive::registerCancelCallback' => ['bool', 'callback'=>'callable'],
'ZipArchive::registerProgressCallback' => ['bool', 'rate'=>'float', 'callback'=>'callable'],
'ZipArchive::renameIndex' => ['bool', 'index'=>'int', 'new_name'=>'string'],
'ZipArchive::renameName' => ['bool', 'name'=>'string', 'new_name'=>'string'],
'ZipArchive::replaceFile' => ['bool', 'filename'=>'string', 'index'=>'int', 'start='=>'int', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::setArchiveComment' => ['bool', 'comment'=>'string'],
'ZipArchive::setCommentIndex' => ['bool', 'index'=>'int', 'comment'=>'string'],
'ZipArchive::setCommentName' => ['bool', 'name'=>'string', 'comment'=>'string'],
'ZipArchive::setCompressionIndex' => ['bool', 'index'=>'int', 'comp_method'=>'int', 'comp_flags='=>'int'],
'ZipArchive::setCompressionName' => ['bool', 'name'=>'string', 'comp_method'=>'int', 'comp_flags='=>'int'],
'ZipArchive::setEncryptionIndex' => ['bool', 'index'=>'int', 'method'=>'string', 'password='=>'string'],
'ZipArchive::setEncryptionName' => ['bool', 'name'=>'string', 'method'=>'int', 'password='=>'string'],
'ZipArchive::setExternalAttributesIndex' => ['bool', 'index'=>'int', 'opsys'=>'int', 'attr'=>'int', 'flags='=>'int'],
'ZipArchive::setExternalAttributesName' => ['bool', 'name'=>'string', 'opsys'=>'int', 'attr'=>'int', 'flags='=>'int'],
'ZipArchive::setMtimeIndex' => ['bool', 'index'=>'int', 'timestamp'=>'int', 'flags='=>'int'],
'ZipArchive::setMtimeName' => ['bool', 'name'=>'string', 'timestamp'=>'int', 'flags='=>'int'],
'ZipArchive::setPassword' => ['bool', 'password'=>'string'],
'ZipArchive::statIndex' => ['array|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::statName' => ['array|false', 'filename'=>'string', 'flags='=>'int'],
'ZipArchive::unchangeAll' => ['bool'],
'ZipArchive::unchangeArchive' => ['bool'],
'ZipArchive::unchangeIndex' => ['bool', 'index'=>'int'],
'ZipArchive::unchangeName' => ['bool', 'name'=>'string'],
'zlib_decode' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'zlib_encode' => ['string', 'data'=>'string', 'encoding'=>'int', 'level='=>'string|int'],
'zlib_get_coding_type' => ['string|false'],
'ZMQ::__construct' => ['void'],
'ZMQContext::__construct' => ['void', 'io_threads='=>'int', 'is_persistent='=>'bool'],
'ZMQContext::getOpt' => ['int|string', 'key'=>'string'],
'ZMQContext::getSocket' => ['ZMQSocket', 'type'=>'int', 'persistent_id='=>'string', 'on_new_socket='=>'callable'],
'ZMQContext::isPersistent' => ['bool'],
'ZMQContext::setOpt' => ['ZMQContext', 'key'=>'int', 'value'=>'mixed'],
'ZMQDevice::__construct' => ['void', 'frontend'=>'ZMQSocket', 'backend'=>'ZMQSocket', 'listener='=>'ZMQSocket'],
'ZMQDevice::getIdleTimeout' => ['ZMQDevice'],
'ZMQDevice::getTimerTimeout' => ['ZMQDevice'],
'ZMQDevice::run' => ['void'],
'ZMQDevice::setIdleCallback' => ['ZMQDevice', 'cb_func'=>'callable', 'timeout'=>'int', 'user_data='=>'mixed'],
'ZMQDevice::setIdleTimeout' => ['ZMQDevice', 'timeout'=>'int'],
'ZMQDevice::setTimerCallback' => ['ZMQDevice', 'cb_func'=>'callable', 'timeout'=>'int', 'user_data='=>'mixed'],
'ZMQDevice::setTimerTimeout' => ['ZMQDevice', 'timeout'=>'int'],
'ZMQPoll::add' => ['string', 'entry'=>'mixed', 'type'=>'int'],
'ZMQPoll::clear' => ['ZMQPoll'],
'ZMQPoll::count' => ['int'],
'ZMQPoll::getLastErrors' => ['array'],
'ZMQPoll::poll' => ['int', '&w_readable'=>'array', '&w_writable'=>'array', 'timeout='=>'int'],
'ZMQPoll::remove' => ['bool', 'item'=>'mixed'],
'ZMQSocket::__construct' => ['void', 'context'=>'ZMQContext', 'type'=>'int', 'persistent_id='=>'string', 'on_new_socket='=>'callable'],
'ZMQSocket::bind' => ['ZMQSocket', 'dsn'=>'string', 'force='=>'bool'],
'ZMQSocket::connect' => ['ZMQSocket', 'dsn'=>'string', 'force='=>'bool'],
'ZMQSocket::disconnect' => ['ZMQSocket', 'dsn'=>'string'],
'ZMQSocket::getEndpoints' => ['array'],
'ZMQSocket::getPersistentId' => ['?string'],
'ZMQSocket::getSocketType' => ['int'],
'ZMQSocket::getSockOpt' => ['int|string', 'key'=>'string'],
'ZMQSocket::isPersistent' => ['bool'],
'ZMQSocket::recv' => ['string', 'mode='=>'int'],
'ZMQSocket::recvMulti' => ['string[]', 'mode='=>'int'],
'ZMQSocket::send' => ['ZMQSocket', 'message'=>'array', 'mode='=>'int'],
'ZMQSocket::send\'1' => ['ZMQSocket', 'message'=>'string', 'mode='=>'int'],
'ZMQSocket::sendmulti' => ['ZMQSocket', 'message'=>'array', 'mode='=>'int'],
'ZMQSocket::setSockOpt' => ['ZMQSocket', 'key'=>'int', 'value'=>'mixed'],
'ZMQSocket::unbind' => ['ZMQSocket', 'dsn'=>'string'],
'Zookeeper::addAuth' => ['bool', 'scheme'=>'string', 'cert'=>'string', 'completion_cb='=>'callable'],
'Zookeeper::close' => ['void'],
'Zookeeper::connect' => ['void', 'host'=>'string', 'watcher_cb='=>'callable', 'recv_timeout='=>'int'],
'Zookeeper::create' => ['string', 'path'=>'string', 'value'=>'string', 'acls'=>'array', 'flags='=>'int'],
'Zookeeper::delete' => ['bool', 'path'=>'string', 'version='=>'int'],
'Zookeeper::exists' => ['bool', 'path'=>'string', 'watcher_cb='=>'callable'],
'Zookeeper::get' => ['string', 'path'=>'string', 'watcher_cb='=>'callable', 'stat='=>'array', 'max_size='=>'int'],
'Zookeeper::getAcl' => ['array', 'path'=>'string'],
'Zookeeper::getChildren' => ['array|false', 'path'=>'string', 'watcher_cb='=>'callable'],
'Zookeeper::getClientId' => ['int'],
'Zookeeper::getConfig' => ['ZookeeperConfig'],
'Zookeeper::getRecvTimeout' => ['int'],
'Zookeeper::getState' => ['int'],
'Zookeeper::isRecoverable' => ['bool'],
'Zookeeper::set' => ['bool', 'path'=>'string', 'value'=>'string', 'version='=>'int', 'stat='=>'array'],
'Zookeeper::setAcl' => ['bool', 'path'=>'string', 'version'=>'int', 'acl'=>'array'],
'Zookeeper::setDebugLevel' => ['bool', 'logLevel'=>'int'],
'Zookeeper::setDeterministicConnOrder' => ['bool', 'yesOrNo'=>'bool'],
'Zookeeper::setLogStream' => ['bool', 'stream'=>'resource'],
'Zookeeper::setWatcher' => ['bool', 'watcher_cb'=>'callable'],
'zookeeper_dispatch' => ['void'],
'ZookeeperConfig::add' => ['void', 'members'=>'string', 'version='=>'int', 'stat='=>'array'],
'ZookeeperConfig::get' => ['string', 'watcher_cb='=>'callable', 'stat='=>'array'],
'ZookeeperConfig::remove' => ['void', 'id_list'=>'string', 'version='=>'int', 'stat='=>'array'],
'ZookeeperConfig::set' => ['void', 'members'=>'string', 'version='=>'int', 'stat='=>'array'],
];
| 1 | 9,864 | Shouldn't it be in the reverse order? `DateTime::createFromInterface()` returns `self` and accepts `DateTimeInterface`. | vimeo-psalm | php |
@@ -114,12 +114,6 @@ function getArrayBuffer (chunk) {
function getFileType (file) {
const fileExtension = file.name ? getFileNameAndExtension(file.name).extension : null
-
- if (file.isRemote) {
- // some remote providers do not support file types
- return file.type ? file.type : mimeTypes[fileExtension]
- }
-
// check if mime type is set in the file object
if (file.type) {
return file.type | 1 | const throttle = require('lodash.throttle')
const mimeTypes = require('./mime-types.js')
/**
* A collection of small utility functions that help with dom manipulation, adding listeners,
* promises and other good things.
*
* @module Utils
*/
function isTouchDevice () {
return 'ontouchstart' in window || // works on most browsers
navigator.maxTouchPoints // works on IE10/11 and Surface
}
function truncateString (str, length) {
if (str.length > length) {
return str.substr(0, length / 2) + '...' + str.substr(str.length - length / 4, str.length)
}
return str
// more precise version if needed
// http://stackoverflow.com/a/831583
}
function secondsToTime (rawSeconds) {
const hours = Math.floor(rawSeconds / 3600) % 24
const minutes = Math.floor(rawSeconds / 60) % 60
const seconds = Math.floor(rawSeconds % 60)
return { hours, minutes, seconds }
}
/**
* Converts list into array
*/
function toArray (list) {
return Array.prototype.slice.call(list || [], 0)
}
/**
* Returns a timestamp in the format of `hours:minutes:seconds`
*/
function getTimeStamp () {
var date = new Date()
var hours = pad(date.getHours().toString())
var minutes = pad(date.getMinutes().toString())
var seconds = pad(date.getSeconds().toString())
return hours + ':' + minutes + ':' + seconds
}
/**
* Adds zero to strings shorter than two characters
*/
function pad (str) {
return str.length !== 2 ? 0 + str : str
}
/**
* Takes a file object and turns it into fileID, by converting file.name to lowercase,
* removing extra characters and adding type, size and lastModified
*
* @param {Object} file
* @return {String} the fileID
*
*/
function generateFileID (file) {
// filter is needed to not join empty values with `-`
return [
'uppy',
file.name ? file.name.toLowerCase().replace(/[^A-Z0-9]/ig, '') : '',
file.type,
file.data.size,
file.data.lastModified
].filter(val => val).join('-')
}
/**
* Runs an array of promise-returning functions in sequence.
*/
function runPromiseSequence (functions, ...args) {
let promise = Promise.resolve()
functions.forEach((func) => {
promise = promise.then(() => func(...args))
})
return promise
}
function isPreviewSupported (fileType) {
if (!fileType) return false
const fileTypeSpecific = fileType.split('/')[1]
// list of images that browsers can preview
if (/^(jpeg|gif|png|svg|svg\+xml|bmp)$/.test(fileTypeSpecific)) {
return true
}
return false
}
function getArrayBuffer (chunk) {
return new Promise(function (resolve, reject) {
var reader = new FileReader()
reader.addEventListener('load', function (e) {
// e.target.result is an ArrayBuffer
resolve(e.target.result)
})
reader.addEventListener('error', function (err) {
console.error('FileReader error' + err)
reject(err)
})
// file-type only needs the first 4100 bytes
reader.readAsArrayBuffer(chunk)
})
}
function getFileType (file) {
const fileExtension = file.name ? getFileNameAndExtension(file.name).extension : null
if (file.isRemote) {
// some remote providers do not support file types
return file.type ? file.type : mimeTypes[fileExtension]
}
// check if mime type is set in the file object
if (file.type) {
return file.type
}
// see if we can map extension to a mime type
if (fileExtension && mimeTypes[fileExtension]) {
return mimeTypes[fileExtension]
}
// if all fails, well, return empty
return null
}
// TODO Check which types are actually supported in browsers. Chrome likes webm
// from my testing, but we may need more.
// We could use a library but they tend to contain dozens of KBs of mappings,
// most of which will go unused, so not sure if that's worth it.
const mimeToExtensions = {
'video/ogg': 'ogv',
'audio/ogg': 'ogg',
'video/webm': 'webm',
'audio/webm': 'webm',
'video/mp4': 'mp4',
'audio/mp3': 'mp3'
}
function getFileTypeExtension (mimeType) {
return mimeToExtensions[mimeType] || null
}
/**
* Takes a full filename string and returns an object {name, extension}
*
* @param {string} fullFileName
* @return {object} {name, extension}
*/
function getFileNameAndExtension (fullFileName) {
var re = /(?:\.([^.]+))?$/
var fileExt = re.exec(fullFileName)[1]
var fileName = fullFileName.replace('.' + fileExt, '')
return {
name: fileName,
extension: fileExt
}
}
/**
* Check if a URL string is an object URL from `URL.createObjectURL`.
*
* @param {string} url
* @return {boolean}
*/
function isObjectURL (url) {
return url.indexOf('blob:') === 0
}
/**
* Save a <canvas> element's content to a Blob object.
*
* @param {HTMLCanvasElement} canvas
* @return {Promise}
*/
function canvasToBlob (canvas, type, quality) {
if (canvas.toBlob) {
return new Promise((resolve) => {
canvas.toBlob(resolve, type, quality)
})
}
return Promise.resolve().then(() => {
return dataURItoBlob(canvas.toDataURL(type, quality), {})
})
}
function dataURItoBlob (dataURI, opts, toFile) {
// get the base64 data
var data = dataURI.split(',')[1]
// user may provide mime type, if not get it from data URI
var mimeType = opts.mimeType || dataURI.split(',')[0].split(':')[1].split(';')[0]
// default to plain/text if data URI has no mimeType
if (mimeType == null) {
mimeType = 'plain/text'
}
var binary = atob(data)
var array = []
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i))
}
// Convert to a File?
if (toFile) {
return new File([new Uint8Array(array)], opts.name || '', {type: mimeType})
}
return new Blob([new Uint8Array(array)], {type: mimeType})
}
function dataURItoFile (dataURI, opts) {
return dataURItoBlob(dataURI, opts, true)
}
/**
* Copies text to clipboard by creating an almost invisible textarea,
* adding text there, then running execCommand('copy').
* Falls back to prompt() when the easy way fails (hello, Safari!)
* From http://stackoverflow.com/a/30810322
*
* @param {String} textToCopy
* @param {String} fallbackString
* @return {Promise}
*/
function copyToClipboard (textToCopy, fallbackString) {
fallbackString = fallbackString || 'Copy the URL below'
return new Promise((resolve) => {
const textArea = document.createElement('textarea')
textArea.setAttribute('style', {
position: 'fixed',
top: 0,
left: 0,
width: '2em',
height: '2em',
padding: 0,
border: 'none',
outline: 'none',
boxShadow: 'none',
background: 'transparent'
})
textArea.value = textToCopy
document.body.appendChild(textArea)
textArea.select()
const magicCopyFailed = () => {
document.body.removeChild(textArea)
window.prompt(fallbackString, textToCopy)
resolve()
}
try {
const successful = document.execCommand('copy')
if (!successful) {
return magicCopyFailed('copy command unavailable')
}
document.body.removeChild(textArea)
return resolve()
} catch (err) {
document.body.removeChild(textArea)
return magicCopyFailed(err)
}
})
}
function getSpeed (fileProgress) {
if (!fileProgress.bytesUploaded) return 0
const timeElapsed = (new Date()) - fileProgress.uploadStarted
const uploadSpeed = fileProgress.bytesUploaded / (timeElapsed / 1000)
return uploadSpeed
}
function getBytesRemaining (fileProgress) {
return fileProgress.bytesTotal - fileProgress.bytesUploaded
}
function getETA (fileProgress) {
if (!fileProgress.bytesUploaded) return 0
const uploadSpeed = getSpeed(fileProgress)
const bytesRemaining = getBytesRemaining(fileProgress)
const secondsRemaining = Math.round(bytesRemaining / uploadSpeed * 10) / 10
return secondsRemaining
}
function prettyETA (seconds) {
const time = secondsToTime(seconds)
// Only display hours and minutes if they are greater than 0 but always
// display minutes if hours is being displayed
// Display a leading zero if the there is a preceding unit: 1m 05s, but 5s
const hoursStr = time.hours ? time.hours + 'h ' : ''
const minutesVal = time.hours ? ('0' + time.minutes).substr(-2) : time.minutes
const minutesStr = minutesVal ? minutesVal + 'm ' : ''
const secondsVal = minutesVal ? ('0' + time.seconds).substr(-2) : time.seconds
const secondsStr = secondsVal + 's'
return `${hoursStr}${minutesStr}${secondsStr}`
}
/**
* Check if an object is a DOM element. Duck-typing based on `nodeType`.
*
* @param {*} obj
*/
function isDOMElement (obj) {
return obj && typeof obj === 'object' && obj.nodeType === Node.ELEMENT_NODE
}
/**
* Find a DOM element.
*
* @param {Node|string} element
* @return {Node|null}
*/
function findDOMElement (element) {
if (typeof element === 'string') {
return document.querySelector(element)
}
if (typeof element === 'object' && isDOMElement(element)) {
return element
}
}
/**
* Find one or more DOM elements.
*
* @param {string} element
* @return {Array|null}
*/
function findAllDOMElements (element) {
if (typeof element === 'string') {
const elements = [].slice.call(document.querySelectorAll(element))
return elements.length > 0 ? elements : null
}
if (typeof element === 'object' && isDOMElement(element)) {
return [element]
}
}
function getSocketHost (url) {
// get the host domain
var regex = /^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?(?:www\.)?([^\n]+)/
var host = regex.exec(url)[1]
var socketProtocol = location.protocol === 'https:' ? 'wss' : 'ws'
return `${socketProtocol}://${host}`
}
function _emitSocketProgress (uploader, progressData, file) {
const { progress, bytesUploaded, bytesTotal } = progressData
if (progress) {
uploader.uppy.log(`Upload progress: ${progress}`)
uploader.uppy.emit('upload-progress', file, {
uploader,
bytesUploaded: bytesUploaded,
bytesTotal: bytesTotal
})
}
}
const emitSocketProgress = throttle(_emitSocketProgress, 300, {leading: true, trailing: true})
function settle (promises) {
const resolutions = []
const rejections = []
function resolved (value) {
resolutions.push(value)
}
function rejected (error) {
rejections.push(error)
}
const wait = Promise.all(
promises.map((promise) => promise.then(resolved, rejected))
)
return wait.then(() => {
return {
successful: resolutions,
failed: rejections
}
})
}
/**
* Limit the amount of simultaneously pending Promises.
* Returns a function that, when passed a function `fn`,
* will make sure that at most `limit` calls to `fn` are pending.
*
* @param {number} limit
* @return {function()}
*/
function limitPromises (limit) {
let pending = 0
const queue = []
return (fn) => {
return (...args) => {
const call = () => {
pending++
const promise = fn(...args)
promise.then(onfinish, onfinish)
return promise
}
if (pending >= limit) {
return new Promise((resolve, reject) => {
queue.push(() => {
call().then(resolve, reject)
})
})
}
return call()
}
}
function onfinish () {
pending--
const next = queue.shift()
if (next) next()
}
}
module.exports = {
generateFileID,
toArray,
getTimeStamp,
runPromiseSequence,
isTouchDevice,
getFileNameAndExtension,
truncateString,
getFileTypeExtension,
getFileType,
getArrayBuffer,
isPreviewSupported,
isObjectURL,
secondsToTime,
dataURItoBlob,
dataURItoFile,
canvasToBlob,
getSpeed,
getBytesRemaining,
getETA,
copyToClipboard,
prettyETA,
findDOMElement,
findAllDOMElements,
getSocketHost,
emitSocketProgress,
settle,
limitPromises
}
| 1 | 10,868 | this check is now redundant. The rest of the function downwards basically does the same thing but with safer checks. | transloadit-uppy | js |
@@ -71,7 +71,7 @@ class Feature extends BaseI18nLoop implements PropelSearchLoopInterface
new Argument(
'order',
new TypeCollection(
- new Type\EnumListType(array('id', 'id_reverse', 'alpha', 'alpha-reverse', 'manual', 'manual_reverse'))
+ new Type\EnumListType(array('id', 'id_reverse', 'alpha', 'alpha-reverse', 'alpha_reverse' , 'manual', 'manual_reverse'))
),
'manual'
), | 1 | <?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : [email protected] */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseI18nLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Model\FeatureI18nQuery;
use Thelia\Model\FeatureQuery;
use Thelia\Model\Product as ProductModel;
use Thelia\Model\ProductQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Thelia\Type\BooleanOrBothType;
use Thelia\Model\FeatureTemplateQuery;
use Thelia\Model\TemplateQuery;
use Thelia\Model\Map\FeatureTemplateTableMap;
use Thelia\Model\Feature as FeatureModel;
/**
*
* Feature loop
*
*
* Class Feature
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <[email protected]>
*
* {@inheritdoc}
* @method int[] getId()
* @method int[] getProduct()
* @method int[] getTemplate()
* @method int[] getExcludeTemplate()
* @method bool|string getVisible()
* @method int[] getExclude()
* @method string getTitle()
* @method string[] getOrder()
*/
class Feature extends BaseI18nLoop implements PropelSearchLoopInterface
{
protected $useFeaturePosition;
protected $timestampable = true;
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntListTypeArgument('product'),
Argument::createIntListTypeArgument('template'),
Argument::createIntListTypeArgument('exclude_template'),
Argument::createBooleanOrBothTypeArgument('visible', 1),
Argument::createIntListTypeArgument('exclude'),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('id', 'id_reverse', 'alpha', 'alpha-reverse', 'manual', 'manual_reverse'))
),
'manual'
),
Argument::createAnyTypeArgument('title')
);
}
public function buildModelCriteria()
{
$search = FeatureQuery::create();
/* manage translations */
$this->configureI18nProcessing($search);
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$exclude = $this->getExclude();
if (null !== $exclude) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$visible = $this->getVisible();
if ($visible != BooleanOrBothType::ANY) {
$search->filterByVisible($visible);
}
$product = $this->getProduct();
$template = $this->getTemplate();
$excludeTemplate = $this->getExcludeTemplate();
$this->useFeaturePosition = true;
if (null !== $product) {
// Find all template assigned to the products.
$products = ProductQuery::create()->findById($product);
// Ignore if the product cannot be found.
if ($products !== null) {
// Create template array
if ($template == null) {
$template = array();
}
/** @var ProductModel $product */
foreach ($products as $product) {
$tplId = $product->getTemplateId();
if (! is_null($tplId)) {
$template[] = $tplId;
}
}
}
// [email protected] - 05/12/2013 : if the given product has no template
// or if the product cannot be found, do not return anything.
if (empty($template)) {
return null;
}
}
if (! empty($template)) {
// Join with feature_template table to get position
$search
->withColumn(FeatureTemplateTableMap::POSITION, 'position')
->filterByTemplate(TemplateQuery::create()->findById($template), Criteria::IN)
;
$this->useFeaturePosition = false;
}
if (null !== $excludeTemplate) {
$search
->filterById(
FeatureTemplateQuery::create()->filterByTemplateId($excludeTemplate)->select('feature_id')->find(),
Criteria::NOT_IN
)
;
}
$title = $this->getTitle();
if (null !== $title) {
//find all feature that match exactly this title and find with all locales.
$features = FeatureI18nQuery::create()
->filterByTitle($title, Criteria::LIKE)
->select('id')
->find();
if ($features) {
$search->filterById(
$features,
Criteria::IN
);
}
}
$orders = $this->getOrder();
foreach ($orders as $order) {
switch ($order) {
case "id":
$search->orderById(Criteria::ASC);
break;
case "id_reverse":
$search->orderById(Criteria::DESC);
break;
case "alpha":
$search->addAscendingOrderByColumn('i18n_TITLE');
break;
case "alpha-reverse":
$search->addDescendingOrderByColumn('i18n_TITLE');
break;
case "manual":
if ($this->useFeaturePosition) {
$search->orderByPosition(Criteria::ASC);
} else {
$search->addAscendingOrderByColumn(FeatureTemplateTableMap::POSITION);
}
break;
case "manual_reverse":
if ($this->useFeaturePosition) {
$search->orderByPosition(Criteria::DESC);
} else {
$search->addDescendingOrderByColumn(FeatureTemplateTableMap::POSITION);
}
break;
}
}
return $search;
}
public function parseResults(LoopResult $loopResult)
{
/** @var FeatureModel $feature */
foreach ($loopResult->getResultDataCollection() as $feature) {
$loopResultRow = new LoopResultRow($feature);
$loopResultRow->set("ID", $feature->getId())
->set("IS_TRANSLATED", $feature->getVirtualColumn('IS_TRANSLATED'))
->set("LOCALE", $this->locale)
->set("TITLE", $feature->getVirtualColumn('i18n_TITLE'))
->set("CHAPO", $feature->getVirtualColumn('i18n_CHAPO'))
->set("DESCRIPTION", $feature->getVirtualColumn('i18n_DESCRIPTION'))
->set("POSTSCRIPTUM", $feature->getVirtualColumn('i18n_POSTSCRIPTUM'))
->set("POSITION", $this->useFeaturePosition ? $feature->getPosition() : $feature->getVirtualColumn('position'))
;
$this->addOutputFields($loopResultRow, $feature);
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}
| 1 | 11,648 | Please could you remove the useless space. | thelia-thelia | php |
@@ -1082,12 +1082,14 @@ public final class OrdsSegmentTermsEnum extends BaseTermsEnum {
if (FST.targetHasArcs(arc)) {
// System.out.println(" targetHasArcs");
result.grow(1+upto);
-
+ if (arc.target < 0 || arc.target > Integer.MAX_VALUE) {
+ assert(arc.target >= 0);
+ assert(arc.target < Integer.MAX_VALUE);
+ }
fr.index.readFirstRealTargetArc(arc.target, arc, fstReader);
if (arc.bytesPerArc != 0) {
// System.out.println(" array arcs");
-
int low = 0;
int high = arc.numArcs-1;
int mid = 0; | 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.lucene.codecs.blocktreeords;
//import java.io.*;
//import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.io.PrintStream;
import org.apache.lucene.codecs.BlockTermState;
import org.apache.lucene.codecs.blocktreeords.FSTOrdsOutputs.Output;
import org.apache.lucene.index.BaseTermsEnum;
import org.apache.lucene.index.ImpactsEnum;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.TermState;
import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.Util;
/** Iterates through terms in this field. */
public final class OrdsSegmentTermsEnum extends BaseTermsEnum {
// Lazy init:
IndexInput in;
// static boolean DEBUG = true;
private OrdsSegmentTermsEnumFrame[] stack;
private final OrdsSegmentTermsEnumFrame staticFrame;
OrdsSegmentTermsEnumFrame currentFrame;
boolean termExists;
final OrdsFieldReader fr;
private int targetBeforeCurrentLength;
private final ByteArrayDataInput scratchReader = new ByteArrayDataInput();
// What prefix of the current term was present in the index:
private int validIndexPrefix;
// assert only:
private boolean eof;
final BytesRefBuilder term = new BytesRefBuilder();
private final FST.BytesReader fstReader;
@SuppressWarnings({"rawtypes","unchecked"}) private FST.Arc<Output>[] arcs =
new FST.Arc[1];
boolean positioned;
OrdsSegmentTermsEnum(OrdsFieldReader fr) throws IOException {
this.fr = fr;
//if (DEBUG) System.out.println("BTTR.init seg=" + segment);
stack = new OrdsSegmentTermsEnumFrame[0];
// Used to hold seek by TermState, or cached seek
staticFrame = new OrdsSegmentTermsEnumFrame(this, -1);
if (fr.index == null) {
fstReader = null;
} else {
fstReader = fr.index.getBytesReader();
}
// Init w/ root block; don't use index since it may
// not (and need not) have been loaded
for(int arcIdx=0;arcIdx<arcs.length;arcIdx++) {
arcs[arcIdx] = new FST.Arc<>();
}
currentFrame = staticFrame;
final FST.Arc<Output> arc;
if (fr.index != null) {
arc = fr.index.getFirstArc(arcs[0]);
// Empty string prefix must have an output in the index!
assert arc.isFinal();
} else {
arc = null;
}
//currentFrame = pushFrame(arc, rootCode, 0);
//currentFrame.loadBlock();
validIndexPrefix = 0;
// if (DEBUG) {
// System.out.println("init frame state " + currentFrame.ord);
// printSeekState();
// }
//System.out.println();
// computeBlockStats().print(System.out);
}
// Not private to avoid synthetic access$NNN methods
void initIndexInput() {
if (this.in == null) {
this.in = fr.parent.in.clone();
}
}
private OrdsSegmentTermsEnumFrame getFrame(int ord) throws IOException {
if (ord >= stack.length) {
final OrdsSegmentTermsEnumFrame[] next = new OrdsSegmentTermsEnumFrame[ArrayUtil.oversize(1+ord, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(stack, 0, next, 0, stack.length);
for(int stackOrd=stack.length;stackOrd<next.length;stackOrd++) {
next[stackOrd] = new OrdsSegmentTermsEnumFrame(this, stackOrd);
}
stack = next;
}
assert stack[ord].ord == ord;
return stack[ord];
}
private FST.Arc<Output> getArc(int ord) {
if (ord >= arcs.length) {
@SuppressWarnings({"rawtypes","unchecked"}) final FST.Arc<Output>[] next =
new FST.Arc[ArrayUtil.oversize(1+ord, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(arcs, 0, next, 0, arcs.length);
for(int arcOrd=arcs.length;arcOrd<next.length;arcOrd++) {
next[arcOrd] = new FST.Arc<>();
}
arcs = next;
}
return arcs[ord];
}
// Pushes a frame we seek'd to
OrdsSegmentTermsEnumFrame pushFrame(FST.Arc<Output> arc, Output frameData, int length) throws IOException {
scratchReader.reset(frameData.bytes.bytes, frameData.bytes.offset, frameData.bytes.length);
final long code = scratchReader.readVLong();
final long fpSeek = code >>> OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS;
// System.out.println(" fpSeek=" + fpSeek);
final OrdsSegmentTermsEnumFrame f = getFrame(1+currentFrame.ord);
f.hasTerms = (code & OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS) != 0;
f.hasTermsOrig = f.hasTerms;
f.isFloor = (code & OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR) != 0;
// Must setFloorData before pushFrame in case pushFrame tries to rewind:
if (f.isFloor) {
f.termOrdOrig = frameData.startOrd;
f.setFloorData(scratchReader, frameData.bytes);
}
pushFrame(arc, fpSeek, length, frameData.startOrd);
return f;
}
// Pushes next'd frame or seek'd frame; we later
// lazy-load the frame only when needed
OrdsSegmentTermsEnumFrame pushFrame(FST.Arc<Output> arc, long fp, int length, long termOrd) throws IOException {
final OrdsSegmentTermsEnumFrame f = getFrame(1+currentFrame.ord);
f.arc = arc;
// System.out.println("pushFrame termOrd= " + termOrd + " fpOrig=" + f.fpOrig + " fp=" + fp + " nextEnt=" + f.nextEnt);
if (f.fpOrig == fp && f.nextEnt != -1) {
//if (DEBUG) System.out.println(" push reused frame ord=" + f.ord + " fp=" + f.fp + " isFloor?=" + f.isFloor + " hasTerms=" + f.hasTerms + " pref=" + term + " nextEnt=" + f.nextEnt + " targetBeforeCurrentLength=" + targetBeforeCurrentLength + " term.length=" + term.length + " vs prefix=" + f.prefix);
if (f.prefix > targetBeforeCurrentLength) {
// System.out.println(" do rewind!");
f.rewind();
} else {
// if (DEBUG) {
// System.out.println(" skip rewind!");
// }
}
assert length == f.prefix;
assert termOrd == f.termOrdOrig;
} else {
f.nextEnt = -1;
f.prefix = length;
f.state.termBlockOrd = 0;
f.termOrdOrig = termOrd;
// System.out.println("set termOrdOrig=" + termOrd);
f.termOrd = termOrd;
f.fpOrig = f.fp = fp;
f.lastSubFP = -1;
// if (DEBUG) {
// final int sav = term.length;
// term.length = length;
// System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term));
// term.length = sav;
// }
}
return f;
}
// asserts only
private boolean clearEOF() {
eof = false;
return true;
}
// asserts only
private boolean setEOF() {
eof = true;
return true;
}
// for debugging
@SuppressWarnings("unused")
static String brToString(BytesRef b) {
try {
return b.utf8ToString() + " " + b;
} catch (Throwable t) {
// If BytesRef isn't actually UTF8, or it's eg a
// prefix of UTF8 that ends mid-unicode-char, we
// fallback to hex:
return b.toString();
}
}
@Override
public boolean seekExact(final BytesRef target) throws IOException {
if (fr.index == null) {
throw new IllegalStateException("terms index was not loaded");
}
term.grow(1+target.length);
assert clearEOF();
/*
if (DEBUG) {
System.out.println("\nBTTR.seekExact seg=" + fr.parent.segment + " target=" + fr.fieldInfo.name + ":" + brToString(target) + " current=" + brToString(term) + " (exists?=" + termExists + ") validIndexPrefix=" + validIndexPrefix);
printSeekState(System.out);
}
*/
FST.Arc<Output> arc;
int targetUpto;
Output output;
targetBeforeCurrentLength = currentFrame.ord;
if (positioned && currentFrame != staticFrame) {
// We are already seek'd; find the common
// prefix of new seek term vs current term and
// re-use the corresponding seek state. For
// example, if app first seeks to foobar, then
// seeks to foobaz, we can re-use the seek state
// for the first 5 bytes.
// if (DEBUG) {
// System.out.println(" re-use current seek state validIndexPrefix=" + validIndexPrefix);
// }
arc = arcs[0];
assert arc.isFinal();
output = arc.output;
targetUpto = 0;
OrdsSegmentTermsEnumFrame lastFrame = stack[0];
assert validIndexPrefix <= term.length();
final int targetLimit = Math.min(target.length, validIndexPrefix);
int cmp = 0;
// TODO: reverse vLong byte order for better FST
// prefix output sharing
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
// }
if (cmp != 0) {
break;
}
arc = arcs[1+targetUpto];
assert arc.label == (target.bytes[target.offset + targetUpto] & 0xFF): "arc.label=" + (char) arc.label + " targetLabel=" + (char) (target.bytes[target.offset + targetUpto] & 0xFF);
if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {
output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);
}
if (arc.isFinal()) {
lastFrame = stack[1+lastFrame.ord];
}
targetUpto++;
}
if (cmp == 0) {
final int targetUptoMid = targetUpto;
// Second compare the rest of the term, but
// don't save arc/output/frame; we only do this
// to find out if the target term is before,
// equal or after the current term
final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
// }
if (cmp != 0) {
break;
}
targetUpto++;
}
if (cmp == 0) {
cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
if (cmp < 0) {
// Common case: target term is after current
// term, ie, app is seeking multiple terms
// in sorted order
// if (DEBUG) {
// System.out.println(" target is after current (shares prefixLen=" + targetUpto + "); frame.ord=" + lastFrame.ord);
// }
currentFrame = lastFrame;
} else if (cmp > 0) {
// Uncommon case: target term
// is before current term; this means we can
// keep the currentFrame but we must rewind it
// (so we scan from the start)
targetBeforeCurrentLength = lastFrame.ord;
// if (DEBUG) {
// System.out.println(" target is before current (shares prefixLen=" + targetUpto + "); rewind frame ord=" + lastFrame.ord);
// }
currentFrame = lastFrame;
currentFrame.rewind();
} else {
// Target is exactly the same as current term
assert term.length() == target.length;
if (termExists) {
// if (DEBUG) {
// System.out.println(" target is same as current; return true");
// }
return true;
} else {
// if (DEBUG) {
// System.out.println(" target is same as current but term doesn't exist");
// }
}
//validIndexPrefix = currentFrame.depth;
//term.length = target.length;
//return termExists;
}
} else {
targetBeforeCurrentLength = -1;
arc = fr.index.getFirstArc(arcs[0]);
// Empty string prefix must have an output (block) in the index!
assert arc.isFinal();
assert arc.output != null;
// if (DEBUG) {
// System.out.println(" no seek state; push root frame");
// }
output = arc.output;
currentFrame = staticFrame;
//term.length = 0;
targetUpto = 0;
currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), 0);
}
positioned = true;
// if (DEBUG) {
// System.out.println(" start index loop targetUpto=" + targetUpto + " output=" + output + " currentFrame.ord=" + currentFrame.ord + " targetBeforeCurrentLength=" + targetBeforeCurrentLength);
// }
// We are done sharing the common prefix with the incoming target and where we are currently seek'd; now continue walking the index:
while (targetUpto < target.length) {
final int targetLabel = target.bytes[target.offset + targetUpto] & 0xFF;
final FST.Arc<Output> nextArc = fr.index.findTargetArc(targetLabel, arc, getArc(1+targetUpto), fstReader);
if (nextArc == null) {
// Index is exhausted
// if (DEBUG) {
// System.out.println(" index: index exhausted label=" + ((char) targetLabel) + " " + toHex(targetLabel));
// }
validIndexPrefix = currentFrame.prefix;
//validIndexPrefix = targetUpto;
currentFrame.scanToFloorFrame(target);
if (!currentFrame.hasTerms) {
termExists = false;
term.setByteAt(targetUpto, (byte) targetLabel);
term.setLength(1+targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
return false;
}
currentFrame.loadBlock();
final SeekStatus result = currentFrame.scanToTerm(target, true);
if (result == SeekStatus.FOUND) {
// if (DEBUG) {
// System.out.println(" return FOUND term=" + term.utf8ToString() + " " + term);
// }
return true;
} else {
// if (DEBUG) {
// System.out.println(" got " + result + "; return NOT_FOUND term=" + brToString(term));
// }
return false;
}
} else {
// Follow this arc
arc = nextArc;
term.setByteAt(targetUpto, (byte) targetLabel);
// Aggregate output as we go:
assert arc.output != null;
if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {
output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);
}
// if (DEBUG) {
// System.out.println(" index: follow label=" + toHex(target.bytes[target.offset + targetUpto]&0xff) + " arc.output=" + arc.output + " arc.nfo=" + arc.nextFinalOutput);
// }
targetUpto++;
if (arc.isFinal()) {
//if (DEBUG) System.out.println(" arc is final!");
currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), targetUpto);
//if (DEBUG) System.out.println(" curFrame.ord=" + currentFrame.ord + " hasTerms=" + currentFrame.hasTerms);
}
}
}
//validIndexPrefix = targetUpto;
validIndexPrefix = currentFrame.prefix;
currentFrame.scanToFloorFrame(target);
// Target term is entirely contained in the index:
if (!currentFrame.hasTerms) {
termExists = false;
term.setLength(targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
return false;
}
currentFrame.loadBlock();
final SeekStatus result = currentFrame.scanToTerm(target, true);
if (result == SeekStatus.FOUND) {
// if (DEBUG) {
// System.out.println(" return FOUND term=" + term.utf8ToString() + " " + term);
// }
return true;
} else {
// if (DEBUG) {
// System.out.println(" got result " + result + "; return NOT_FOUND term=" + term.utf8ToString());
// }
return false;
}
}
@Override
public SeekStatus seekCeil(final BytesRef target) throws IOException {
if (fr.index == null) {
throw new IllegalStateException("terms index was not loaded");
}
term.grow(1+target.length);
assert clearEOF();
//if (DEBUG) {
//System.out.println("\nBTTR.seekCeil seg=" + segment + " target=" + fieldInfo.name + ":" + target.utf8ToString() + " " + target + " current=" + brToString(term) + " (exists?=" + termExists + ") validIndexPrefix= " + validIndexPrefix);
//printSeekState();
//}
FST.Arc<Output> arc;
int targetUpto;
Output output;
targetBeforeCurrentLength = currentFrame.ord;
if (positioned && currentFrame != staticFrame) {
// We are already seek'd; find the common
// prefix of new seek term vs current term and
// re-use the corresponding seek state. For
// example, if app first seeks to foobar, then
// seeks to foobaz, we can re-use the seek state
// for the first 5 bytes.
//if (DEBUG) {
//System.out.println(" re-use current seek state validIndexPrefix=" + validIndexPrefix);
//}
arc = arcs[0];
assert arc.isFinal();
output = arc.output;
targetUpto = 0;
OrdsSegmentTermsEnumFrame lastFrame = stack[0];
assert validIndexPrefix <= term.length();
final int targetLimit = Math.min(target.length, validIndexPrefix);
int cmp = 0;
// TODO: we should write our vLong backwards (MSB
// first) to get better sharing from the FST
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
//}
if (cmp != 0) {
break;
}
arc = arcs[1+targetUpto];
assert arc.label == (target.bytes[target.offset + targetUpto] & 0xFF): "arc.label=" + (char) arc.label + " targetLabel=" + (char) (target.bytes[target.offset + targetUpto] & 0xFF);
// TODO: we could save the outputs in local
// byte[][] instead of making new objs ever
// seek; but, often the FST doesn't have any
// shared bytes (but this could change if we
// reverse vLong byte order)
if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {
output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);
}
if (arc.isFinal()) {
lastFrame = stack[1+lastFrame.ord];
}
targetUpto++;
}
if (cmp == 0) {
final int targetUptoMid = targetUpto;
// Second compare the rest of the term, but
// don't save arc/output/frame:
final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
//}
if (cmp != 0) {
break;
}
targetUpto++;
}
if (cmp == 0) {
cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
if (cmp < 0) {
// Common case: target term is after current
// term, ie, app is seeking multiple terms
// in sorted order
//if (DEBUG) {
//System.out.println(" target is after current (shares prefixLen=" + targetUpto + "); clear frame.scanned ord=" + lastFrame.ord);
//}
currentFrame = lastFrame;
} else if (cmp > 0) {
// Uncommon case: target term
// is before current term; this means we can
// keep the currentFrame but we must rewind it
// (so we scan from the start)
targetBeforeCurrentLength = 0;
//if (DEBUG) {
//System.out.println(" target is before current (shares prefixLen=" + targetUpto + "); rewind frame ord=" + lastFrame.ord);
//}
currentFrame = lastFrame;
currentFrame.rewind();
} else {
// Target is exactly the same as current term
assert term.length() == target.length;
if (termExists) {
//if (DEBUG) {
//System.out.println(" target is same as current; return FOUND");
//}
return SeekStatus.FOUND;
} else {
//if (DEBUG) {
//System.out.println(" target is same as current but term doesn't exist");
//}
}
}
} else {
targetBeforeCurrentLength = -1;
arc = fr.index.getFirstArc(arcs[0]);
// Empty string prefix must have an output (block) in the index!
assert arc.isFinal();
assert arc.output != null;
//if (DEBUG) {
//System.out.println(" no seek state; push root frame");
//}
output = arc.output;
currentFrame = staticFrame;
//term.length = 0;
targetUpto = 0;
currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), 0);
}
positioned = true;
//if (DEBUG) {
//System.out.println(" start index loop targetUpto=" + targetUpto + " output=" + output + " currentFrame.ord+1=" + currentFrame.ord + " targetBeforeCurrentLength=" + targetBeforeCurrentLength);
//}
// We are done sharing the common prefix with the incoming target and where we are currently seek'd; now continue walking the index:
while (targetUpto < target.length) {
final int targetLabel = target.bytes[target.offset + targetUpto] & 0xFF;
final FST.Arc<Output> nextArc = fr.index.findTargetArc(targetLabel, arc, getArc(1+targetUpto), fstReader);
if (nextArc == null) {
// Index is exhausted
// if (DEBUG) {
// System.out.println(" index: index exhausted label=" + ((char) targetLabel) + " " + toHex(targetLabel));
// }
validIndexPrefix = currentFrame.prefix;
//validIndexPrefix = targetUpto;
currentFrame.scanToFloorFrame(target);
currentFrame.loadBlock();
final SeekStatus result = currentFrame.scanToTerm(target, false);
if (result == SeekStatus.END) {
term.copyBytes(target);
termExists = false;
if (next() != null) {
//if (DEBUG) {
//System.out.println(" return NOT_FOUND term=" + brToString(term) + " " + term);
//}
return SeekStatus.NOT_FOUND;
} else {
//if (DEBUG) {
//System.out.println(" return END");
//}
return SeekStatus.END;
}
} else {
//if (DEBUG) {
//System.out.println(" return " + result + " term=" + brToString(term) + " " + term);
//}
return result;
}
} else {
// Follow this arc
term.setByteAt(targetUpto, (byte) targetLabel);
arc = nextArc;
// Aggregate output as we go:
assert arc.output != null;
if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {
output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);
}
//if (DEBUG) {
//System.out.println(" index: follow label=" + toHex(target.bytes[target.offset + targetUpto]&0xff) + " arc.output=" + arc.output + " arc.nfo=" + arc.nextFinalOutput);
//}
targetUpto++;
if (arc.isFinal()) {
//if (DEBUG) System.out.println(" arc is final!");
currentFrame = pushFrame(arc, OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput), targetUpto);
//if (DEBUG) System.out.println(" curFrame.ord=" + currentFrame.ord + " hasTerms=" + currentFrame.hasTerms);
}
}
}
//validIndexPrefix = targetUpto;
validIndexPrefix = currentFrame.prefix;
currentFrame.scanToFloorFrame(target);
currentFrame.loadBlock();
final SeekStatus result = currentFrame.scanToTerm(target, false);
if (result == SeekStatus.END) {
term.copyBytes(target);
termExists = false;
if (next() != null) {
//if (DEBUG) {
//System.out.println(" return NOT_FOUND term=" + term.utf8ToString() + " " + term);
//}
return SeekStatus.NOT_FOUND;
} else {
//if (DEBUG) {
//System.out.println(" return END");
//}
return SeekStatus.END;
}
} else {
return result;
}
}
@SuppressWarnings("unused")
private void printSeekState(PrintStream out) throws IOException {
if (currentFrame == staticFrame) {
out.println(" no prior seek");
} else {
out.println(" prior seek state:");
int ord = 0;
boolean isSeekFrame = true;
while(true) {
OrdsSegmentTermsEnumFrame f = getFrame(ord);
assert f != null;
final BytesRef prefix = new BytesRef(term.bytes(), 0, f.prefix);
if (f.nextEnt == -1) {
out.println(" frame " + (isSeekFrame ? "(seek)" : "(next)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + brToString(prefix) + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd() + " termOrd=" + f.termOrd);
} else {
out.println(" frame " + (isSeekFrame ? "(seek, loaded)" : "(next, loaded)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + brToString(prefix) + " nextEnt=" + f.nextEnt + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " lastSubFP=" + f.lastSubFP + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd() + " termOrd=" + f.termOrd);
}
if (fr.index != null) {
assert !isSeekFrame || f.arc != null: "isSeekFrame=" + isSeekFrame + " f.arc=" + f.arc;
if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.byteAt(f.prefix-1)&0xFF)) {
out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.byteAt(f.prefix-1)&0xFF));
throw new RuntimeException("seek state is broken");
}
Output output = Util.get(fr.index, prefix);
if (output == null) {
out.println(" broken seek state: prefix is not final in index");
throw new RuntimeException("seek state is broken");
} else if (isSeekFrame && !f.isFloor) {
final ByteArrayDataInput reader = new ByteArrayDataInput(output.bytes.bytes, output.bytes.offset, output.bytes.length);
final long codeOrig = reader.readVLong();
final long code = (f.fp << OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) | (f.hasTerms ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) | (f.isFloor ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0);
if (codeOrig != code) {
out.println(" broken seek state: output code=" + codeOrig + " doesn't match frame code=" + code);
throw new RuntimeException("seek state is broken");
}
}
}
if (f == currentFrame) {
break;
}
if (f.prefix == validIndexPrefix) {
isSeekFrame = false;
}
ord++;
}
}
}
/* Decodes only the term bytes of the next term. If caller then asks for
metadata, ie docFreq, totalTermFreq or pulls a D/&PEnum, we then (lazily)
decode all metadata up to the current term. */
@Override
public BytesRef next() throws IOException {
if (in == null) {
// Fresh TermsEnum; seek to first term:
final FST.Arc<Output> arc;
if (fr.index != null) {
arc = fr.index.getFirstArc(arcs[0]);
// Empty string prefix must have an output in the index!
assert arc.isFinal();
} else {
arc = null;
}
currentFrame = pushFrame(arc, fr.rootCode, 0);
currentFrame.loadBlock();
positioned = true;
}
targetBeforeCurrentLength = currentFrame.ord;
assert !eof;
//if (DEBUG) {
//System.out.println("\nBTTR.next seg=" + segment + " term=" + brToString(term) + " termExists?=" + termExists + " field=" + fieldInfo.name + " termBlockOrd=" + currentFrame.state.termBlockOrd + " validIndexPrefix=" + validIndexPrefix);
//printSeekState();
//}
if (currentFrame == staticFrame || positioned == false) {
// If seek was previously called and the term was
// cached, or seek(TermState) was called, usually
// caller is just going to pull a D/&PEnum or get
// docFreq, etc. But, if they then call next(),
// this method catches up all internal state so next()
// works properly:
// if (DEBUG) System.out.println(" re-seek to pending term=" + term.utf8ToString() + " " + term);
final boolean result = seekExact(term.get());
assert result;
}
// Pop finished blocks
while (currentFrame.nextEnt == currentFrame.entCount) {
if (!currentFrame.isLastInFloor) {
currentFrame.loadNextFloorBlock();
} else {
//if (DEBUG) System.out.println(" pop frame");
if (currentFrame.ord == 0) {
//if (DEBUG) System.out.println(" return null");
assert setEOF();
term.setLength(0);
validIndexPrefix = 0;
currentFrame.rewind();
termExists = false;
positioned = false;
return null;
}
final long lastFP = currentFrame.fpOrig;
currentFrame = stack[currentFrame.ord-1];
if (currentFrame.nextEnt == -1 || currentFrame.lastSubFP != lastFP) {
// We popped into a frame that's not loaded
// yet or not scan'd to the right entry
currentFrame.scanToFloorFrame(term.get());
currentFrame.loadBlock();
currentFrame.scanToSubBlock(lastFP);
}
// Note that the seek state (last seek) has been
// invalidated beyond this depth
validIndexPrefix = Math.min(validIndexPrefix, currentFrame.prefix);
//if (DEBUG) {
//System.out.println(" reset validIndexPrefix=" + validIndexPrefix);
//}
}
}
while(true) {
long prevTermOrd = currentFrame.termOrd;
if (currentFrame.next()) {
// Push to new block:
//if (DEBUG) System.out.println(" push frame");
currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length(), prevTermOrd);
// This is a "next" frame -- even if it's
// floor'd we must pretend it isn't so we don't
// try to scan to the right floor frame:
currentFrame.isFloor = false;
//currentFrame.hasTerms = true;
currentFrame.loadBlock();
} else {
//if (DEBUG) System.out.println(" return term=" + term.utf8ToString() + " " + term + " currentFrame.ord=" + currentFrame.ord);
positioned = true;
return term.get();
}
}
}
@Override
public BytesRef term() {
assert !eof;
return term.get();
}
@Override
public long ord() {
assert !eof;
assert currentFrame.termOrd > 0;
return currentFrame.termOrd-1;
}
@Override
public int docFreq() throws IOException {
assert !eof;
//if (DEBUG) System.out.println("BTR.docFreq");
currentFrame.decodeMetaData();
//if (DEBUG) System.out.println(" return " + currentFrame.state.docFreq);
return currentFrame.state.docFreq;
}
@Override
public long totalTermFreq() throws IOException {
assert !eof;
currentFrame.decodeMetaData();
return currentFrame.state.totalTermFreq;
}
@Override
public PostingsEnum postings(PostingsEnum reuse, int flags) throws IOException {
assert !eof;
//if (DEBUG) {
//System.out.println("BTTR.docs seg=" + segment);
//}
currentFrame.decodeMetaData();
//if (DEBUG) {
//System.out.println(" state=" + currentFrame.state);
//}
return fr.parent.postingsReader.postings(fr.fieldInfo, currentFrame.state, reuse, flags);
}
@Override
public ImpactsEnum impacts(int flags) throws IOException {
assert !eof;
//if (DEBUG) {
//System.out.println("BTTR.docs seg=" + segment);
//}
currentFrame.decodeMetaData();
//if (DEBUG) {
//System.out.println(" state=" + currentFrame.state);
//}
return fr.parent.postingsReader.impacts(fr.fieldInfo, currentFrame.state, flags);
}
@Override
public void seekExact(BytesRef target, TermState otherState) {
// if (DEBUG) {
// System.out.println("BTTR.seekExact termState seg=" + segment + " target=" + target.utf8ToString() + " " + target + " state=" + otherState);
// }
assert clearEOF();
if (target.compareTo(term.get()) != 0 || !termExists) {
assert otherState != null && otherState instanceof BlockTermState;
BlockTermState blockState = (BlockTermState) otherState;
currentFrame = staticFrame;
currentFrame.state.copyFrom(otherState);
term.copyBytes(target);
currentFrame.metaDataUpto = currentFrame.getTermBlockOrd();
currentFrame.termOrd = blockState.ord+1;
assert currentFrame.metaDataUpto > 0;
validIndexPrefix = 0;
} else {
// if (DEBUG) {
// System.out.println(" skip seek: already on target state=" + currentFrame.state);
// }
}
positioned = true;
}
@Override
public TermState termState() throws IOException {
assert !eof;
currentFrame.decodeMetaData();
BlockTermState ts = (BlockTermState) currentFrame.state.clone();
assert currentFrame.termOrd > 0;
ts.ord = currentFrame.termOrd-1;
//if (DEBUG) System.out.println("BTTR.termState seg=" + segment + " state=" + ts);
return ts;
}
@Override
public void seekExact(long targetOrd) throws IOException {
// System.out.println("seekExact targetOrd=" + targetOrd);
if (targetOrd < 0 || targetOrd >= fr.numTerms) {
throw new IllegalArgumentException("targetOrd out of bounds (got: " + targetOrd + ", numTerms=" + fr.numTerms + ")");
}
assert clearEOF();
// First do reverse lookup in the index to find the block that holds this term:
InputOutput io = getByOutput(targetOrd);
term.grow(io.input.length);
Util.toBytesRef(io.input, term);
if (io.input.length == 0) {
currentFrame = staticFrame;
} else {
currentFrame = getFrame(io.input.length-1);
}
FST.Arc<Output> arc = getArc(io.input.length);
// Don't force rewind based on term length; we rewind below based on ord:
targetBeforeCurrentLength = Integer.MAX_VALUE;
currentFrame = pushFrame(arc, io.output, io.input.length);
if (currentFrame.termOrd > targetOrd) {
//System.out.println(" do rewind: " + currentFrame.termOrd);
currentFrame.rewind();
}
currentFrame.scanToFloorFrame(targetOrd);
currentFrame.loadBlock();
// System.out.println(" after loadBlock termOrd=" + currentFrame.termOrd + " vs " + targetOrd);
while (currentFrame.termOrd <= targetOrd) {
currentFrame.next();
}
assert currentFrame.termOrd == targetOrd+1: "currentFrame.termOrd=" + currentFrame.termOrd + " vs ord=" + targetOrd;
assert termExists;
// Leave enum fully unpositioned, because we didn't set frames for each byte leading up to current term:
validIndexPrefix = 0;
positioned = false;
}
@Override
public String toString() {
return "OrdsSegmentTermsEnum(seg=" + fr.parent + ")";
}
/** Holds a single input (IntsRef) + output pair. */
private static class InputOutput {
public IntsRef input;
public Output output;
@Override
public String toString() {
return "InputOutput(input=" + input + " output=" + output + ")";
}
}
private final FST.Arc<Output> arc = new FST.Arc<>();
// TODO: this is similar to Util.getByOutput ... can we refactor/share?
/** Specialized getByOutput that can understand the ranges (startOrd to endOrd) we use here, not just startOrd. */
private InputOutput getByOutput(long targetOrd) throws IOException {
final IntsRefBuilder result = new IntsRefBuilder();
fr.index.getFirstArc(arc);
Output output = arc.output;
int upto = 0;
int bestUpto = 0;
Output bestOutput = null;
/*
Writer w = new OutputStreamWriter(new FileOutputStream("/tmp/out.dot"));
Util.toDot(fr.index, w, true, true);
w.close();
*/
// System.out.println("reverseLookup seg=" + fr.parent.segment + " output=" + targetOrd);
while (true) {
// System.out.println(" loop: output=" + output.startOrd + "-" + (Long.MAX_VALUE-output.endOrd) + " upto=" + upto + " arc=" + arc + " final?=" + arc.isFinal());
if (arc.isFinal()) {
final Output finalOutput = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.nextFinalOutput);
// System.out.println(" isFinal: " + finalOutput.startOrd + "-" + (Long.MAX_VALUE-finalOutput.endOrd));
if (targetOrd >= finalOutput.startOrd && targetOrd <= Long.MAX_VALUE-finalOutput.endOrd) {
// Only one range should match across all arc leaving this node
//assert bestOutput == null;
bestOutput = finalOutput;
bestUpto = upto;
}
}
if (FST.targetHasArcs(arc)) {
// System.out.println(" targetHasArcs");
result.grow(1+upto);
fr.index.readFirstRealTargetArc(arc.target, arc, fstReader);
if (arc.bytesPerArc != 0) {
// System.out.println(" array arcs");
int low = 0;
int high = arc.numArcs-1;
int mid = 0;
//System.out.println("bsearch: numArcs=" + arc.numArcs + " target=" + targetOutput + " output=" + output);
boolean found = false;
while (low <= high) {
mid = (low + high) >>> 1;
fstReader.setPosition(arc.posArcsStart);
fstReader.skipBytes(arc.bytesPerArc*mid);
final byte flags = fstReader.readByte();
fr.index.readLabel(fstReader);
final Output minArcOutput;
if ((flags & FST.BIT_ARC_HAS_OUTPUT) != 0) {
minArcOutput = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, OrdsBlockTreeTermsWriter.FST_OUTPUTS.read(fstReader));
} else {
minArcOutput = output;
}
// System.out.println(" cycle mid=" + mid + " targetOrd=" + targetOrd + " output=" + minArcOutput.startOrd + "-" + (Long.MAX_VALUE-minArcOutput.endOrd));
if (targetOrd > Long.MAX_VALUE-minArcOutput.endOrd) {
low = mid + 1;
} else if (targetOrd < minArcOutput.startOrd) {
high = mid - 1;
} else {
// System.out.println(" found!!");
found = true;
break;
}
}
if (found) {
// Keep recursing
arc.arcIdx = mid-1;
} else {
result.setLength(bestUpto);
InputOutput io = new InputOutput();
io.input = result.get();
io.output = bestOutput;
// System.out.println(" ret0=" + io);
return io;
}
fr.index.readNextRealArc(arc, fstReader);
// Recurse on this arc:
result.setIntAt(upto++, arc.label);
output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);
} else {
// System.out.println(" non-array arc");
while (true) {
// System.out.println(" cycle label=" + arc.label + " output=" + arc.output);
// This is the min output we'd hit if we follow
// this arc:
final Output minArcOutput = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);
long endOrd = Long.MAX_VALUE - minArcOutput.endOrd;
// System.out.println(" endOrd=" + endOrd + " targetOrd=" + targetOrd);
if (targetOrd >= minArcOutput.startOrd && targetOrd <= endOrd) {
// Recurse on this arc:
output = minArcOutput;
result.setIntAt(upto++, arc.label);
break;
} else if (targetOrd < endOrd || arc.isLast()) {
result.setLength(bestUpto);
InputOutput io = new InputOutput();
io.input = result.get();
assert bestOutput != null;
io.output = bestOutput;
// System.out.println(" ret2=" + io);
return io;
} else {
// System.out.println(" next arc");
// Read next arc in this node:
fr.index.readNextRealArc(arc, fstReader);
}
}
}
} else {
result.setLength(bestUpto);
InputOutput io = new InputOutput();
io.input = result.get();
io.output = bestOutput;
// System.out.println(" ret3=" + io);
return io;
}
}
}
}
| 1 | 29,015 | What's the point of this block (and isn't it effectively dead code)? | apache-lucene-solr | java |
@@ -5,7 +5,7 @@ class ForumSessionsController < ApplicationController
def new
sso = DiscourseSignOn.parse(
request.query_string,
- ENV["DISCOURSE_SSO_SECRET"]
+ ENV.fetch("DISCOURSE_SSO_SECRET"),
)
populate_sso_for_current_user(sso)
track_forum_access | 1 | class ForumSessionsController < ApplicationController
before_action :require_login
before_action :must_have_forum_access
def new
sso = DiscourseSignOn.parse(
request.query_string,
ENV["DISCOURSE_SSO_SECRET"]
)
populate_sso_for_current_user(sso)
track_forum_access
redirect_to sso.to_url(Forum.sso_url)
end
private
def must_have_forum_access
unless current_user.has_access_to?(:forum)
redirect_to(
new_subscription_url,
notice: I18n.t(
"products.subscribe_cta",
offering_type: "forum",
subscription_name: I18n.t("shared.upcase")
)
)
end
end
def populate_sso_for_current_user(sso)
sso.email = current_user.email
sso.name = current_user.name
sso.username = current_user.github_username
sso.external_id = current_user.id
sso.sso_secret = ENV["DISCOURSE_SSO_SECRET"]
end
def track_forum_access
analytics.track_accessed_forum
end
end
| 1 | 16,045 | Put a comma after the last parameter of a multiline method call. | thoughtbot-upcase | rb |
@@ -0,0 +1,6 @@
+from dagster import job, SourceHashVersionStrategy
+
+
+@job(version_strategy=SourceHashVersionStrategy())
+def the_job():
+ ... | 1 | 1 | 17,464 | Newline at end of file plz | dagster-io-dagster | py |
|
@@ -18,7 +18,10 @@ package v1alpha3
import (
"fmt"
+ "github.com/aws/aws-sdk-go/aws"
+ "k8s.io/apimachinery/pkg/types"
"reflect"
+ clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3"
)
// Tags defines a map of tags. | 1 | /*
Copyright 2019 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 v1alpha3
import (
"fmt"
"reflect"
)
// Tags defines a map of tags.
type Tags map[string]string
// Equals returns true if the tags are equal.
func (t Tags) Equals(other Tags) bool {
return reflect.DeepEqual(t, other)
}
// HasOwned returns true if the tags contains a tag that marks the resource as owned by the cluster from the perspective of this management tooling.
func (t Tags) HasOwned(cluster string) bool {
value, ok := t[ClusterTagKey(cluster)]
return ok && ResourceLifecycle(value) == ResourceLifecycleOwned
}
// HasOwned returns true if the tags contains a tag that marks the resource as owned by the cluster from the perspective of the in-tree cloud provider.
func (t Tags) HasAWSCloudProviderOwned(cluster string) bool {
value, ok := t[ClusterAWSCloudProviderTagKey(cluster)]
return ok && ResourceLifecycle(value) == ResourceLifecycleOwned
}
// GetRole returns the Cluster API role for the tagged resource
func (t Tags) GetRole() string {
return t[NameAWSClusterAPIRole]
}
// Difference returns the difference between this map of tags and the other map of tags.
// Items are considered equals if key and value are equals.
func (t Tags) Difference(other Tags) Tags {
res := make(Tags, len(t))
for key, value := range t {
if otherValue, ok := other[key]; ok && value == otherValue {
continue
}
res[key] = value
}
return res
}
// Merge merges in tags from other. If a tag already exists, it is replaced by the tag in other.
func (t Tags) Merge(other Tags) {
for k, v := range other {
t[k] = v
}
}
// ResourceLifecycle configures the lifecycle of a resource
type ResourceLifecycle string
const (
// ResourceLifecycleOwned is the value we use when tagging resources to indicate
// that the resource is considered owned and managed by the cluster,
// and in particular that the lifecycle is tied to the lifecycle of the cluster.
ResourceLifecycleOwned = ResourceLifecycle("owned")
// ResourceLifecycleShared is the value we use when tagging resources to indicate
// that the resource is shared between multiple clusters, and should not be destroyed
// if the cluster is destroyed.
ResourceLifecycleShared = ResourceLifecycle("shared")
// NameKubernetesClusterPrefix is the tag name used by the cloud provider to logically
// separate independent cluster resources. We use it to identify which resources we expect
// to be permissive about state changes.
// logically independent clusters running in the same AZ.
// The tag key = NameKubernetesAWSCloudProviderPrefix + clusterID
// The tag value is an ownership value
NameKubernetesAWSCloudProviderPrefix = "kubernetes.io/cluster/"
// NameAWSProviderPrefix is the tag prefix we use to differentiate
// cluster-api-provider-aws owned components from other tooling that
// uses NameKubernetesClusterPrefix
NameAWSProviderPrefix = "sigs.k8s.io/cluster-api-provider-aws/"
// NameAWSProviderOwned is the tag name we use to differentiate
// cluster-api-provider-aws owned components from other tooling that
// uses NameKubernetesClusterPrefix
NameAWSProviderOwned = NameAWSProviderPrefix + "cluster/"
// NameAWSClusterAPIRole is the tag name we use to mark roles for resources
// dedicated to this cluster api provider implementation.
NameAWSClusterAPIRole = NameAWSProviderPrefix + "role"
// APIServerRoleTagValue describes the value for the apiserver role
APIServerRoleTagValue = "apiserver"
// BastionRoleTagValue describes the value for the bastion role
BastionRoleTagValue = "bastion"
// CommonRoleTagValue describes the value for the common role
CommonRoleTagValue = "common"
// PublicRoleTagValue describes the value for the public role
PublicRoleTagValue = "public"
// PrivateRoleTagValue describes the value for the private role
PrivateRoleTagValue = "private"
)
// ClusterTagKey generates the key for resources associated with a cluster.
func ClusterTagKey(name string) string {
return fmt.Sprintf("%s%s", NameAWSProviderOwned, name)
}
// ClusterAWSCloudProviderTagKey generates the key for resources associated a cluster's AWS cloud provider.
func ClusterAWSCloudProviderTagKey(name string) string {
return fmt.Sprintf("%s%s", NameKubernetesAWSCloudProviderPrefix, name)
}
// BuildParams is used to build tags around an aws resource.
type BuildParams struct {
// Lifecycle determines the resource lifecycle.
Lifecycle ResourceLifecycle
// ClusterName is the cluster associated with the resource.
ClusterName string
// ResourceID is the unique identifier of the resource to be tagged.
ResourceID string
// Name is the name of the resource, it's applied as the tag "Name" on AWS.
// +optional
Name *string
// Role is the role associated to the resource.
// +optional
Role *string
// Any additional tags to be added to the resource.
// +optional
Additional Tags
}
// Build builds tags including the cluster tag and returns them in map form.
func Build(params BuildParams) Tags {
tags := make(Tags)
for k, v := range params.Additional {
tags[k] = v
}
tags[ClusterTagKey(params.ClusterName)] = string(params.Lifecycle)
if params.Role != nil {
tags[NameAWSClusterAPIRole] = *params.Role
}
if params.Name != nil {
tags["Name"] = *params.Name
}
return tags
}
| 1 | 16,736 | Can this be refactored to avoid including the aws sdk in the types that we expose? I know it's not being exposed directly through the types we expose, but I do worry that it might make it easier to accidentally do that in the future and not realize it as easily. | kubernetes-sigs-cluster-api-provider-aws | go |
@@ -1028,4 +1028,18 @@ class Queue
]
);
}
+
+ /**
+ * Sets the timestamp of when an item last has been indexed.
+ *
+ * @param Item $item
+ */
+ public function updateIndexQueueByItem(Item $item)
+ {
+ $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
+ 'tx_solr_indexqueue_item',
+ 'uid = ' . (int)$item->getIndexQueueUid(),
+ ['indexed' => time()]
+ );
+ }
} | 1 | <?php
namespace ApacheSolrForTypo3\Solr\IndexQueue;
/***************************************************************
* Copyright notice
*
* (c) 2009-2015 Ingo Renner <[email protected]>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project 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.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\ConfigurationAwareRecordService;
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\RootPageResolver;
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\Statistic\QueueStatistic;
use ApacheSolrForTypo3\Solr\Site;
use ApacheSolrForTypo3\Solr\System\Cache\TwoLevelCache;
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
use ApacheSolrForTypo3\Solr\Util;
use ApacheSolrForTypo3\Solr\Utility\DatabaseUtility;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* The Indexing Queue. It allows us to decouple from frontend indexing and
* reacting to changes faster.
*
* @author Ingo Renner <[email protected]>
*/
class Queue
{
/**
* @var RootPageResolver
*/
protected $rootPageResolver;
/**
* @var ConfigurationAwareRecordService
*/
protected $recordService;
/**
* @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
*/
protected $logger = null;
/**
* Queue constructor.
* @param RootPageResolver|null $rootPageResolver
* @param ConfigurationAwareRecordService|null $recordService
*/
public function __construct(RootPageResolver $rootPageResolver = null, ConfigurationAwareRecordService $recordService = null)
{
$this->logger = GeneralUtility::makeInstance(SolrLogManager::class, __CLASS__);
$this->rootPageResolver = isset($rootPageResolver) ? $rootPageResolver : GeneralUtility::makeInstance(RootPageResolver::class);
$this->recordService = isset($recordService) ? $recordService : GeneralUtility::makeInstance(ConfigurationAwareRecordService::class);
}
// FIXME some of the methods should be renamed to plural forms
// FIXME singular form methods should deal with exactly one item only
/**
* Returns the timestamp of the last indexing run.
*
* @param int $rootPageId The root page uid for which to get
* the last indexed item id
* @return int Timestamp of last index run.
*/
public function getLastIndexTime($rootPageId)
{
$lastIndexTime = 0;
$lastIndexedRow = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'indexed',
'tx_solr_indexqueue_item',
'root = ' . (int)$rootPageId,
'',
'indexed DESC',
1
);
if ($lastIndexedRow[0]['indexed']) {
$lastIndexTime = $lastIndexedRow[0]['indexed'];
}
return $lastIndexTime;
}
/**
* Returns the uid of the last indexed item in the queue
*
* @param int $rootPageId The root page uid for which to get
* the last indexed item id
* @return int The last indexed item's ID.
*/
public function getLastIndexedItemId($rootPageId)
{
$lastIndexedItemId = 0;
$lastIndexedItemRow = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'uid',
'tx_solr_indexqueue_item',
'root = ' . (int)$rootPageId,
'',
'indexed DESC',
1
);
if ($lastIndexedItemRow[0]['uid']) {
$lastIndexedItemId = $lastIndexedItemRow[0]['uid'];
}
return $lastIndexedItemId;
}
/**
* Truncate and rebuild the tx_solr_indexqueue_item table. This is the most
* complete way to force reindexing, or to build the Index Queue for the
* first time. The Index Queue initialization is site-specific.
*
* @param Site $site The site to initialize
* @param string $indexingConfigurationName Name of a specific
* indexing configuration
* @return array An array of booleans, each representing whether the
* initialization for an indexing configuration was successful
*/
public function initialize(Site $site, $indexingConfigurationName = '')
{
$indexingConfigurations = [];
$initializationStatus = [];
if (empty($indexingConfigurationName)) {
$solrConfiguration = $site->getSolrConfiguration();
$indexingConfigurations = $solrConfiguration->getEnabledIndexQueueConfigurationNames();
} else {
$indexingConfigurations[] = $indexingConfigurationName;
}
foreach ($indexingConfigurations as $indexingConfigurationName) {
$initializationStatus[$indexingConfigurationName] = $this->initializeIndexingConfiguration(
$site,
$indexingConfigurationName
);
}
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessIndexQueueInitialization'])) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessIndexQueueInitialization'] as $classReference) {
$indexQueueInitializationPostProcessor = GeneralUtility::getUserObj($classReference);
if ($indexQueueInitializationPostProcessor instanceof InitializationPostProcessor) {
$indexQueueInitializationPostProcessor->postProcessIndexQueueInitialization(
$site,
$indexingConfigurations,
$initializationStatus
);
} else {
throw new \UnexpectedValueException(
get_class($indexQueueInitializationPostProcessor) .
' must implement interface ' . InitializationPostProcessor::class,
1345815561
);
}
}
}
return $initializationStatus;
}
/**
* Initializes the Index Queue for a specific indexing configuration.
*
* @param Site $site The site to initialize
* @param string $indexingConfigurationName name of a specific
* indexing configuration
* @return bool TRUE if the initialization was successful, FALSE otherwise
*/
protected function initializeIndexingConfiguration(
Site $site,
$indexingConfigurationName
) {
// clear queue
$this->deleteItemsBySite($site, $indexingConfigurationName);
$solrConfiguration = $site->getSolrConfiguration();
$tableToIndex = $solrConfiguration->getIndexQueueTableNameOrFallbackToConfigurationName($indexingConfigurationName);
$initializerClass = $solrConfiguration->getIndexQueueInitializerClassByConfigurationName($indexingConfigurationName);
$initializer = GeneralUtility::makeInstance($initializerClass);
/** @var $initializer \ApacheSolrForTypo3\Solr\IndexQueue\Initializer\AbstractInitializer */
$initializer->setSite($site);
$initializer->setType($tableToIndex);
$initializer->setIndexingConfigurationName($indexingConfigurationName);
$indexConfiguration = $solrConfiguration->getIndexQueueConfigurationByName($indexingConfigurationName);
$initializer->setIndexingConfiguration($indexConfiguration);
return $initializer->initialize();
}
/**
* Gets the indexing configuration to use for an item.
* Sometimes, when there are multiple configurations for a certain item type
* (table) it can be hard or even impossible to find which one to use
* though.
* Currently selects the first indexing configuration where the name matches
* the itemType or where the configured tbale is the same as the itemType.
*
* !!! Might return incorrect results for complex configurations !!!
* Try to set the indexingConfiguration directly when using the updateItem()
* method in such situations.
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @param int $rootPageId The configuration's page tree's root page id.
* Optional, not needed for all types.
* @return string The indexing configuration's name to use when indexing
* @deprecated since 6.1 will be removed in 7.0
* Use getIndexingConfigurationsByItem() now, which behaves
* almost the same way but returns an array of configurations
*/
protected function getIndexingConfigurationByItem(
$itemType,
$itemUid,
$rootPageId = null
) {
GeneralUtility::logDeprecatedFunction();
$indexingConfigurationName = '';
$configurations = $this->getIndexingConfigurationsByItem($itemType, $rootPageId);
if (count($configurations) > 0) {
$indexingConfigurationName = $configurations[0];
}
return $indexingConfigurationName;
}
/**
* Gets the indexing configurations to use for an item.
* Multiple configurations for a certain item type (table) might be available.
*
* @param string $itemType The item's type, usually a table name.
* @param int $rootPageId The configuration's page tree's root page id.
* Optional, not needed for all types.
* @return array<string> The indexing configurations names to use when indexing
* @deprecated since 6.1 will be removed in 7.0
*/
protected function getIndexingConfigurationsByItem(
$itemType,
$rootPageId = null
) {
GeneralUtility::logDeprecatedFunction();
$possibleIndexingConfigurationNames = [];
if (!is_null($rootPageId)) {
// get configuration for the root's branch
$solrConfiguration = Util::getSolrConfigurationFromPageId($rootPageId);
$possibleIndexingConfigurationNames = $solrConfiguration->getIndexQueueConfigurationNamesByTableName($itemType);
}
return $possibleIndexingConfigurationNames;
}
/**
* Marks an item as needing (re)indexing.
*
* Like with Solr itself, there's no add method, just a simple update method
* that handles the adds, too.
*
* The method creates or updates the index queue items for all related rootPageIds.
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @param int $forcedChangeTime The change time for the item if set, otherwise
* value from getItemChangedTime() is used.
*/
public function updateItem($itemType, $itemUid, $forcedChangeTime = 0)
{
$rootPageIds = $this->rootPageResolver->getResponsibleRootPageIds($itemType, $itemUid);
foreach ($rootPageIds as $rootPageId) {
$skipInvalidRootPage = $rootPageId === 0;
if ($skipInvalidRootPage) {
continue;
}
$solrConfiguration = Util::getSolrConfigurationFromPageId($rootPageId);
$indexingConfiguration = $this->recordService->getIndexingConfigurationName($itemType, $itemUid, $solrConfiguration);
$itemInQueueForRootPage = $this->containsItemWithRootPageId($itemType, $itemUid, $rootPageId);
if ($itemInQueueForRootPage) {
// update the existing queue item
$this->updateExistingItem($itemType, $itemUid, $indexingConfiguration, $rootPageId, $forcedChangeTime);
} else {
// add the item since it's not in the queue yet
$this->addNewItem($itemType, $itemUid, $indexingConfiguration, $rootPageId);
}
}
}
/**
* Finds indexing errors for the current site
*
* @param Site $site
* @return array Error items for the current site's Index Queue
*/
public function getErrorsBySite(Site $site)
{
return $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'uid, item_type, item_uid, errors',
'tx_solr_indexqueue_item',
'errors NOT LIKE "" AND root = ' . $site->getRootPageId()
);
}
/**
* Resets all the errors for all index queue items.
*
* @return mixed
*/
public function resetAllErrors()
{
return $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
'tx_solr_indexqueue_item',
'errors NOT LIKE ""',
['errors' => '']
);
}
/**
* Updates an existing queue entry by $itemType $itemUid and $rootPageId.
*
* @param string $itemType The item's type, usually a table name.
* @param int $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @param string $indexingConfiguration The name of the related indexConfiguration
* @param int $rootPageId The uid of the rootPage
* @param int $forcedChangeTime The forced change time that should be used for updating
*/
protected function updateExistingItem($itemType, $itemUid, $indexingConfiguration, $rootPageId, $forcedChangeTime)
{
// update if that item is in the queue already
$changes = [
'changed' => ($forcedChangeTime > 0) ? $forcedChangeTime : $this->getItemChangedTime($itemType, $itemUid)
];
if (!empty($indexingConfiguration)) {
$changes['indexing_configuration'] = $indexingConfiguration;
}
$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
'tx_solr_indexqueue_item',
'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType, 'tx_solr_indexqueue_item') .
' AND item_uid = ' . (int)$itemUid . ' AND root = ' . (int)$rootPageId,
$changes);
}
/**
* Adds an item to the index queue.
*
* Not meant for public use.
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @param string $indexingConfiguration The item's indexing configuration to use.
* Optional, overwrites existing / determined configuration.
* @return void
*/
private function addNewItem($itemType, $itemUid, $indexingConfiguration, $rootPageId)
{
$additionalRecordFields = '';
if ($itemType == 'pages') {
$additionalRecordFields = ', doktype, uid';
}
$record = $this->getRecordCached($itemType, $itemUid, $additionalRecordFields);
if (empty($record) || ($itemType == 'pages' && !Util::isAllowedPageType($record, $indexingConfiguration))) {
return;
}
$item = [
'root' => $rootPageId,
'item_type' => $itemType,
'item_uid' => $itemUid,
'changed' => $this->getItemChangedTime($itemType, $itemUid),
'errors' => ''
];
// make a backup of the current item
$item['indexing_configuration'] = $indexingConfiguration;
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_solr_indexqueue_item', $item);
}
/**
* Get record to be added in addNewItem
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @param string $additionalRecordFields for sql-query
*
* @return array|NULL
*/
protected function getRecordCached($itemType, $itemUid, $additionalRecordFields)
{
$cache = GeneralUtility::makeInstance(TwoLevelCache::class, 'cache_runtime');
$cacheId = md5('Queue' . ':' . 'getRecordCached' . ':' . $itemType . ':' . $itemUid . ':' . 'pid' . $additionalRecordFields);
$record = $cache->get($cacheId);
if (empty($record)) {
$record = BackendUtility::getRecord($itemType, $itemUid, 'pid' . $additionalRecordFields);
$cache->set($cacheId, $record);
}
return $record;
}
/**
* Determines the time for when an item should be indexed. This timestamp
* is then stored in the changed column in the Index Queue.
*
* The changed timestamp usually is now - time(). For records which are set
* to published at a later time, this timestamp is the start time. So if a
* future start time has been set, that will be used to delay indexing
* of an item.
*
* @param string $itemType The item's table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @return int Timestamp of the item's changed time or future start time
*/
protected function getItemChangedTime($itemType, $itemUid)
{
$itemTypeHasStartTimeColumn = false;
$changedTimeColumns = $GLOBALS['TCA'][$itemType]['ctrl']['tstamp'];
$startTime = 0;
$pageChangedTime = 0;
if (!empty($GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime'])) {
$itemTypeHasStartTimeColumn = true;
$changedTimeColumns .= ', ' . $GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime'];
}
if ($itemType == 'pages') {
// does not carry time information directly, but needed to support
// canonical pages
$changedTimeColumns .= ', content_from_pid';
}
$record = BackendUtility::getRecord($itemType, $itemUid, $changedTimeColumns);
$itemChangedTime = $record[$GLOBALS['TCA'][$itemType]['ctrl']['tstamp']];
if ($itemTypeHasStartTimeColumn) {
$startTime = $record[$GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime']];
}
if ($itemType == 'pages') {
$record['uid'] = $itemUid;
// overrule the page's last changed time with the most recent
//content element change
$pageChangedTime = $this->getPageItemChangedTime($record);
}
$localizationsChangedTime = $this->getLocalizableItemChangedTime($itemType, $itemUid);
// if start time exists and start time is higher than last changed timestamp
// then set changed to the future start time to make the item
// indexed at a later time
$changedTime = max(
$itemChangedTime,
$pageChangedTime,
$localizationsChangedTime,
$startTime
);
return $changedTime;
}
/**
* Gets the most recent changed time of a page's content elements
*
* @param array $page Partial page record
* @return int Timestamp of the most recent content element change
*/
protected function getPageItemChangedTime(array $page)
{
if (!empty($page['content_from_pid'])) {
// canonical page, get the original page's last changed time
$pageContentLastChangedTime = $this->getPageItemChangedTime(['uid' => $page['content_from_pid']]);
} else {
$pageContentLastChangedTime = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
'MAX(tstamp) AS changed_time',
'tt_content',
'pid = ' . (int)$page['uid']
);
$pageContentLastChangedTime = $pageContentLastChangedTime['changed_time'];
}
return $pageContentLastChangedTime;
}
/**
* Gets the most recent changed time for an item taking into account
* localized records.
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @return int Timestamp of the most recent content element change
*/
protected function getLocalizableItemChangedTime($itemType, $itemUid)
{
$localizedChangedTime = 0;
if (isset($GLOBALS['TCA'][$itemType]['ctrl']['transOrigPointerField'])) {
// table is localizable
$translationOriginalPointerField = $GLOBALS['TCA'][$itemType]['ctrl']['transOrigPointerField'];
$itemUid = intval($itemUid);
$localizedChangedTime = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
'MAX(tstamp) AS changed_time',
$itemType,
"uid = $itemUid OR $translationOriginalPointerField = $itemUid"
);
$localizedChangedTime = $localizedChangedTime['changed_time'];
}
return $localizedChangedTime;
}
/**
* Checks whether the Index Queue contains a specific item.
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @return bool TRUE if the item is found in the queue, FALSE otherwise
*/
public function containsItem($itemType, $itemUid)
{
$itemIsInQueue = (boolean)$GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
'uid',
'tx_solr_indexqueue_item',
'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
'tx_solr_indexqueue_item') .
' AND item_uid = ' . (int)$itemUid
);
return $itemIsInQueue;
}
/**
* Checks whether the Index Queue contains a specific item.
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @param integer $rootPageId
* @return bool TRUE if the item is found in the queue, FALSE otherwise
*/
public function containsItemWithRootPageId($itemType, $itemUid, $rootPageId)
{
$itemIsInQueue = (boolean)$GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
'uid',
'tx_solr_indexqueue_item',
'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
'tx_solr_indexqueue_item') .
' AND item_uid = ' . (int)$itemUid . ' AND root = ' . (int)$rootPageId
);
return $itemIsInQueue;
}
/**
* Checks whether the Index Queue contains a specific item that has been
* marked as indexed.
*
* @param string $itemType The item's type, usually a table name.
* @param string $itemUid The item's uid, usually an integer uid, could be a
* different value for non-database-record types.
* @return bool TRUE if the item is found in the queue and marked as
* indexed, FALSE otherwise
*/
public function containsIndexedItem($itemType, $itemUid)
{
$itemIsInQueue = (boolean)$GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
'uid',
'tx_solr_indexqueue_item',
'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
'tx_solr_indexqueue_item') .
' AND item_uid = ' . (int)$itemUid .
' AND indexed > 0'
);
return $itemIsInQueue;
}
/**
* Removes an item from the Index Queue.
*
* @param string $itemType The type of the item to remove, usually a table name.
* @param int $itemUid The uid of the item to remove
*/
public function deleteItem($itemType, $itemUid)
{
$uidList = [];
// get the item uids to use them in the deletes afterwards
$items = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'uid',
'tx_solr_indexqueue_item',
'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
'tx_solr_indexqueue_item') .
' AND item_uid = ' . intval($itemUid)
);
if (count($items)) {
foreach ($items as $item) {
$uidList[] = $item['uid'];
}
$GLOBALS['TYPO3_DB']->exec_DELETEquery(
'tx_solr_indexqueue_item',
'uid IN(' . implode(',', $uidList) . ')'
);
$GLOBALS['TYPO3_DB']->exec_DELETEquery(
'tx_solr_indexqueue_indexing_property',
'item_id IN(' . implode(',', $uidList) . ')'
);
}
}
/**
* Removes all items of a certain type from the Index Queue.
*
* @param string $itemType The type of items to remove, usually a table name.
*/
public function deleteItemsByType($itemType)
{
$uidList = [];
// get the item uids to use them in the deletes afterwards
$items = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'uid',
'tx_solr_indexqueue_item',
'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr(
$itemType,
'tx_solr_indexqueue_item'
)
);
if (count($items)) {
foreach ($items as $item) {
$uidList[] = $item['uid'];
}
$GLOBALS['TYPO3_DB']->exec_DELETEquery(
'tx_solr_indexqueue_item',
'uid IN(' . implode(',', $uidList) . ')'
);
$GLOBALS['TYPO3_DB']->exec_DELETEquery(
'tx_solr_indexqueue_indexing_property',
'item_id IN(' . implode(',', $uidList) . ')'
);
}
}
/**
* Removes all items of a certain site from the Index Queue. Accepts an
* optional parameter to limit the deleted items by indexing configuration.
*
* @param Site $site The site to remove items for.
* @param string $indexingConfigurationName Name of a specific indexing
* configuration
*/
public function deleteItemsBySite(
Site $site,
$indexingConfigurationName = ''
) {
$rootPageConstraint = 'tx_solr_indexqueue_item.root = ' . $site->getRootPageId();
$indexingConfigurationConstraint = '';
if (!empty($indexingConfigurationName)) {
$indexingConfigurationConstraint =
' AND tx_solr_indexqueue_item.indexing_configuration = \'' .
$indexingConfigurationName . '\'';
}
DatabaseUtility::transactionStart();
try {
// reset Index Queue
$result = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
'tx_solr_indexqueue_item',
$rootPageConstraint . $indexingConfigurationConstraint
);
if (!$result) {
throw new \RuntimeException(
'Failed to reset Index Queue for site ' . $site->getLabel(),
1412986560
);
}
// reset Index Queue Properties
$indexQueuePropertyResetQuery = '
DELETE tx_solr_indexqueue_indexing_property.*
FROM tx_solr_indexqueue_indexing_property
INNER JOIN tx_solr_indexqueue_item
ON tx_solr_indexqueue_item.uid = tx_solr_indexqueue_indexing_property.item_id
AND ' .
$rootPageConstraint .
$indexingConfigurationConstraint;
$result = $GLOBALS['TYPO3_DB']->sql_query($indexQueuePropertyResetQuery);
if (!$result) {
throw new \RuntimeException(
'Failed to reset Index Queue properties for site ' . $site->getLabel(),
1412986604
);
}
DatabaseUtility::transactionCommit();
} catch (\RuntimeException $e) {
DatabaseUtility::transactionRollback();
}
}
/**
* Removes all items from the Index Queue.
*
*/
public function deleteAllItems()
{
$GLOBALS['TYPO3_DB']->exec_TRUNCATEquery('tx_solr_indexqueue_item', '');
}
/**
* Gets a single Index Queue item by its uid.
*
* @param int $itemId Index Queue item uid
* @return Item The request Index Queue item or NULL
* if no item with $itemId was found
*/
public function getItem($itemId)
{
$item = null;
$indexQueueItemRecord = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'*',
'tx_solr_indexqueue_item',
'uid = ' . intval($itemId)
);
if (count($indexQueueItemRecord) == 1) {
$indexQueueItemRecord = $indexQueueItemRecord[0];
$item = GeneralUtility::makeInstance(
Item::class,
$indexQueueItemRecord
);
}
return $item;
}
/**
* Gets Index Queue items by type and uid.
*
* @param string $itemType item type, usually the table name
* @param int $itemUid item uid
* @return Item[] An array of items matching $itemType and $itemUid
*/
public function getItems($itemType, $itemUid)
{
$indexQueueItemRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'*',
'tx_solr_indexqueue_item',
'item_type = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($itemType,
'tx_solr_indexqueue_item') .
' AND item_uid = ' . intval($itemUid)
);
return $this->getIndexQueueItemObjectsFromRecords($indexQueueItemRecords);
}
/**
* Gets number of Index Queue items for a specific site / indexing configuration
* optional parameter to limit the counted items by indexing configuration.
*
* @param Site $site The site to search for.
* @param string $indexingConfigurationName name of a specific indexing
* configuration
* @deprecated since 6.1 will be removed in 7.0 use getStatisticsBySite()->getTotalCount() please
* @return int Number of items
*/
public function getItemsCountBySite(Site $site, $indexingConfigurationName = '')
{
GeneralUtility::logDeprecatedFunction();
return (int) $this->getStatisticsBySite($site, $indexingConfigurationName)->getTotalCount();
}
/**
* Gets number of unprocessed Index Queue items for a specific site / indexing configuration
* optional parameter to limit the counted items by indexing configuration.
*
* @param Site $site The site to search for.
* @param string $indexingConfigurationName name of a specific indexing
* configuration
* @deprecated since 6.1 will be removed in 7.0 use getStatisticsBySite()->getPendingCount() please
* @return int Number of items.
*/
public function getRemainingItemsCountBySite(Site $site, $indexingConfigurationName = '')
{
GeneralUtility::logDeprecatedFunction();
return (int) $this->getStatisticsBySite($site, $indexingConfigurationName)->getPendingCount();
}
/**
* Returns the number of items for all queues.
*
* @return int
*/
public function getAllItemsCount()
{
return $this->getItemCount();
}
/**
* @param string $where
* @return int
*/
private function getItemCount($where = '1=1')
{
/** @var $db \TYPO3\CMS\Core\Database\DatabaseConnection */
$db = $GLOBALS['TYPO3_DB'];
return (int)$db->exec_SELECTcountRows('uid', 'tx_solr_indexqueue_item', $where);
}
/**
* Extracts the number of pending, indexed and erroneous items from the
* Index Queue.
*
* @param Site $site
* @param string $indexingConfigurationName
*
* @return QueueStatistic
*/
public function getStatisticsBySite(Site $site, $indexingConfigurationName = '')
{
$indexingConfigurationConstraint = $this->buildIndexConfigurationConstraint($indexingConfigurationName);
$where = 'root = ' . (int)$site->getRootPageId() . $indexingConfigurationConstraint;
$indexQueueStats = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'indexed < changed as pending,'
. '(errors not like "") as failed,'
. 'COUNT(*) as count',
'tx_solr_indexqueue_item',
$where,
'pending, failed'
);
/** @var $statistic QueueStatistic */
$statistic = GeneralUtility::makeInstance(QueueStatistic::class);
foreach ($indexQueueStats as $row) {
if ($row['failed'] == 1) {
$statistic->setFailedCount((int) $row['count']);
} elseif ($row['pending'] == 1) {
$statistic->setPendingCount((int) $row['count']);
} else {
$statistic->setSuccessCount((int) $row['count']);
}
}
return $statistic;
}
/**
* Build a database constraint that limits to a certain indexConfigurationName
*
* @param string $indexingConfigurationName
* @return string
*/
protected function buildIndexConfigurationConstraint($indexingConfigurationName)
{
$indexingConfigurationConstraint = '';
if (!empty($indexingConfigurationName)) {
$indexingConfigurationConstraint = ' AND indexing_configuration = \'' . $indexingConfigurationName . '\'';
return $indexingConfigurationConstraint;
}
return $indexingConfigurationConstraint;
}
/**
* Gets $limit number of items to index for a particular $site.
*
* @param Site $site TYPO3 site
* @param int $limit Number of items to get from the queue
* @return Item[] Items to index to the given solr server
*/
public function getItemsToIndex(Site $site, $limit = 50)
{
$itemsToIndex = [];
// determine which items to index with this run
$indexQueueItemRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'*',
'tx_solr_indexqueue_item',
'root = ' . $site->getRootPageId() .
' AND changed > indexed' .
' AND changed <= ' . time() .
' AND errors = \'\'',
'',
'indexing_priority DESC, changed DESC, uid DESC',
intval($limit)
);
if (!empty($indexQueueItemRecords)) {
// convert queued records to index queue item objects
$itemsToIndex = $this->getIndexQueueItemObjectsFromRecords($indexQueueItemRecords);
}
return $itemsToIndex;
}
/**
* Creates an array of ApacheSolrForTypo3\Solr\IndexQueue\Item objects from an array of
* index queue records.
*
* @param array $indexQueueItemRecords Array of plain index queue records
* @return array Array of ApacheSolrForTypo3\Solr\IndexQueue\Item objects
*/
protected function getIndexQueueItemObjectsFromRecords(
array $indexQueueItemRecords
) {
$indexQueueItems = [];
$tableUids = [];
$tableRecords = [];
// grouping records by table
foreach ($indexQueueItemRecords as $indexQueueItemRecord) {
$tableUids[$indexQueueItemRecord['item_type']][] = $indexQueueItemRecord['item_uid'];
}
// fetching records by table, saves us a lot of single queries
foreach ($tableUids as $table => $uids) {
$uidList = implode(',', $uids);
$records = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'*',
$table,
'uid IN(' . $uidList . ')',
'', '', '', // group, order, limit
'uid'
);
$tableRecords[$table] = $records;
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessFetchRecordsForIndexQueueItem'])) {
$params = ['table' => $table, 'uids' => $uids, 'tableRecords' => &$tableRecords];
foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessFetchRecordsForIndexQueueItem'] as $reference) {
GeneralUtility::callUserFunction($reference, $params, $this);
}
unset($params);
}
}
// creating index queue item objects and assigning / mapping
// records to index queue items
foreach ($indexQueueItemRecords as $indexQueueItemRecord) {
if (isset($tableRecords[$indexQueueItemRecord['item_type']][$indexQueueItemRecord['item_uid']])) {
$indexQueueItems[] = GeneralUtility::makeInstance(
Item::class,
$indexQueueItemRecord,
$tableRecords[$indexQueueItemRecord['item_type']][$indexQueueItemRecord['item_uid']]
);
} else {
$this->logger->log(
SolrLogManager::ERROR,
'Record missing for Index Queue item. Item removed.',
[
$indexQueueItemRecord
]
);
$this->deleteItem($indexQueueItemRecord['item_type'],
$indexQueueItemRecord['item_uid']);
}
}
return $indexQueueItems;
}
/**
* Marks an item as failed and causes the indexer to skip the item in the
* next run.
*
* @param int|Item $item Either the item's Index Queue uid or the complete item
* @param string $errorMessage Error message
*/
public function markItemAsFailed($item, $errorMessage = '')
{
if ($item instanceof Item) {
$itemUid = $item->getIndexQueueUid();
} else {
$itemUid = (int)$item;
}
if (empty($errorMessage)) {
// simply set to "TRUE"
$errorMessage = '1';
}
$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
'tx_solr_indexqueue_item',
'uid = ' . $itemUid,
[
'errors' => $errorMessage
]
);
}
}
| 1 | 6,212 | Hi thomas, i would propose to indicate in the name, that only the indextime is updated, otherwise somebody might think the whole items is getting updated. I would propose something like "updateIndexTimeByItem(Item $item)" | TYPO3-Solr-ext-solr | php |
@@ -95,6 +95,8 @@ class visibility_of(object):
def _element_if_visible(element, visibility=True):
+ if isinstance(element, str) or isinstance(element, dict):
+ raise StaleElementReferenceException("Invalid locator")
return element if element.is_displayed() == visibility else False
| 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.
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchFrameException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import NoAlertPresentException
"""
* Canned "Expected Conditions" which are generally useful within webdriver
* tests.
"""
class title_is(object):
"""An expectation for checking the title of a page.
title is the expected title, which must be an exact match
returns True if the title matches, false otherwise."""
def __init__(self, title):
self.title = title
def __call__(self, driver):
return self.title == driver.title
class title_contains(object):
""" An expectation for checking that the title contains a case-sensitive
substring. title is the fragment of title expected
returns True when the title matches, False otherwise
"""
def __init__(self, title):
self.title = title
def __call__(self, driver):
return self.title in driver.title
class presence_of_element_located(object):
""" An expectation for checking that an element is present on the DOM
of a page. This does not necessarily mean that the element is visible.
locator - used to find the element
returns the WebElement once it is located
"""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
return _find_element(driver, self.locator)
class visibility_of_element_located(object):
""" An expectation for checking that an element is present on the DOM of a
page and visible. Visibility means that the element is not only displayed
but also has a height and width that is greater than 0.
locator - used to find the element
returns the WebElement once it is located and visible
"""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
return _element_if_visible(_find_element(driver, self.locator))
except StaleElementReferenceException:
return False
class visibility_of(object):
""" An expectation for checking that an element, known to be present on the
DOM of a page, is visible. Visibility means that the element is not only
displayed but also has a height and width that is greater than 0.
element is the WebElement
returns the (same) WebElement once it is visible
"""
def __init__(self, element):
self.element = element
def __call__(self, ignored):
return _element_if_visible(self.element)
def _element_if_visible(element, visibility=True):
return element if element.is_displayed() == visibility else False
class presence_of_all_elements_located(object):
""" An expectation for checking that there is at least one element present
on a web page.
locator is used to find the element
returns the list of WebElements once they are located
"""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
return _find_elements(driver, self.locator)
class visibility_of_any_elements_located(object):
""" An expectation for checking that there is at least one element visible
on a web page.
locator is used to find the element
returns the list of WebElements once they are located
"""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
return [element for element in _find_elements(driver, self.locator) if _element_if_visible(element)]
class text_to_be_present_in_element(object):
""" An expectation for checking if the given text is present in the
specified element.
locator, text
"""
def __init__(self, locator, text_):
self.locator = locator
self.text = text_
def __call__(self, driver):
try:
element_text = _find_element(driver, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
class text_to_be_present_in_element_value(object):
"""
An expectation for checking if the given text is present in the element's
locator, text
"""
def __init__(self, locator, text_):
self.locator = locator
self.text = text_
def __call__(self, driver):
try:
element_text = _find_element(driver,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
class frame_to_be_available_and_switch_to_it(object):
""" An expectation for checking whether the given frame is available to
switch to. If the frame is available it switches the given driver to the
specified frame.
"""
def __init__(self, locator):
self.frame_locator = locator
def __call__(self, driver):
try:
if isinstance(self.frame_locator, tuple):
driver.switch_to.frame(_find_element(driver,
self.frame_locator))
else:
driver.switch_to.frame(self.frame_locator)
return True
except NoSuchFrameException:
return False
class invisibility_of_element_located(object):
""" An Expectation for checking that an element is either invisible or not
present on the DOM.
locator used to find the element
"""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
return _element_if_visible(_find_element(driver, self.locator), False)
except (NoSuchElementException, StaleElementReferenceException):
# In the case of NoSuchElement, returns true because the element is
# not present in DOM. The try block checks if the element is present
# but is invisible.
# In the case of StaleElementReference, returns true because stale
# element reference implies that element is no longer visible.
return True
class element_to_be_clickable(object):
""" An Expectation for checking an element is visible and enabled such that
you can click it."""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
element = visibility_of_element_located(self.locator)(driver)
if element and element.is_enabled():
return element
else:
return False
class staleness_of(object):
""" Wait until an element is no longer attached to the DOM.
element is the element to wait for.
returns False if the element is still attached to the DOM, true otherwise.
"""
def __init__(self, element):
self.element = element
def __call__(self, ignored):
try:
# Calling any method forces a staleness check
self.element.is_enabled()
return False
except StaleElementReferenceException:
return True
class element_to_be_selected(object):
""" An expectation for checking the selection is selected.
element is WebElement object
"""
def __init__(self, element):
self.element = element
def __call__(self, ignored):
return self.element.is_selected()
class element_located_to_be_selected(object):
"""An expectation for the element to be located is selected.
locator is a tuple of (by, path)"""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
return _find_element(driver, self.locator).is_selected()
class element_selection_state_to_be(object):
""" An expectation for checking if the given element is selected.
element is WebElement object
is_selected is a Boolean."
"""
def __init__(self, element, is_selected):
self.element = element
self.is_selected = is_selected
def __call__(self, ignored):
return self.element.is_selected() == self.is_selected
class element_located_selection_state_to_be(object):
""" An expectation to locate an element and check if the selection state
specified is in that state.
locator is a tuple of (by, path)
is_selected is a boolean
"""
def __init__(self, locator, is_selected):
self.locator = locator
self.is_selected = is_selected
def __call__(self, driver):
try:
element = _find_element(driver, self.locator)
return element.is_selected() == self.is_selected
except StaleElementReferenceException:
return False
class number_of_windows_to_be(object):
""" An expectation for the number of windows to be a certain value."""
def __init__(self, num_windows):
self.num_windows = num_windows
def __call__(self, driver):
return len(driver.window_handles) == self.num_windows
class new_window_is_opened(object):
""" An expectation that a new window will be opened and have the number of
windows handles increase"""
def __init__(self, current_handles):
self.current_handles = current_handles
def __call__(self, driver):
return len(driver.window_handles) > len(self.current_handles)
class alert_is_present(object):
""" Expect an alert to be present."""
def __init__(self):
pass
def __call__(self, driver):
try:
alert = driver.switch_to.alert
alert.text
return alert
except NoAlertPresentException:
return False
def _find_element(driver, by):
"""Looks up an element. Logs and re-raises ``WebDriverException``
if thrown."""
try:
return driver.find_element(*by)
except NoSuchElementException as e:
raise e
except WebDriverException as e:
raise e
def _find_elements(driver, by):
try:
return driver.find_elements(*by)
except WebDriverException as e:
raise e
| 1 | 14,205 | This is not the right exception class. There is an InvalidSelectorException class that covers bad locators. | SeleniumHQ-selenium | js |
@@ -45,6 +45,10 @@
#include <Kokkos_Macros.hpp>
#ifdef KOKKOS_ENABLE_CUDA
+#include <Kokkos_Core.hpp>
+#include <Kokkos_Cuda.hpp>
+#include <Kokkos_CudaSpace.hpp>
+
#include <cstdlib>
#include <iostream>
#include <sstream> | 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 ([email protected])
//
// ************************************************************************
//@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>
#include <impl/Kokkos_Tools.hpp>
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
namespace Kokkos {
namespace Impl {
namespace {
static std::atomic<int> num_uvm_allocations(0);
cudaStream_t get_deep_copy_stream() {
static cudaStream_t s = nullptr;
if (s == nullptr) {
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 : bool { UVM_available = true };
#else
enum : bool { 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 {
return allocate("[unlabeled]", arg_alloc_size);
}
void *CudaSpace::allocate(const char *arg_label, const size_t arg_alloc_size,
const size_t arg_logical_size) const {
return impl_allocate(arg_label, arg_alloc_size, arg_logical_size);
}
void *CudaSpace::impl_allocate(
const char *arg_label, const size_t arg_alloc_size,
const size_t arg_logical_size,
const Kokkos::Tools::SpaceHandle arg_handle) 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);
}
if (Kokkos::Profiling::profileLibraryLoaded()) {
const size_t reported_size =
(arg_logical_size > 0) ? arg_logical_size : arg_alloc_size;
Kokkos::Profiling::allocateData(arg_handle, arg_label, ptr, reported_size);
}
return ptr;
}
void *CudaUVMSpace::allocate(const size_t arg_alloc_size) const {
return allocate("[unlabeled]", arg_alloc_size);
}
void *CudaUVMSpace::allocate(const char *arg_label, const size_t arg_alloc_size,
const size_t arg_logical_size) const {
return impl_allocate(arg_label, arg_alloc_size, arg_logical_size);
}
void *CudaUVMSpace::impl_allocate(
const char *arg_label, const size_t arg_alloc_size,
const size_t arg_logical_size,
const Kokkos::Tools::SpaceHandle arg_handle) 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();
if (Kokkos::Profiling::profileLibraryLoaded()) {
const size_t reported_size =
(arg_logical_size > 0) ? arg_logical_size : arg_alloc_size;
Kokkos::Profiling::allocateData(arg_handle, arg_label, ptr, reported_size);
}
return ptr;
}
void *CudaHostPinnedSpace::allocate(const size_t arg_alloc_size) const {
return allocate("[unlabeled]", arg_alloc_size);
}
void *CudaHostPinnedSpace::allocate(const char *arg_label,
const size_t arg_alloc_size,
const size_t arg_logical_size) const {
return impl_allocate(arg_label, arg_alloc_size, arg_logical_size);
}
void *CudaHostPinnedSpace::impl_allocate(
const char *arg_label, const size_t arg_alloc_size,
const size_t arg_logical_size,
const Kokkos::Tools::SpaceHandle arg_handle) 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);
}
if (Kokkos::Profiling::profileLibraryLoaded()) {
const size_t reported_size =
(arg_logical_size > 0) ? arg_logical_size : arg_alloc_size;
Kokkos::Profiling::allocateData(arg_handle, arg_label, ptr, reported_size);
}
return ptr;
}
// </editor-fold> end allocate() }}}1
//==============================================================================
void CudaSpace::deallocate(void *const arg_alloc_ptr,
const size_t arg_alloc_size) const {
deallocate("[unlabeled]", arg_alloc_ptr, arg_alloc_size);
}
void CudaSpace::deallocate(const char *arg_label, void *const arg_alloc_ptr,
const size_t arg_alloc_size,
const size_t arg_logical_size) const {
impl_deallocate(arg_label, arg_alloc_ptr, arg_alloc_size, arg_logical_size);
}
void CudaSpace::impl_deallocate(
const char *arg_label, void *const arg_alloc_ptr,
const size_t arg_alloc_size, const size_t arg_logical_size,
const Kokkos::Tools::SpaceHandle arg_handle) const {
if (Kokkos::Profiling::profileLibraryLoaded()) {
const size_t reported_size =
(arg_logical_size > 0) ? arg_logical_size : arg_alloc_size;
Kokkos::Profiling::deallocateData(arg_handle, arg_label, arg_alloc_ptr,
reported_size);
}
try {
CUDA_SAFE_CALL(cudaFree(arg_alloc_ptr));
} catch (...) {
}
}
void CudaUVMSpace::deallocate(void *const arg_alloc_ptr,
const size_t arg_alloc_size) const {
deallocate("[unlabeled]", arg_alloc_ptr, arg_alloc_size);
}
void CudaUVMSpace::deallocate(const char *arg_label, void *const arg_alloc_ptr,
const size_t arg_alloc_size
,
const size_t arg_logical_size) const {
impl_deallocate(arg_label, arg_alloc_ptr, arg_alloc_size, arg_logical_size);
}
void CudaUVMSpace::impl_deallocate(
const char *arg_label, void *const arg_alloc_ptr,
const size_t arg_alloc_size
,
const size_t arg_logical_size,
const Kokkos::Tools::SpaceHandle arg_handle) const {
Cuda::impl_static_fence();
if (Kokkos::Profiling::profileLibraryLoaded()) {
const size_t reported_size =
(arg_logical_size > 0) ? arg_logical_size : arg_alloc_size;
Kokkos::Profiling::deallocateData(arg_handle, arg_label, arg_alloc_ptr,
reported_size);
}
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 {
deallocate("[unlabeled]", arg_alloc_ptr, arg_alloc_size);
}
void CudaHostPinnedSpace::deallocate(const char *arg_label,
void *const arg_alloc_ptr,
const size_t arg_alloc_size,
const size_t arg_logical_size) const {
impl_deallocate(arg_label, arg_alloc_ptr, arg_alloc_size, arg_logical_size);
}
void CudaHostPinnedSpace::impl_deallocate(
const char *arg_label, void *const arg_alloc_ptr,
const size_t arg_alloc_size, const size_t arg_logical_size,
const Kokkos::Tools::SpaceHandle arg_handle) const {
if (Kokkos::Profiling::profileLibraryLoaded()) {
const size_t reported_size =
(arg_logical_size > 0) ? arg_logical_size : arg_alloc_size;
Kokkos::Profiling::deallocateData(arg_handle, arg_label, arg_alloc_ptr,
reported_size);
}
try {
CUDA_SAFE_CALL(cudaFreeHost(arg_alloc_ptr));
} catch (...) {
}
}
} // namespace Kokkos
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
#ifdef KOKKOS_ENABLE_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 == nullptr) ||
(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() {
const char *label = nullptr;
if (Kokkos::Profiling::profileLibraryLoaded()) {
SharedAllocationHeader header;
Kokkos::Impl::DeepCopy<Kokkos::CudaSpace, HostSpace>(
&header, RecordBase::m_alloc_ptr, sizeof(SharedAllocationHeader));
label = header.label();
}
auto alloc_size = SharedAllocationRecord<void, void>::m_alloc_size;
m_space.deallocate(label, SharedAllocationRecord<void, void>::m_alloc_ptr,
alloc_size, (alloc_size - sizeof(SharedAllocationHeader)));
}
SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::~SharedAllocationRecord() {
const char *label = nullptr;
if (Kokkos::Profiling::profileLibraryLoaded()) {
label = RecordBase::m_alloc_ptr->m_label;
}
m_space.deallocate(label, SharedAllocationRecord<void, void>::m_alloc_ptr,
SharedAllocationRecord<void, void>::m_alloc_size,
(SharedAllocationRecord<void, void>::m_alloc_size -
sizeof(SharedAllocationHeader)));
}
SharedAllocationRecord<Kokkos::CudaHostPinnedSpace,
void>::~SharedAllocationRecord() {
m_space.deallocate(RecordBase::m_alloc_ptr->m_label,
SharedAllocationRecord<void, void>::m_alloc_ptr,
SharedAllocationRecord<void, void>::m_alloc_size,
(SharedAllocationRecord<void, void>::m_alloc_size -
sizeof(SharedAllocationHeader)));
}
// </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_ENABLE_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) {
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 - 1);
// Set last element zero, in case c_str is too long
header.m_label[SharedAllocationHeader::maximum_label_length - 1] = '\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_ENABLE_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) {
// 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 - 1);
// Set last element zero, in case c_str is too long
RecordBase::m_alloc_ptr
->m_label[SharedAllocationHeader::maximum_label_length - 1] = '\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_ENABLE_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) {
// 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 - 1);
// Set last element zero, in case c_str is too long
RecordBase::m_alloc_ptr
->m_label[SharedAllocationHeader::maximum_label_length - 1] = '\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 nullptr;
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 != nullptr) {
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 nullptr;
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 != nullptr) {
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 nullptr;
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 != nullptr) {
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) : nullptr;
if (alloc_ptr) {
Kokkos::Impl::DeepCopy<HostSpace, CudaSpace>(
&head, head_cuda, sizeof(SharedAllocationHeader));
}
RecordCuda *const record =
alloc_ptr ? static_cast<RecordCuda *>(head.m_record) : nullptr;
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 : nullptr;
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 : nullptr;
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_ENABLE_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_ENABLE_DEBUG enabled");
#endif
}
void SharedAllocationRecord<Kokkos::CudaUVMSpace, void>::print_records(
std::ostream &s, const Kokkos::CudaUVMSpace &, bool detail) {
(void)s;
(void)detail;
#ifdef KOKKOS_ENABLE_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_ENABLE_DEBUG enabled");
#endif
}
void SharedAllocationRecord<Kokkos::CudaHostPinnedSpace, void>::print_records(
std::ostream &s, const Kokkos::CudaHostPinnedSpace &, bool detail) {
(void)s;
(void)detail;
#ifdef KOKKOS_ENABLE_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_ENABLE_DEBUG enabled");
#endif
}
// </editor-fold> end SharedAllocationRecord::print_records() }}}1
//==============================================================================
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 | 26,903 | I assume this came from format? | kokkos-kokkos | cpp |
@@ -56,6 +56,13 @@ class ReIndexTask extends AbstractTask
*/
protected $indexingConfigurationsToReIndex = array();
+ /**
+ * Clear Index for selected sites and record types
+ *
+ * @var boolean
+ */
+ protected $clearSearchIndex;
+
/**
* Purges/commits all Solr indexes, initializes the Index Queue | 1 | <?php
namespace ApacheSolrForTypo3\Solr\Task;
/***************************************************************
* Copyright notice
*
* (c) 2011-2015 Christoph Moeller <[email protected]>
* (c) 2012-2015 Ingo Renner <[email protected]>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project 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.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use ApacheSolrForTypo3\Solr\IndexQueue\Queue;
use ApacheSolrForTypo3\Solr\Site;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Scheduler\Task\AbstractTask;
/**
* Scheduler task to empty the indexes of a site and re-initialize the
* Solr Index Queue thus making the indexer re-index the site.
*
* @author Christoph Moeller <[email protected]>
* @package TYPO3
* @subpackage solr
*/
class ReIndexTask extends AbstractTask
{
/**
* The site this task is supposed to initialize the index queue for.
*
* @var Site
*/
protected $site;
/**
* Indexing configurations to re-initialize.
*
* @var array
*/
protected $indexingConfigurationsToReIndex = array();
/**
* Purges/commits all Solr indexes, initializes the Index Queue
* and returns TRUE if the execution was successful
*
* @return boolean Returns TRUE on success, FALSE on failure.
*/
public function execute()
{
// clean up
$cleanUpResult = $this->cleanUpIndex();
// initialize for re-indexing
$indexQueue = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\IndexQueue\\Queue');
$indexQueueInitializationResults = array();
foreach ($this->indexingConfigurationsToReIndex as $indexingConfigurationName) {
$indexQueueInitializationResults = $indexQueue->initialize($this->site,
$indexingConfigurationName);
}
return ($cleanUpResult && !in_array(false,
$indexQueueInitializationResults));
}
/**
* Removes documents of the selected types from the index.
*
* @return bool TRUE if clean up was successful, FALSE on error
*/
protected function cleanUpIndex()
{
$cleanUpResult = true;
$solrConfiguration = $this->site->getSolrConfiguration();
$solrServers = GeneralUtility::makeInstance('ApacheSolrForTypo3\\Solr\\ConnectionManager')->getConnectionsBySite($this->site);
$typesToCleanUp = array();
foreach ($this->indexingConfigurationsToReIndex as $indexingConfigurationName) {
$type = Queue::getTableToIndexByIndexingConfigurationName(
$solrConfiguration,
$indexingConfigurationName
);
$typesToCleanUp[] = $type;
}
foreach ($solrServers as $solrServer) {
// make sure not-yet committed documents are removed, too
$solrServer->commit();
$deleteQuery = 'type:(' . implode(' OR ', $typesToCleanUp) . ')'
. ' AND siteHash:' . $this->site->getSiteHash();
$solrServer->deleteByQuery($deleteQuery);
$response = $solrServer->commit(false, false, false);
if ($response->getHttpStatus() != 200) {
$cleanUpResult = false;
break;
}
}
return $cleanUpResult;
}
/**
* Gets the site / the site's root page uid this task is running on.
*
* @return Site The site's root page uid this task is optimizing
*/
public function getSite()
{
return $this->site;
}
/**
* Sets the task's site.
*
* @param Site $site The site to be handled by this task
*/
public function setSite(Site $site)
{
$this->site = $site;
}
/**
* Gets the indexing configurations to re-index.
*
* @return array
*/
public function getIndexingConfigurationsToReIndex()
{
return $this->indexingConfigurationsToReIndex;
}
/**
* Sets the indexing configurations to re-index.
*
* @param array $indexingConfigurationsToReIndex
*/
public function setIndexingConfigurationsToReIndex(
array $indexingConfigurationsToReIndex
) {
$this->indexingConfigurationsToReIndex = $indexingConfigurationsToReIndex;
}
/**
* This method is designed to return some additional information about the task,
* that may help to set it apart from other tasks from the same class
* This additional information is used - for example - in the Scheduler's BE module
* This method should be implemented in most task classes
*
* @return string Information to display
*/
public function getAdditionalInformation()
{
$information = '';
if ($this->site) {
$information = 'Site: ' . $this->site->getLabel();
}
if (!empty($this->indexingConfigurationsToReIndex)) {
$information .= ', Indexing Configurations: ' . implode(', ',
$this->indexingConfigurationsToReIndex);
}
return $information;
}
}
| 1 | 6,070 | I'd suggest a default value of `false` just to make sure existing tasks are ok when they get deserialized after an update to a version containing this code. | TYPO3-Solr-ext-solr | php |
@@ -237,6 +237,8 @@ func (km *KeyManagerStandard) getTLFCryptKeyParams(
kbfscrypto.CryptPublicKey{},
localMakeRekeyReadError(err)
}
+ km.log.CDebugf(ctx, "Trying to decrypt with keys = %s",
+ dumpConfig().Sdump(keys))
var index int
clientHalf, index, err = crypto.DecryptTLFCryptKeyClientHalfAny(ctx,
keys, flags&getTLFCryptKeyPromptPaper != 0) | 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 (
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfscrypto"
"github.com/keybase/kbfs/tlf"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// KeyManagerStandard implements the KeyManager interface by fetching
// keys from KeyOps and KBPKI, and computing the complete keys
// necessary to run KBFS.
type KeyManagerStandard struct {
config Config
log logger.Logger
deferLog logger.Logger
}
// NewKeyManagerStandard returns a new KeyManagerStandard
func NewKeyManagerStandard(config Config) *KeyManagerStandard {
log := config.MakeLogger("")
return &KeyManagerStandard{config, log, log.CloneWithAddedDepth(1)}
}
// GetTLFCryptKeyForEncryption implements the KeyManager interface for
// KeyManagerStandard.
func (km *KeyManagerStandard) GetTLFCryptKeyForEncryption(ctx context.Context,
kmd KeyMetadata) (tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
return km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd,
kmd.LatestKeyGeneration(), false)
}
// GetTLFCryptKeyForMDDecryption implements the KeyManager interface
// for KeyManagerStandard.
func (km *KeyManagerStandard) GetTLFCryptKeyForMDDecryption(
ctx context.Context, kmdToDecrypt, kmdWithKeys KeyMetadata) (
tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
return km.getTLFCryptKey(ctx, kmdWithKeys, kmdToDecrypt.LatestKeyGeneration(),
getTLFCryptKeyAnyDevice|getTLFCryptKeyDoCache)
}
// GetTLFCryptKeyForBlockDecryption implements the KeyManager interface for
// KeyManagerStandard.
func (km *KeyManagerStandard) GetTLFCryptKeyForBlockDecryption(
ctx context.Context, kmd KeyMetadata, blockPtr BlockPointer) (
tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
return km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd, blockPtr.KeyGen, true)
}
// GetTLFCryptKeyOfAllGenerations implements the KeyManager interface for
// KeyManagerStandard.
func (km *KeyManagerStandard) GetTLFCryptKeyOfAllGenerations(
ctx context.Context, kmd KeyMetadata) (
keys []kbfscrypto.TLFCryptKey, err error) {
for g := FirstValidKeyGen; g <= kmd.LatestKeyGeneration(); g++ {
var key kbfscrypto.TLFCryptKey
key, err = km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd, g, true)
if err != nil {
return keys, err
}
keys = append(keys, key)
}
return keys, nil
}
func (km *KeyManagerStandard) getTLFCryptKeyUsingCurrentDevice(
ctx context.Context, kmd KeyMetadata, keyGen KeyGen, cache bool) (
tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
flags := getTLFCryptKeyFlags(0)
if cache {
flags = getTLFCryptKeyDoCache
}
return km.getTLFCryptKey(ctx, kmd, keyGen, flags)
}
type getTLFCryptKeyFlags byte
const (
getTLFCryptKeyAnyDevice getTLFCryptKeyFlags = 1 << iota
getTLFCryptKeyDoCache
getTLFCryptKeyPromptPaper
)
func (km *KeyManagerStandard) getTLFCryptKey(ctx context.Context,
kmd KeyMetadata, keyGen KeyGen, flags getTLFCryptKeyFlags) (
kbfscrypto.TLFCryptKey, error) {
tlfID := kmd.TlfID()
if tlfID.IsPublic() {
return kbfscrypto.PublicTLFCryptKey, nil
}
if keyGen < FirstValidKeyGen {
return kbfscrypto.TLFCryptKey{}, InvalidKeyGenerationError{tlfID, keyGen}
}
// Is this some key we don't know yet? Shouldn't really ever happen,
// since we must have seen the MD that led us to this block, which
// should include all the latest keys. Consider this a failsafe.
if keyGen > kmd.LatestKeyGeneration() {
return kbfscrypto.TLFCryptKey{}, NewKeyGenerationError{tlfID, keyGen}
}
// look in the cache first
kcache := km.config.KeyCache()
tlfCryptKey, err := kcache.GetTLFCryptKey(tlfID, keyGen)
switch err := err.(type) {
case nil:
return tlfCryptKey, nil
case KeyCacheMissError:
break
default:
return kbfscrypto.TLFCryptKey{}, err
}
// Get the encrypted version of this secret key for this device
kbpki := km.config.KBPKI()
username, uid, err := kbpki.GetCurrentUserInfo(ctx)
if err != nil {
return kbfscrypto.TLFCryptKey{}, err
}
clientHalf, serverHalfID, cryptPublicKey, err :=
km.getTLFCryptKeyParams(ctx, kmd, keyGen, uid, username, flags)
var notPerDeviceEncrypted bool
if _, notPerDeviceEncrypted = err.(TLFCryptKeyNotPerDeviceEncrypted); notPerDeviceEncrypted {
// get the key we want using the current crypt key
currKeyGen := kmd.LatestKeyGeneration()
// look in the cache first
latestKey, err := kcache.GetTLFCryptKey(tlfID, currKeyGen)
switch err := err.(type) {
case nil:
break
case KeyCacheMissError:
// not cached, look up the params
clientHalf, serverHalfID, cryptPublicKey, err2 :=
km.getTLFCryptKeyParams(ctx, kmd, currKeyGen, uid, username, flags)
if err2 != nil {
return kbfscrypto.TLFCryptKey{}, err2
}
// unmask it
latestKey, err2 = km.unmaskTLFCryptKey(ctx, serverHalfID, cryptPublicKey, clientHalf)
if err2 != nil {
return kbfscrypto.TLFCryptKey{}, err2
}
break
default:
return kbfscrypto.TLFCryptKey{}, err
}
// get the historic key we want
tlfCryptKey, err =
kmd.GetHistoricTLFCryptKey(km.config.Crypto(), keyGen, latestKey)
if err != nil {
return kbfscrypto.TLFCryptKey{}, err
}
} else if err != nil {
return kbfscrypto.TLFCryptKey{}, err
} else {
// unmask it
tlfCryptKey, err = km.unmaskTLFCryptKey(ctx, serverHalfID, cryptPublicKey, clientHalf)
if err != nil {
return kbfscrypto.TLFCryptKey{}, err
}
}
if flags&getTLFCryptKeyDoCache != 0 {
if err = kcache.PutTLFCryptKey(tlfID, keyGen, tlfCryptKey); err != nil {
return kbfscrypto.TLFCryptKey{}, err
}
}
return tlfCryptKey, nil
}
func (km *KeyManagerStandard) getTLFCryptKeyParams(
ctx context.Context, kmd KeyMetadata,
keyGen KeyGen, uid keybase1.UID, username libkb.NormalizedUsername,
flags getTLFCryptKeyFlags) (
clientHalf kbfscrypto.TLFCryptKeyClientHalf,
serverHalfID TLFCryptKeyServerHalfID,
cryptPublicKey kbfscrypto.CryptPublicKey, err error) {
kbpki := km.config.KBPKI()
crypto := km.config.Crypto()
localMakeRekeyReadError := func(err error) error {
return makeRekeyReadError(ctx, err, kbpki,
kmd, keyGen, uid, username)
}
if flags&getTLFCryptKeyAnyDevice != 0 {
publicKeys, err := kbpki.GetCryptPublicKeys(ctx, uid)
if err != nil {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{}, err
}
keys := make([]EncryptedTLFCryptKeyClientAndEphemeral, 0,
len(publicKeys))
serverHalfIDs := make([]TLFCryptKeyServerHalfID, 0, len(publicKeys))
publicKeyLookup := make([]int, 0, len(publicKeys))
for i, k := range publicKeys {
ePublicKey, encryptedClientHalf, serverHalfID, found, err := kmd.GetTLFCryptKeyParams(keyGen, uid, k)
if _, notPerDeviceEncrypted := err.(TLFCryptKeyNotPerDeviceEncrypted); notPerDeviceEncrypted {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{}, err
}
if err != nil {
km.log.CDebugf(ctx, "Got error for GetTLFCryptKeyParams(%d, %v, %v); skipping: %+v", keyGen, uid, k, err)
continue
}
if !found {
km.log.CDebugf(ctx, "Could not find key info for(%d, %v, %v); skipping", keyGen, uid, k)
continue
}
serverHalfIDs = append(serverHalfIDs, serverHalfID)
keys = append(keys, EncryptedTLFCryptKeyClientAndEphemeral{
PubKey: k,
ClientHalf: encryptedClientHalf,
EPubKey: ePublicKey,
})
publicKeyLookup = append(publicKeyLookup, i)
}
if len(keys) == 0 {
err := errors.New("no valid public keys found")
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{},
localMakeRekeyReadError(err)
}
var index int
clientHalf, index, err = crypto.DecryptTLFCryptKeyClientHalfAny(ctx,
keys, flags&getTLFCryptKeyPromptPaper != 0)
cause := errors.Cause(err)
_, isDecryptError := cause.(libkb.DecryptionError)
_, isNoKeyError := cause.(libkb.NoSecretKeyError)
if isDecryptError || isNoKeyError {
km.log.CDebugf(ctx, "Got decryption error from service: %+v", err)
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{},
localMakeRekeyReadError(err)
} else if err != nil {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{}, err
}
serverHalfID = serverHalfIDs[index]
cryptPublicKey = publicKeys[publicKeyLookup[index]]
} else {
cryptPublicKey, err = kbpki.GetCurrentCryptPublicKey(ctx)
if err != nil {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{}, err
}
ePublicKey, encryptedClientHalf, foundServerHalfID, found, err :=
kmd.GetTLFCryptKeyParams(keyGen, uid, cryptPublicKey)
if _, notPerDeviceEncrypted := err.(TLFCryptKeyNotPerDeviceEncrypted); notPerDeviceEncrypted {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{}, err
}
if err != nil {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{}, err
} else if !found {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{},
localMakeRekeyReadError(err)
}
clientHalf, err = crypto.DecryptTLFCryptKeyClientHalf(
ctx, ePublicKey, encryptedClientHalf)
if err != nil {
return kbfscrypto.TLFCryptKeyClientHalf{},
TLFCryptKeyServerHalfID{},
kbfscrypto.CryptPublicKey{}, err
}
serverHalfID = foundServerHalfID
}
return
}
func (km *KeyManagerStandard) unmaskTLFCryptKey(ctx context.Context, serverHalfID TLFCryptKeyServerHalfID,
cryptPublicKey kbfscrypto.CryptPublicKey,
clientHalf kbfscrypto.TLFCryptKeyClientHalf) (
kbfscrypto.TLFCryptKey, error) {
// get the server-side key-half, do the unmasking, possibly cache the result, return
// TODO: can parallelize the get() with decryption
serverHalf, err := km.config.KeyOps().GetTLFCryptKeyServerHalf(ctx, serverHalfID,
cryptPublicKey)
if err != nil {
return kbfscrypto.TLFCryptKey{}, err
}
tlfCryptKey := kbfscrypto.UnmaskTLFCryptKey(serverHalf, clientHalf)
return tlfCryptKey, nil
}
func (km *KeyManagerStandard) updateKeyGeneration(ctx context.Context,
md *RootMetadata, keyGen KeyGen, wKeys, rKeys UserDevicePublicKeys,
ePubKey kbfscrypto.TLFEphemeralPublicKey,
ePrivKey kbfscrypto.TLFEphemeralPrivateKey,
tlfCryptKey kbfscrypto.TLFCryptKey) error {
serverHalves, err := md.updateKeyGeneration(km.config.Crypto(),
keyGen, wKeys, rKeys, ePubKey, ePrivKey, tlfCryptKey)
if err != nil {
return err
}
// Push new keys to the key server.
//
// TODO: Should accumulate the server halves across multiple
// key generations and push them all at once right before the
// MD push, although this only really matters for MDv2.
if err = km.config.KeyOps().
PutTLFCryptKeyServerHalves(ctx, serverHalves); err != nil {
return err
}
return nil
}
func (km *KeyManagerStandard) usersWithNewDevices(ctx context.Context,
tlfID tlf.ID, keyInfoMap UserDeviceKeyInfoMap,
expectedKeys UserDevicePublicKeys) map[keybase1.UID]bool {
users := make(map[keybase1.UID]bool)
for u, keys := range expectedKeys {
kids, ok := keyInfoMap[u]
if !ok {
// Currently there probably shouldn't be any new users
// in the handle, but don't error just in case we ever
// want to support that in the future.
km.log.CInfof(ctx, "Rekey %s: adding new user %s", tlfID, u)
users[u] = true
continue
}
for k := range keys {
km.log.CDebugf(ctx, "Checking key %v", k.KID())
if _, ok := kids[k]; !ok {
km.log.CInfof(ctx, "Rekey %s: adding new device %s for user %s",
tlfID, k.KID(), u)
users[u] = true
break
}
}
}
return users
}
func (km *KeyManagerStandard) usersWithRemovedDevices(ctx context.Context,
tlfID tlf.ID, keyInfoMap UserDeviceKeyInfoMap,
expectedKeys UserDevicePublicKeys) map[keybase1.UID]bool {
users := make(map[keybase1.UID]bool)
for u, keyInfos := range keyInfoMap {
keys, ok := expectedKeys[u]
if !ok {
// Currently there probably shouldn't be any users removed
// from the handle, but don't error just in case we ever
// want to support that in the future.
km.log.CInfof(ctx, "Rekey %s: removing user %s", tlfID, u)
users[u] = true
continue
}
keyLookup := make(map[keybase1.KID]bool)
for key := range keys {
keyLookup[key.KID()] = true
}
for key := range keyInfos {
// Make sure every kid has an expected key
if !keyLookup[key.KID()] {
km.log.CInfof(ctx,
"Rekey %s: removing device %s for user %s", tlfID, key, u)
users[u] = true
break
}
}
}
return users
}
func (km *KeyManagerStandard) identifyUIDSets(ctx context.Context,
tlfID tlf.ID, writersToIdentify map[keybase1.UID]bool,
readersToIdentify map[keybase1.UID]bool) error {
uids := make([]keybase1.UID, 0, len(writersToIdentify)+len(readersToIdentify))
for u := range writersToIdentify {
uids = append(uids, u)
}
for u := range readersToIdentify {
uids = append(uids, u)
}
kbpki := km.config.KBPKI()
return identifyUserList(ctx, kbpki, kbpki, uids, tlfID.IsPublic())
}
func (km *KeyManagerStandard) generateKeyMapForUsers(
ctx context.Context, users []keybase1.UID) (
UserDevicePublicKeys, error) {
keyMap := make(UserDevicePublicKeys)
// TODO: parallelize
for _, w := range users {
// HACK: clear cache
km.config.KeybaseService().FlushUserFromLocalCache(ctx, w)
publicKeys, err := km.config.KBPKI().GetCryptPublicKeys(ctx, w)
if err != nil {
return nil, err
}
keyMap[w] = make(map[kbfscrypto.CryptPublicKey]bool)
for _, key := range publicKeys {
keyMap[w][key] = true
}
}
return keyMap, nil
}
// Rekey implements the KeyManager interface for KeyManagerStandard.
// TODO make this less terrible.
func (km *KeyManagerStandard) Rekey(ctx context.Context, md *RootMetadata, promptPaper bool) (
mdChanged bool, cryptKey *kbfscrypto.TLFCryptKey, err error) {
km.log.CDebugf(ctx, "Rekey %s (prompt for paper key: %t)",
md.TlfID(), promptPaper)
defer func() { km.deferLog.CDebugf(ctx, "Rekey %s done: %+v", md.TlfID(), err) }()
currKeyGen := md.LatestKeyGeneration()
if md.TlfID().IsPublic() != (currKeyGen == PublicKeyGen) {
return false, nil, errors.Errorf(
"ID %v has isPublic=%t but currKeyGen is %d (isPublic=%t)",
md.TlfID(), md.TlfID().IsPublic(), currKeyGen, currKeyGen == PublicKeyGen)
}
if promptPaper && md.TlfID().IsPublic() {
return false, nil, errors.Errorf("promptPaper set for public TLF %v", md.TlfID())
}
handle := md.GetTlfHandle()
username, uid, err := km.config.KBPKI().GetCurrentUserInfo(ctx)
if err != nil {
return false, nil, err
}
resolvedHandle, err := handle.ResolveAgain(ctx, km.config.KBPKI())
if err != nil {
return false, nil, err
}
isWriter := resolvedHandle.IsWriter(uid)
if !md.TlfID().IsPublic() && !isWriter {
// If I was already a reader, there's nothing more to do
if handle.IsReader(uid) {
resolvedHandle = handle
km.log.CDebugf(ctx, "Local user is not a writer, and was "+
"already a reader; reverting back to the original handle")
} else {
// Only allow yourself to change
resolvedHandle, err =
handle.ResolveAgainForUser(ctx, km.config.KBPKI(), uid)
if err != nil {
return false, nil, err
}
}
}
eq, err := handle.Equals(km.config.Codec(), *resolvedHandle)
if err != nil {
return false, nil, err
}
handleChanged := !eq
if handleChanged {
km.log.CDebugf(ctx, "handle for %s resolved to %s",
handle.GetCanonicalPath(),
resolvedHandle.GetCanonicalPath())
// Check with the server to see if the handle became a conflict.
latestHandle, err := km.config.MDOps().GetLatestHandleForTLF(ctx, md.TlfID())
if latestHandle.ConflictInfo != nil {
km.log.CDebugf(ctx, "handle for %s is conflicted",
handle.GetCanonicalPath())
}
resolvedHandle, err = resolvedHandle.WithUpdatedConflictInfo(
km.config.Codec(), latestHandle.ConflictInfo)
if err != nil {
return false, nil, err
}
}
// For a public TLF there's no rekeying to be done, but we
// should still update the writer list.
if md.TlfID().IsPublic() {
if !handleChanged {
km.log.CDebugf(ctx,
"Skipping rekeying %s (public): handle hasn't changed",
md.TlfID())
return false, nil, nil
}
return true, nil, md.updateFromTlfHandle(resolvedHandle)
}
// Decide whether we have a new device and/or a revoked device, or neither.
// Look up all the device public keys for all writers and readers first.
incKeyGen := currKeyGen < FirstValidKeyGen
if !isWriter && incKeyGen {
// Readers cannot create the first key generation
return false, nil, NewReadAccessError(resolvedHandle, username, resolvedHandle.GetCanonicalPath())
}
// All writer keys in the desired keyset
wKeys, err := km.generateKeyMapForUsers(ctx, resolvedHandle.ResolvedWriters())
if err != nil {
return false, nil, err
}
// All reader keys in the desired keyset
rKeys, err := km.generateKeyMapForUsers(ctx, resolvedHandle.ResolvedReaders())
if err != nil {
return false, nil, err
}
addNewReaderDevice := false
addNewWriterDevice := false
var newReaderUsers map[keybase1.UID]bool
var newWriterUsers map[keybase1.UID]bool
var promotedReaders map[keybase1.UID]bool
// Figure out if we need to add or remove any keys.
// If we're already incrementing the key generation then we don't need to
// figure out the key delta.
addNewReaderDeviceForSelf := false
if !incKeyGen {
// See if there is at least one new device in relation to the
// current key bundle
rDkim, wDkim, err := md.getUserDeviceKeyInfoMaps(
km.config.Codec(), currKeyGen)
if err != nil {
return false, nil, err
}
newWriterUsers = km.usersWithNewDevices(ctx, md.TlfID(), wDkim, wKeys)
newReaderUsers = km.usersWithNewDevices(ctx, md.TlfID(), rDkim, rKeys)
addNewWriterDevice = len(newWriterUsers) > 0
addNewReaderDevice = len(newReaderUsers) > 0
wRemoved := km.usersWithRemovedDevices(ctx, md.TlfID(), wDkim, wKeys)
rRemoved := km.usersWithRemovedDevices(ctx, md.TlfID(), rDkim, rKeys)
// TODO: This is incorrectly true if we're only
// promoting readers. This is KBFS-1744.
incKeyGen = len(wRemoved) > 0 || len(rRemoved) > 0
promotedReaders = make(map[keybase1.UID]bool, len(rRemoved))
// Before we add the removed devices, check if we are adding a
// new reader device for ourselves.
_, addNewReaderDeviceForSelf = newReaderUsers[uid]
for u := range rRemoved {
// FIXME (potential): this could cause a reader to attempt to rekey
// in the case of a revocation for the currently logged-in user. I
// _think_ incKeyGen above protects against this, but I'm not
// confident.
newReaderUsers[u] = true
// Track which readers have been promoted. This must happen before
// the following line adds all the removed writers to the writer
// set
if newWriterUsers[u] {
promotedReaders[u] = true
}
}
for u := range wRemoved {
newWriterUsers[u] = true
}
if err := km.identifyUIDSets(ctx, md.TlfID(), newWriterUsers, newReaderUsers); err != nil {
return false, nil, err
}
}
if !addNewReaderDevice && !addNewWriterDevice && !incKeyGen &&
!handleChanged {
km.log.CDebugf(ctx,
"Skipping rekeying %s (private): no new or removed devices, no new keygen, and handle hasn't changed",
md.TlfID())
return false, nil, nil
}
if !isWriter {
if _, userHasNewKeys := newReaderUsers[uid]; userHasNewKeys && !promotedReaders[uid] {
// Only rekey the logged-in reader, and only if that reader isn't being promoted
rKeys = UserDevicePublicKeys{
uid: rKeys[uid],
}
wKeys = nil
delete(newReaderUsers, uid)
} else {
// No new reader device for our user, so the reader can't do
// anything
return false, nil, RekeyIncompleteError{}
}
}
// Generate ephemeral keys to be used by addNewDevice,
// incKeygen, or both. ePrivKey will be discarded at the end
// of the function.
ePubKey, ePrivKey, err :=
km.config.Crypto().MakeRandomTLFEphemeralKeys()
for uid := range promotedReaders {
// If there are readers that need to be promoted to
// writers, do that here.
err := md.promoteReader(uid)
if err != nil {
return false, nil, err
}
}
// Note: For MDv3, if incKeyGen is true, then all the
// manipulations below aren't needed, since they'll just be
// replaced by the new key generation. However, do them
// anyway, as they may have some side effects, e.g. removing
// server key halves.
// If there's at least one new device, add that device to every key bundle.
if addNewReaderDevice || addNewWriterDevice {
for keyGen := FirstValidKeyGen; keyGen <= currKeyGen; keyGen++ {
flags := getTLFCryptKeyAnyDevice
if promptPaper {
flags |= getTLFCryptKeyPromptPaper
}
currTlfCryptKey, err := km.getTLFCryptKey(ctx, md.ReadOnly(), keyGen, flags)
if err != nil {
return false, nil, err
}
err = km.updateKeyGeneration(ctx, md, keyGen, wKeys,
rKeys, ePubKey, ePrivKey, currTlfCryptKey)
if _, noDkim := err.(TLFCryptKeyNotPerDeviceEncrypted); noDkim {
// No DKIM for this generation. This is possible for MDv3.
continue
}
if err != nil {
return false, nil, err
}
}
}
// Make sure the private MD is decrypted if it wasn't already. We
// have to do this here, before adding a new key generation, since
// decryptMDPrivateData assumes that the MD is always encrypted
// using the latest key gen.
if !md.IsReadable() && len(md.GetSerializedPrivateMetadata()) > 0 {
pmd, err := decryptMDPrivateData(
ctx, km.config.Codec(), km.config.Crypto(),
km.config.BlockCache(), km.config.BlockOps(),
km, uid, md.GetSerializedPrivateMetadata(), md, md, km.log)
if err != nil {
return false, nil, err
}
md.data = pmd
}
defer func() {
// On our way back out, update the md with the resolved handle
// if at least part of a rekey was performed.
_, isRekeyIncomplete := err.(RekeyIncompleteError)
if err == nil || isRekeyIncomplete {
updateErr := md.updateFromTlfHandle(resolvedHandle)
if updateErr != nil {
err = updateErr
}
}
}()
// From this point on, if we return true for mdChanged with a
// nil error or RekeyIncompleteError{}, we must call
// md.finalizeRekey() first.
defer func() {
_, isErrRekeyIncomplete := err.(RekeyIncompleteError)
if mdChanged && (err == nil || isErrRekeyIncomplete) {
finalizeErr := md.finalizeRekey(km.config.Crypto())
if finalizeErr != nil {
mdChanged = false
cryptKey = nil
err = finalizeErr
}
}
}()
if !isWriter {
if len(newReaderUsers) > 0 || addNewWriterDevice || incKeyGen {
// If we're a reader but we haven't completed all the work, return
// RekeyIncompleteError.
return addNewReaderDeviceForSelf, nil, RekeyIncompleteError{}
}
// Otherwise, there's nothing left to do!
return true, nil, nil
} else if !incKeyGen {
// we're done!
return true, nil, nil
}
// Send rekey start notification once we're sure that this device
// can perform the rekey.
//
// TODO: Shouldn't this happen earlier?
km.config.Reporter().Notify(ctx, rekeyNotification(ctx, km.config, resolvedHandle,
false))
// Delete server-side key halves for any revoked devices, if
// there are any previous key generations. Do this before
// adding a new key generation, as MDv3 only keeps track of
// the latest key generation.
//
// TODO: Add test coverage for this.
if currKeyGen >= FirstValidKeyGen {
allRemovalInfo, err := md.revokeRemovedDevices(wKeys, rKeys)
if err != nil {
return false, nil, err
}
kops := km.config.KeyOps()
for uid, userRemovalInfo := range allRemovalInfo {
if userRemovalInfo.userRemoved {
km.log.CInfof(ctx, "Rekey %s: removed user %s entirely",
md.TlfID(), uid)
}
for key, serverHalfIDs := range userRemovalInfo.deviceServerHalfIDs {
km.log.CInfof(ctx, "Rekey %s: removing %d server key halves "+
" for device %s of user %s", md.TlfID(),
len(serverHalfIDs), key, uid)
for _, serverHalfID := range serverHalfIDs {
err := kops.DeleteTLFCryptKeyServerHalf(
ctx, uid, key.KID(), serverHalfID)
if err != nil {
return false, nil, err
}
}
}
}
}
pubKey, privKey, tlfCryptKey, err :=
km.config.Crypto().MakeRandomTLFKeys()
if err != nil {
return false, nil, err
}
// Get the previous TLF crypt key if needed. It's
// symmetrically encrypted and appended to a list for MDv3
// metadata.
var prevTLFCryptKey, currTLFCryptKey kbfscrypto.TLFCryptKey
if md.StoresHistoricTLFCryptKeys() {
if currKeyGen >= FirstValidKeyGen {
flags := getTLFCryptKeyAnyDevice
if promptPaper {
flags |= getTLFCryptKeyPromptPaper
}
var err error
prevTLFCryptKey, err = km.getTLFCryptKey(
ctx, md.ReadOnly(), currKeyGen, flags)
if err != nil {
return false, nil, err
}
}
currTLFCryptKey = tlfCryptKey
}
err = md.AddKeyGeneration(km.config.Codec(),
km.config.Crypto(), prevTLFCryptKey, currTLFCryptKey, pubKey)
if err != nil {
return false, nil, err
}
currKeyGen = md.LatestKeyGeneration()
err = km.updateKeyGeneration(ctx, md, currKeyGen, wKeys, rKeys, ePubKey,
ePrivKey, tlfCryptKey)
if err != nil {
return false, nil, err
}
md.data.TLFPrivateKey = privKey
return true, &tlfCryptKey, nil
}
| 1 | 15,161 | Do we really need this? Seems like it would pollute the logs pretty badly. | keybase-kbfs | go |
@@ -9,6 +9,8 @@ namespace Microsoft.AspNet.Server.Kestrel.Infrastructure
{
public struct MemoryPoolIterator2
{
+ private readonly static int _vectorSpan = Vector<byte>.Count;
+
private MemoryPoolBlock2 _block;
private int _index;
| 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.Diagnostics;
using System.Numerics;
namespace Microsoft.AspNet.Server.Kestrel.Infrastructure
{
public struct MemoryPoolIterator2
{
private MemoryPoolBlock2 _block;
private int _index;
public MemoryPoolIterator2(MemoryPoolBlock2 block)
{
_block = block;
_index = _block?.Start ?? 0;
}
public MemoryPoolIterator2(MemoryPoolBlock2 block, int index)
{
_block = block;
_index = index;
}
public bool IsDefault => _block == null;
public bool IsEnd
{
get
{
if (_block == null)
{
return true;
}
else if (_index < _block.End)
{
return false;
}
else
{
var block = _block.Next;
while (block != null)
{
if (block.Start < block.End)
{
return false; // subsequent block has data - IsEnd is false
}
block = block.Next;
}
return true;
}
}
}
public MemoryPoolBlock2 Block => _block;
public int Index => _index;
public int Take()
{
var block = _block;
if (block == null)
{
return -1;
}
var index = _index;
if (index < block.End)
{
_index = index + 1;
return block.Array[index];
}
do
{
if (block.Next == null)
{
return -1;
}
else
{
block = block.Next;
index = block.Start;
}
if (index < block.End)
{
_block = block;
_index = index + 1;
return block.Array[index];
}
} while (true);
}
public void Skip(int bytesToSkip)
{
if (_block == null)
{
return;
}
var following = _block.End - _index;
if (following >= bytesToSkip)
{
_index += bytesToSkip;
return;
}
var block = _block;
var index = _index;
while (true)
{
if (block.Next == null)
{
return;
}
else
{
bytesToSkip -= following;
block = block.Next;
index = block.Start;
}
following = block.End - index;
if (following >= bytesToSkip)
{
_block = block;
_index = index + bytesToSkip;
return;
}
}
}
public int Peek()
{
var block = _block;
if (block == null)
{
return -1;
}
var index = _index;
if (index < block.End)
{
return block.Array[index];
}
do
{
if (block.Next == null)
{
return -1;
}
else
{
block = block.Next;
index = block.Start;
}
if (index < block.End)
{
return block.Array[index];
}
} while (true);
}
public unsafe long PeekLong()
{
if (_block == null)
{
return -1;
}
else if (_block.End - _index >= sizeof(long))
{
fixed (byte* ptr = _block.Array)
{
return *(long*)(ptr + _index);
}
}
else if (_block.Next == null)
{
return -1;
}
else
{
var blockBytes = _block.End - _index;
var nextBytes = sizeof(long) - blockBytes;
if (_block.Next.End - _block.Next.Start < nextBytes)
{
return -1;
}
long blockLong;
fixed (byte* ptr = _block.Array)
{
blockLong = *(long*)(ptr + _block.End - sizeof(long));
}
long nextLong;
fixed (byte* ptr = _block.Next.Array)
{
nextLong = *(long*)(ptr + _block.Next.Start);
}
return (blockLong >> (sizeof(long) - blockBytes) * 8) | (nextLong << (sizeof(long) - nextBytes) * 8);
}
}
public int Seek(Vector<byte> byte0Vector)
{
if (IsDefault)
{
return -1;
}
var block = _block;
var index = _index;
var array = block.Array;
while (true)
{
while (block.End == index)
{
if (block.Next == null)
{
_block = block;
_index = index;
return -1;
}
block = block.Next;
index = block.Start;
array = block.Array;
}
while (block.End != index)
{
var following = block.End - index;
if (following >= Vector<byte>.Count)
{
var data = new Vector<byte>(array, index);
var byte0Equals = Vector.Equals(data, byte0Vector);
if (byte0Equals.Equals(Vector<byte>.Zero))
{
index += Vector<byte>.Count;
continue;
}
_block = block;
_index = index + FindFirstEqualByte(byte0Equals);
return byte0Vector[0];
}
var byte0 = byte0Vector[0];
while (following > 0)
{
if (block.Array[index] == byte0)
{
_block = block;
_index = index;
return byte0;
}
following--;
index++;
}
}
}
}
public int Seek(Vector<byte> byte0Vector, Vector<byte> byte1Vector)
{
if (IsDefault)
{
return -1;
}
var block = _block;
var index = _index;
var array = block.Array;
while (true)
{
while (block.End == index)
{
if (block.Next == null)
{
_block = block;
_index = index;
return -1;
}
block = block.Next;
index = block.Start;
array = block.Array;
}
while (block.End != index)
{
var following = block.End - index;
if (following >= Vector<byte>.Count)
{
var data = new Vector<byte>(array, index);
var byte0Equals = Vector.Equals(data, byte0Vector);
var byte1Equals = Vector.Equals(data, byte1Vector);
int byte0Index = int.MaxValue;
int byte1Index = int.MaxValue;
if (!byte0Equals.Equals(Vector<byte>.Zero))
{
byte0Index = FindFirstEqualByte(byte0Equals);
}
if (!byte1Equals.Equals(Vector<byte>.Zero))
{
byte1Index = FindFirstEqualByte(byte1Equals);
}
if (byte0Index == int.MaxValue && byte1Index == int.MaxValue)
{
index += Vector<byte>.Count;
continue;
}
_block = block;
if (byte0Index < byte1Index)
{
_index = index + byte0Index;
return byte0Vector[0];
}
_index = index + byte1Index;
return byte1Vector[0];
}
byte byte0 = byte0Vector[0];
byte byte1 = byte1Vector[0];
while (following > 0)
{
var byteIndex = block.Array[index];
if (byteIndex == byte0)
{
_block = block;
_index = index;
return byte0;
}
else if (byteIndex == byte1)
{
_block = block;
_index = index;
return byte1;
}
following--;
index++;
}
}
}
}
public int Seek(Vector<byte> byte0Vector, Vector<byte> byte1Vector, Vector<byte> byte2Vector)
{
if (IsDefault)
{
return -1;
}
var block = _block;
var index = _index;
var array = block.Array;
while (true)
{
while (block.End == index)
{
if (block.Next == null)
{
_block = block;
_index = index;
return -1;
}
block = block.Next;
index = block.Start;
array = block.Array;
}
while (block.End != index)
{
var following = block.End - index;
if (following >= Vector<byte>.Count)
{
var data = new Vector<byte>(array, index);
var byte0Equals = Vector.Equals(data, byte0Vector);
var byte1Equals = Vector.Equals(data, byte1Vector);
var byte2Equals = Vector.Equals(data, byte2Vector);
int byte0Index = int.MaxValue;
int byte1Index = int.MaxValue;
int byte2Index = int.MaxValue;
if (!byte0Equals.Equals(Vector<byte>.Zero))
{
byte0Index = FindFirstEqualByte(byte0Equals);
}
if (!byte1Equals.Equals(Vector<byte>.Zero))
{
byte1Index = FindFirstEqualByte(byte1Equals);
}
if (!byte2Equals.Equals(Vector<byte>.Zero))
{
byte2Index = FindFirstEqualByte(byte2Equals);
}
if (byte0Index == int.MaxValue && byte1Index == int.MaxValue && byte2Index == int.MaxValue)
{
index += Vector<byte>.Count;
continue;
}
int toReturn, toMove;
if (byte0Index < byte1Index)
{
if (byte0Index < byte2Index)
{
toReturn = byte0Vector[0];
toMove = byte0Index;
}
else
{
toReturn = byte2Vector[0];
toMove = byte2Index;
}
}
else
{
if (byte1Index < byte2Index)
{
toReturn = byte1Vector[0];
toMove = byte1Index;
}
else
{
toReturn = byte2Vector[0];
toMove = byte2Index;
}
}
_block = block;
_index = index + toMove;
return toReturn;
}
var byte0 = byte0Vector[0];
var byte1 = byte1Vector[0];
var byte2 = byte2Vector[0];
while (following > 0)
{
var byteIndex = block.Array[index];
if (byteIndex == byte0)
{
_block = block;
_index = index;
return byte0;
}
else if (byteIndex == byte1)
{
_block = block;
_index = index;
return byte1;
}
else if (byteIndex == byte2)
{
_block = block;
_index = index;
return byte2;
}
following--;
index++;
}
}
}
}
private static int FindFirstEqualByte(Vector<byte> byteEquals)
{
// Quasi-tree search
var vector64 = Vector.AsVectorInt64(byteEquals);
for (var i = 0; i < Vector<long>.Count; i++)
{
var longValue = vector64[i];
if (longValue == 0) continue;
var shift = i << 1;
var offset = shift << 2;
var vector32 = Vector.AsVectorInt32(byteEquals);
if (vector32[shift] != 0)
{
if (byteEquals[offset] != 0) return offset;
if (byteEquals[++offset] != 0) return offset;
if (byteEquals[++offset] != 0) return offset;
return ++offset;
}
offset += 4;
if (byteEquals[offset] != 0) return offset;
if (byteEquals[++offset] != 0) return offset;
if (byteEquals[++offset] != 0) return offset;
return ++offset;
}
throw new InvalidOperationException();
}
/// <summary>
/// Save the data at the current location then move to the next available space.
/// </summary>
/// <param name="data">The byte to be saved.</param>
/// <returns>true if the operation successes. false if can't find available space.</returns>
public bool Put(byte data)
{
if (_block == null)
{
return false;
}
else if (_index < _block.End)
{
_block.Array[_index++] = data;
return true;
}
var block = _block;
var index = _index;
while (true)
{
if (index < block.End)
{
_block = block;
_index = index + 1;
block.Array[index] = data;
return true;
}
else if (block.Next == null)
{
return false;
}
else
{
block = block.Next;
index = block.Start;
}
}
}
public int GetLength(MemoryPoolIterator2 end)
{
if (IsDefault || end.IsDefault)
{
return -1;
}
var block = _block;
var index = _index;
var length = 0;
checked
{
while (true)
{
if (block == end._block)
{
return length + end._index - index;
}
else if (block.Next == null)
{
throw new InvalidOperationException("end did not follow iterator");
}
else
{
length += block.End - index;
block = block.Next;
index = block.Start;
}
}
}
}
public MemoryPoolIterator2 CopyTo(byte[] array, int offset, int count, out int actual)
{
if (IsDefault)
{
actual = 0;
return this;
}
var block = _block;
var index = _index;
var remaining = count;
while (true)
{
var following = block.End - index;
if (remaining <= following)
{
actual = count;
if (array != null)
{
Buffer.BlockCopy(block.Array, index, array, offset, remaining);
}
return new MemoryPoolIterator2(block, index + remaining);
}
else if (block.Next == null)
{
actual = count - remaining + following;
if (array != null)
{
Buffer.BlockCopy(block.Array, index, array, offset, following);
}
return new MemoryPoolIterator2(block, index + following);
}
else
{
if (array != null)
{
Buffer.BlockCopy(block.Array, index, array, offset, following);
}
offset += following;
remaining -= following;
block = block.Next;
index = block.Start;
}
}
}
public void CopyFrom(byte[] data)
{
CopyFrom(data, 0, data.Length);
}
public void CopyFrom(ArraySegment<byte> buffer)
{
CopyFrom(buffer.Array, buffer.Offset, buffer.Count);
}
public void CopyFrom(byte[] data, int offset, int count)
{
Debug.Assert(_block != null);
Debug.Assert(_block.Pool != null);
Debug.Assert(_block.Next == null);
Debug.Assert(_block.End == _index);
var pool = _block.Pool;
var block = _block;
var blockIndex = _index;
var bufferIndex = offset;
var remaining = count;
var bytesLeftInBlock = block.Data.Offset + block.Data.Count - blockIndex;
while (remaining > 0)
{
if (bytesLeftInBlock == 0)
{
var nextBlock = pool.Lease();
block.End = blockIndex;
block.Next = nextBlock;
block = nextBlock;
blockIndex = block.Data.Offset;
bytesLeftInBlock = block.Data.Count;
}
var bytesToCopy = remaining < bytesLeftInBlock ? remaining : bytesLeftInBlock;
Buffer.BlockCopy(data, bufferIndex, block.Array, blockIndex, bytesToCopy);
blockIndex += bytesToCopy;
bufferIndex += bytesToCopy;
remaining -= bytesToCopy;
bytesLeftInBlock -= bytesToCopy;
}
block.End = blockIndex;
_block = block;
_index = blockIndex;
}
public unsafe void CopyFromAscii(string data)
{
Debug.Assert(_block != null);
Debug.Assert(_block.Pool != null);
Debug.Assert(_block.Next == null);
Debug.Assert(_block.End == _index);
var pool = _block.Pool;
var block = _block;
var blockIndex = _index;
var length = data.Length;
var bytesLeftInBlock = block.Data.Offset + block.Data.Count - blockIndex;
var bytesLeftInBlockMinusSpan = bytesLeftInBlock - 3;
fixed (char* pData = data)
{
var input = pData;
var inputEnd = pData + length;
var inputEndMinusSpan = inputEnd - 3;
while (input < inputEnd)
{
if (bytesLeftInBlock == 0)
{
var nextBlock = pool.Lease();
block.End = blockIndex;
block.Next = nextBlock;
block = nextBlock;
blockIndex = block.Data.Offset;
bytesLeftInBlock = block.Data.Count;
bytesLeftInBlockMinusSpan = bytesLeftInBlock - 3;
}
fixed (byte* pOutput = block.Data.Array)
{
var output = pOutput + block.End;
var copied = 0;
for (; input < inputEndMinusSpan && copied < bytesLeftInBlockMinusSpan; copied += 4)
{
*(output) = (byte)*(input);
*(output + 1) = (byte)*(input + 1);
*(output + 2) = (byte)*(input + 2);
*(output + 3) = (byte)*(input + 3);
output += 4;
input += 4;
}
for (; input < inputEnd && copied < bytesLeftInBlock; copied++)
{
*(output++) = (byte)*(input++);
}
blockIndex += copied;
bytesLeftInBlockMinusSpan -= copied;
bytesLeftInBlock -= copied;
}
}
}
block.End = blockIndex;
_block = block;
_index = blockIndex;
}
}
}
| 1 | 7,668 | `Vector<byte>.Count` should Jit to const when intrinsic; not sure when `Vector.IsHardwareAccelerated == false` ; however we know `readonly static int` does Jit to const. | aspnet-KestrelHttpServer | .cs |
@@ -208,6 +208,9 @@ class PostgresqlStorageMigrationTest(unittest.TestCase):
class PostgresqlPermissionMigrationTest(unittest.TestCase):
def __init__(self, *args, **kw):
super(PostgresqlPermissionMigrationTest, self).__init__(*args, **kw)
+ from kinto.core.utils import sqlalchemy
+ if sqlalchemy is None:
+ return
from .test_permission import PostgreSQLPermissionTest
settings = PostgreSQLPermissionTest.settings.copy() | 1 | import os
import mock
import six
from pyramid import testing
from kinto.core.cache import postgresql as postgresql_cache
from kinto.core.permission import postgresql as postgresql_permission
from kinto.core.storage import postgresql as postgresql_storage, exceptions
from kinto.core.utils import json
from .support import unittest, skip_if_no_postgresql
@skip_if_no_postgresql
class PostgresqlStorageMigrationTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(PostgresqlStorageMigrationTest, self).__init__(*args, **kwargs)
from kinto.core.utils import sqlalchemy
if sqlalchemy is None:
return
from .test_storage import PostgreSQLStorageTest
self.settings = PostgreSQLStorageTest.settings.copy()
self.config = testing.setUp()
self.config.add_settings(self.settings)
self.version = postgresql_storage.Storage.schema_version
# Usual storage object to manipulate the storage.
self.storage = postgresql_storage.load_from_config(self.config)
def setUp(self):
# Start empty.
self._delete_everything()
# Create schema in its last version
self.storage.initialize_schema()
# Patch to keep track of SQL files executed.
self.sql_execute_patcher = mock.patch(
'kinto.core.storage.postgresql.Storage._execute_sql_file')
def tearDown(self):
postgresql_storage.Storage.schema_version = self.version
mock.patch.stopall()
def _delete_everything(self):
q = """
DROP TABLE IF EXISTS records CASCADE;
DROP TABLE IF EXISTS deleted CASCADE;
DROP TABLE IF EXISTS metadata CASCADE;
DROP FUNCTION IF EXISTS resource_timestamp(VARCHAR, VARCHAR);
DROP FUNCTION IF EXISTS collection_timestamp(VARCHAR, VARCHAR);
DROP FUNCTION IF EXISTS bump_timestamp();
"""
with self.storage.client.connect() as conn:
conn.execute(q)
def test_schema_sets_the_current_version(self):
version = self.storage._get_installed_version()
self.assertEqual(version, self.version)
def test_schema_is_not_recreated_from_scratch_if_already_exists(self):
mocked = self.sql_execute_patcher.start()
self.storage.initialize_schema()
self.assertFalse(mocked.called)
def test_schema_is_considered_first_version_if_no_version_detected(self):
with self.storage.client.connect() as conn:
q = "DELETE FROM metadata WHERE name = 'storage_schema_version';"
conn.execute(q)
mocked = self.sql_execute_patcher.start()
postgresql_storage.Storage.schema_version = 2
self.storage.initialize_schema()
sql_called = mocked.call_args[0][0]
self.assertIn('migrations/migration_001_002.sql', sql_called)
def test_migration_file_is_executed_for_every_intermediary_version(self):
postgresql_storage.Storage.schema_version = 6
versions = [6, 5, 4, 3, 3]
self.storage._get_installed_version = lambda: versions.pop()
mocked = self.sql_execute_patcher.start()
self.storage.initialize_schema()
sql_called = mocked.call_args_list[-3][0][0]
self.assertIn('migrations/migration_003_004.sql', sql_called)
sql_called = mocked.call_args_list[-2][0][0]
self.assertIn('migrations/migration_004_005.sql', sql_called)
sql_called = mocked.call_args_list[-1][0][0]
self.assertIn('migrations/migration_005_006.sql', sql_called)
def test_migration_fails_if_intermediary_version_is_missing(self):
with mock.patch.object(self.storage,
'_get_installed_version') as current:
current.return_value = -1
self.sql_execute_patcher.start()
self.assertRaises(AssertionError, self.storage.initialize_schema)
def test_every_available_migration(self):
"""Test every migration available in kinto.core code base since
version 1.6.
Records migration test is currently very naive, and should be
elaborated along future migrations.
"""
self._delete_everything()
# Install old schema
with self.storage.client.connect() as conn:
here = os.path.abspath(os.path.dirname(__file__))
filepath = 'schema/postgresql-storage-1.6.sql'
old_schema = open(os.path.join(here, filepath)).read()
conn.execute(old_schema)
# Create a sample record using some code that is compatible with the
# schema in place in cliquet 1.6.
with self.storage.client.connect() as conn:
before = {'drink': 'cacao'}
query = """
INSERT INTO records (user_id, resource_name, data)
VALUES (:user_id, :resource_name, (:data)::JSON)
RETURNING id, as_epoch(last_modified) AS last_modified;
"""
placeholders = dict(user_id='jean-louis',
resource_name='test',
data=json.dumps(before))
result = conn.execute(query, placeholders)
inserted = result.fetchone()
before['id'] = six.text_type(inserted['id'])
before['last_modified'] = inserted['last_modified']
# In cliquet 1.6, version = 1.
version = self.storage._get_installed_version()
self.assertEqual(version, 1)
# Run every migrations available.
self.storage.initialize_schema()
# Version matches current one.
version = self.storage._get_installed_version()
self.assertEqual(version, self.version)
# Check that previously created record is still here
migrated, count = self.storage.get_all('test', 'jean-louis')
self.assertEqual(migrated[0], before)
# Check that new records can be created
r = self.storage.create('test', ',jean-louis', {'drink': 'mate'})
# And deleted
self.storage.delete('test', ',jean-louis', r['id'])
def test_every_available_migration_succeeds_if_tables_were_flushed(self):
# During tests, tables can be flushed.
self.storage.flush()
self.storage.initialize_schema()
# Version matches current one.
version = self.storage._get_installed_version()
self.assertEqual(version, self.version)
def test_migration_12_clean_tombstones(self):
self._delete_everything()
postgresql_storage.Storage.schema_version = 11
self.storage.initialize_schema()
# Set the schema version back to 11 in the base as well
with self.storage.client.connect() as conn:
query = """
UPDATE metadata SET value = '11'
WHERE name = 'storage_schema_version';
"""
conn.execute(query)
r = self.storage.create('test', 'jean-louis', {'drink': 'mate'})
self.storage.delete('test', 'jean-louis', r['id'])
# Insert back the record without removing the tombstone.
with self.storage.client.connect() as conn:
query = """
INSERT INTO records (id, parent_id, collection_id,
data, last_modified)
VALUES (:id, :parent_id, :collection_id,
(:data)::JSONB, from_epoch(:last_modified));
"""
placeholders = dict(id=r['id'],
collection_id='test',
parent_id='jean-louis',
data=json.dumps({'drink': 'mate'}),
last_modified=1468400666777)
conn.execute(query, placeholders)
records, count = self.storage.get_all('test', 'jean-louis',
include_deleted=True)
# Check that we have the tombstone
assert len(records) == 2
assert count == 1
# Execute the 011 to 012 migration
postgresql_storage.Storage.schema_version = 12
self.storage.initialize_schema()
# Check that the rotted tombstone have been removed.
records, count = self.storage.get_all('test', 'jean-louis',
include_deleted=True)
# Only the record remains.
assert len(records) == 1
assert count == 1
@skip_if_no_postgresql
class PostgresqlPermissionMigrationTest(unittest.TestCase):
def __init__(self, *args, **kw):
super(PostgresqlPermissionMigrationTest, self).__init__(*args, **kw)
from .test_permission import PostgreSQLPermissionTest
settings = PostgreSQLPermissionTest.settings.copy()
config = testing.setUp()
config.add_settings(settings)
self.permission = postgresql_permission.load_from_config(config)
def setUp(self):
patcher = mock.patch.object(self.permission, 'get_user_principals',
side_effect=exceptions.BackendError)
self.addCleanup(patcher.stop)
patcher.start()
def test_runs_initialize_schema_if_using_it_fails(self):
with mock.patch.object(self.permission.client, 'connect') as mocked:
self.permission.initialize_schema()
self.assertTrue(mocked.called)
def test_does_not_execute_if_ran_with_dry(self):
with mock.patch.object(self.permission.client, 'connect') as mocked:
self.permission.initialize_schema(dry_run=True)
self.assertFalse(mocked.called)
@skip_if_no_postgresql
class PostgresqlCacheMigrationTest(unittest.TestCase):
def __init__(self, *args, **kw):
super(PostgresqlCacheMigrationTest, self).__init__(*args, **kw)
from .test_cache import PostgreSQLCacheTest
settings = PostgreSQLCacheTest.settings.copy()
config = testing.setUp()
config.add_settings(settings)
self.permission = postgresql_cache.load_from_config(config)
def setUp(self):
patcher = mock.patch.object(self.permission, 'get',
side_effect=exceptions.BackendError)
self.addCleanup(patcher.stop)
patcher.start()
def test_runs_initialize_schema_if_using_it_fails(self):
with mock.patch.object(self.permission.client, 'connect') as mocked:
self.permission.initialize_schema()
self.assertTrue(mocked.called)
def test_does_not_execute_if_ran_with_dry(self):
with mock.patch.object(self.permission.client, 'connect') as mocked:
self.permission.initialize_schema(dry_run=True)
self.assertFalse(mocked.called)
class PostgresqlExceptionRaisedTest(unittest.TestCase):
def setUp(self):
self.sqlalchemy = postgresql_storage.client.sqlalchemy
def tearDown(self):
postgresql_storage.client.sqlalchemy = self.sqlalchemy
def test_postgresql_usage_raise_an_error_if_postgresql_not_installed(self):
postgresql_storage.client.sqlalchemy = None
with self.assertRaises(ImportWarning):
postgresql_storage.client.create_from_config(testing.setUp())
| 1 | 9,543 | Can we use a skipIf decorator instead? | Kinto-kinto | py |
@@ -3,6 +3,14 @@
module Faker
class Number < Base
class << self
+ ##
+ # Produce a random number.
+ #
+ # @param digits [Integer] Number of digits that the generated number should have.
+ # @return [Integer]
+ #
+ # @example
+ # Faker::Number.number(digits: 10) #=> 1968353479
def number(legacy_digits = NOT_GIVEN, digits: 10)
warn_for_deprecated_arguments do |keywords|
keywords << :digits if legacy_digits != NOT_GIVEN | 1 | # frozen_string_literal: true
module Faker
class Number < Base
class << self
def number(legacy_digits = NOT_GIVEN, digits: 10)
warn_for_deprecated_arguments do |keywords|
keywords << :digits if legacy_digits != NOT_GIVEN
end
return if digits < 1
return rand(0..9).round if digits == 1
# Ensure the first digit is not zero
([non_zero_digit] + generate(digits - 1)).join.to_i
end
def leading_zero_number(legacy_digits = NOT_GIVEN, digits: 10)
warn_for_deprecated_arguments do |keywords|
keywords << :digits if legacy_digits != NOT_GIVEN
end
'0' + (2..digits).collect { digit }.join
end
def decimal_part(legacy_digits = NOT_GIVEN, digits: 10)
warn_for_deprecated_arguments do |keywords|
keywords << :digits if legacy_digits != NOT_GIVEN
end
num = ''
if digits > 1
num = non_zero_digit
digits -= 1
end
leading_zero_number(digits: digits) + num.to_s
end
def decimal(legacy_l_digits = NOT_GIVEN, legacy_r_digits = NOT_GIVEN, l_digits: 5, r_digits: 2)
warn_for_deprecated_arguments do |keywords|
keywords << :l_digits if legacy_l_digits != NOT_GIVEN
keywords << :r_digits if legacy_r_digits != NOT_GIVEN
end
l_d = number(digits: l_digits)
r_d = if r_digits == 1
generate(r_digits)
else
# Ensure the last digit is not zero
# so it does not get truncated on converting to float
generate(r_digits - 1).join + non_zero_digit.to_s
end
"#{l_d}.#{r_d}".to_f
end
def non_zero_digit
rand(1..9)
end
def digit
rand(10)
end
def hexadecimal(legacy_digits = NOT_GIVEN, digits: 6)
warn_for_deprecated_arguments do |keywords|
keywords << :digits if legacy_digits != NOT_GIVEN
end
hex = ''
digits.times { hex += rand(15).to_s(16) }
hex
end
def normal(legacy_mean = NOT_GIVEN, legacy_standard_deviation = NOT_GIVEN, mean: 1, standard_deviation: 1)
warn_for_deprecated_arguments do |keywords|
keywords << :mean if legacy_mean != NOT_GIVEN
keywords << :standard_deviation if legacy_standard_deviation != NOT_GIVEN
end
theta = 2 * Math::PI * rand
rho = Math.sqrt(-2 * Math.log(1 - rand))
scale = standard_deviation * rho
mean + scale * Math.cos(theta)
end
def between(legacy_from = NOT_GIVEN, legacy_to = NOT_GIVEN, from: 1.00, to: 5000.00)
warn_for_deprecated_arguments do |keywords|
keywords << :from if legacy_from != NOT_GIVEN
keywords << :to if legacy_to != NOT_GIVEN
end
Faker::Base.rand_in_range(from, to)
end
def within(legacy_range = NOT_GIVEN, range: 1.00..5000.00)
warn_for_deprecated_arguments do |keywords|
keywords << :range if legacy_range != NOT_GIVEN
end
between(from: range.min, to: range.max)
end
def positive(legacy_from = NOT_GIVEN, legacy_to = NOT_GIVEN, from: 1.00, to: 5000.00)
warn_for_deprecated_arguments do |keywords|
keywords << :from if legacy_from != NOT_GIVEN
keywords << :to if legacy_to != NOT_GIVEN
end
random_number = between(from: from, to: to)
greater_than_zero(random_number)
end
def negative(legacy_from = NOT_GIVEN, legacy_to = NOT_GIVEN, from: -5000.00, to: -1.00)
warn_for_deprecated_arguments do |keywords|
keywords << :from if legacy_from != NOT_GIVEN
keywords << :to if legacy_to != NOT_GIVEN
end
random_number = between(from: from, to: to)
less_than_zero(random_number)
end
private
def generate(count)
return [] if count.zero?
Array.new(count) { digit }
end
def greater_than_zero(number)
should_be(number, :>)
end
def less_than_zero(number)
should_be(number, :<)
end
def should_be(number, method_to_compare)
if number.send(method_to_compare, 0)
number
else
number * -1
end
end
end
end
end
| 1 | 9,395 | Missing version tags | faker-ruby-faker | rb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.