id
int64 22
34.9k
| comment_id
int64 0
328
| comment
stringlengths 2
2.55k
| code
stringlengths 31
107k
| classification
stringclasses 6
values | isFinished
bool 1
class | code_context_2
stringlengths 21
27.3k
| code_context_10
stringlengths 29
27.3k
| code_context_20
stringlengths 29
27.3k
|
---|---|---|---|---|---|---|---|---|
33,498 | 10 | // invalid comment end - */ or int*/* */ | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2); | }
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1); | }
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR); |
33,498 | 11 | // ellipsis ... | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else { | backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1); | return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE); |
33,498 | 12 | // float literal | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') { | }
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE); | }
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?': |
33,498 | 13 | // in a number literal | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal | case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3': | case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd': |
33,498 | 14 | // in hexadecimal (possibly floating-point) literal | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false; | case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5': | case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': |
33,498 | 15 | // in bianry literal | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) { | return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6': | return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A': |
33,498 | 16 | // hex float literal | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true; | case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p': | case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL); |
33,498 | 17 | // two dots in the float literal | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
} | case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u': | case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
} |
33,498 | 18 | // 0x1234l or 0x1234L | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p': | case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid | case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4': |
33,498 | 19 | // binary exponent | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u': | if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
} | case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': |
33,498 | 20 | // if float then before mandatory binary exponent => invalid | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL); | case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4': | case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline(); |
33,498 | 21 | // end of while(true) | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | : CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false); | return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8': | inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow |
33,498 | 22 | // NOI18N | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | } else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else { | c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out; | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out; |
33,498 | 23 | // All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' '] | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b: | case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true); | } // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break; |
33,498 | 24 | // Return single space as flyweight token | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N | case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
} | return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R'); |
33,498 | 25 | // NOI18N | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | } else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else { | c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out; | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out; |
33,498 | 26 | // dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR); | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c); | }
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true); | case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') { |
33,498 | 27 | // uR, UR or LR | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true); | case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
} | return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote"; |
33,498 | 28 | // u8 | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') { | c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote(); | if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
} |
33,498 | 29 | // u8R | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true); | int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) { | break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) { |
33,498 | 30 | // string with L/U/u/R prefixes | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | }
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote"; | } else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1); | default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c); |
33,498 | 31 | // char with L or U/u prefix | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote"; | raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL(); | boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char |
33,498 | 32 | // Invalid char | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
} | Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | // char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} |
33,498 | 33 | // end of switch (c) | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | }
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} |
33,498 | 34 | // end of while(true) | @SuppressWarnings("fallthrough")
@Override
public Token<CppTokenId> nextToken() {
while (true) {
// special handling for escaped lines
if (lastTokenEndedByEscapedLine > 0) {
int c = read(false);
lastTokenEndedByEscapedLine--;
assert c == '\\' : "there must be \\";
c = read(false);
assert c == '\n' || c == '\r' : "there must be \r or \n";
if (c == '\r') {
lastTokenEndedByEscapedLine--;
if (input.consumeNewline()) {
lastTokenEndedByEscapedLine--;
}
return token(CppTokenId.ESCAPED_LINE);
} else {
lastTokenEndedByEscapedLine--;
return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N
}
} else {
int c = read(true);
// if read of the first char caused skipping escaped line
// do we need to backup and create escaped lines first?
switch (c) {
case '"': {
Token<CppTokenId> out = finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
}
case '\'': {// char literal
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
}
case '#': {
Token<CppTokenId> out = finishSharp();
assert out != null : "not handled #";
return out;
}
case '/':
switch (read(true)) {
case '/': // in single-line or doxygen comment
{
Token<CppTokenId> out = finishLineComment(true);
assert out != null : "not handled //";
return out;
}
case '=': // found /=
return token(CppTokenId.SLASHEQ);
case '*': // in multi-line or doxygen comment
{
Token<CppTokenId> out = finishBlockComment(true);
assert out != null : "not handled /*";
return out;
}
} // end of switch()
backup(1);
return token(CppTokenId.SLASH);
case '=':
if (read(true) == '=') {
return token(CppTokenId.EQEQ);
}
backup(1);
return token(CppTokenId.EQ);
case '>':
switch (read(true)) {
case '>': // >>
if (read(true) == '=') {
return token(CppTokenId.GTGTEQ);
}
backup(1);
return token(CppTokenId.GTGT);
case '=': // >=
return token(CppTokenId.GTEQ);
}
backup(1);
return token(CppTokenId.GT);
case '<': {
Token<CppTokenId> out = finishLT();
assert out != null : "not handled '<'";
return out;
}
case '+':
switch (read(true)) {
case '+':
return token(CppTokenId.PLUSPLUS);
case '=':
return token(CppTokenId.PLUSEQ);
}
backup(1);
return token(CppTokenId.PLUS);
case '-':
switch (read(true)) {
case '-':
return token(CppTokenId.MINUSMINUS);
case '>':
if (read(true) == '*') {
return token(CppTokenId.ARROWMBR);
}
backup(1);
return token(CppTokenId.ARROW);
case '=':
return token(CppTokenId.MINUSEQ);
}
backup(1);
return token(CppTokenId.MINUS);
case '*':
switch (read(true)) {
case '/': // invalid comment end - */ or int*/* */
if (read(true) == '*') {
backup(2);
return token(CppTokenId.STAR);
}
backup(1);
return token(CppTokenId.INVALID_COMMENT_END);
case '=':
return token(CppTokenId.STAREQ);
}
backup(1);
return token(CppTokenId.STAR);
case '|':
switch (read(true)) {
case '|':
return token(CppTokenId.BARBAR);
case '=':
return token(CppTokenId.BAREQ);
}
backup(1);
return token(CppTokenId.BAR);
case '&':
switch (read(true)) {
case '&':
return token(CppTokenId.AMPAMP);
case '=':
return token(CppTokenId.AMPEQ);
}
backup(1);
return token(CppTokenId.AMP);
case '%': {
Token<CppTokenId> out = finishPercent();
assert out != null : "not handled %";
return out;
}
case '^':
if (read(true) == '=') {
return token(CppTokenId.CARETEQ);
}
backup(1);
return token(CppTokenId.CARET);
case '!':
if (read(true) == '=') {
return token(CppTokenId.NOTEQ);
}
backup(1);
return token(CppTokenId.NOT);
case '.':
if ((c = read(true)) == '.') {
if (read(true) == '.') { // ellipsis ...
return token(CppTokenId.ELLIPSIS);
} else {
input.backup(2);
}
} else if ('0' <= c && c <= '9') { // float literal
return finishNumberLiteral(read(true), true);
} else if (c == '*') {
return token(CppTokenId.DOTMBR);
} else {
backup(1);
}
return token(CppTokenId.DOT);
case ':':
if (read(true) == ':') {
return token(CppTokenId.SCOPE);
}
backup(1);
return token(CppTokenId.COLON);
case '~':
return token(CppTokenId.TILDE);
case ',':
return token(CppTokenId.COMMA);
case ';':
return token(CppTokenId.SEMICOLON);
case '?':
return token(CppTokenId.QUESTION);
case '(':
return token(CppTokenId.LPAREN);
case ')':
return token(CppTokenId.RPAREN);
case '[':
return token(CppTokenId.LBRACKET);
case ']':
return token(CppTokenId.RBRACKET);
case '{':
return token(CppTokenId.LBRACE);
case '}':
return token(CppTokenId.RBRACE);
case '`':
return token(CppTokenId.GRAVE_ACCENT);
case '@':
return token(CppTokenId.AT);
case '0': // in a number literal
c = read(true);
if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal
c == 'b' || c == 'B' ) { // in bianry literal
boolean inFraction = false;
while (true) {
switch (read(true)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
break;
case '.': // hex float literal
if (!inFraction) {
inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow
// ['\t' - '\f'] and [0x1c - ' ']
case '\t':
case 0x0b:
case '\f':
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
return finishWhitespace();
case ' ':
c = read(true);
if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token
backup(1);
return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N
}
return finishWhitespace();
case EOF:
if (isTokenSplittedByEscapedLine()) {
backup(1);
assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine;
break;
}
return null;
case '$':
// dollar is extension in gcc and msvc $ is a valid start of identifiers
// return token(CppTokenId.DOLLAR);
default:
c = translateSurrogates(c);
if (CndLexerUtilities.isCppIdentifierStart(c)) {
if (c == 'L' || c == 'U' || c == 'u' || c == 'R') {
int next = read(true);
boolean raw_string = (c == 'R');
if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) {
// uR, UR or LR
raw_string = true;
next = read(true);
} else if (next == '8' && c == 'u') {
// u8
next = read(true);
if (next == 'R') {
// u8R
raw_string = true;
next = read(true);
}
}
if (next == '"') {
// string with L/U/u/R prefixes
Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote();
assert out != null : "not handled dobule quote";
return out;
} else if (next == '\'' && !raw_string) {
// char with L or U/u prefix
Token<CppTokenId> out = finishSingleQuote();
assert out != null : "not handled single quote";
return out;
} else {
backup(1);
}
}
if (c == 'E') {
if(isExecSQL(c)) {
Token<CppTokenId> out = finishExecSQL();
assert out != null : "not handled exec sql";
return out;
}
}
return keywordOrIdentifier(c);
}
if (Character.isWhitespace(c)) {
return finishWhitespace();
}
// Invalid char
return token(CppTokenId.ERROR);
}
} // end of switch (c)
} // end of while(true)
} | NONSATD | true | : CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false); | return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8': | inFraction = true;
} else { // two dots in the float literal
return token(CppTokenId.FLOAT_LITERAL_INVALID);
}
break;
case 'l':
case 'L': // 0x1234l or 0x1234L
return finishLongLiteral(read(true));
case 'p':
case 'P': // binary exponent
return finishFloatExponent();
case 'u':
case 'U':
return finishUnsignedLiteral(read(true));
default:
backup(1);
// if float then before mandatory binary exponent => invalid
return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID
: CppTokenId.INT_LITERAL);
}
} // end of while(true)
}
return finishNumberLiteral(c, false);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return finishNumberLiteral(read(true), false);
case '\\':
return token(CppTokenId.BACK_SLASH);
case '\r':
consumeNewline();
return token(CppTokenId.NEW_LINE);
case '\n':
return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N
// All Character.isWhitespace(c) below 0x80 follow |
733 | 0 | /** Called by LockssTestCase.tearDown() to prevent events from happening
* after tests complete. tk - fix when this is made a LockssManager. */ | public static void stopTimerQueue() {
singleton.stop();
singleton.queue = new PriorityQueue();
} | DEFECT | true | public static void stopTimerQueue() {
singleton.stop();
singleton.queue = new PriorityQueue();
} | public static void stopTimerQueue() {
singleton.stop();
singleton.queue = new PriorityQueue();
} | public static void stopTimerQueue() {
singleton.stop();
singleton.queue = new PriorityQueue();
} |
17,124 | 0 | //This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} | TEST | true | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts); | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} |
17,124 | 1 | //When | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} | NONSATD | true | ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} |
17,124 | 2 | //Then | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} | NONSATD | true | //When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test")); | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} | @Test
public void simpleEndpointReturnsPostsWithoutTransformation() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
ForumPosts posts = generateTestPosts();
when(exampleApiService.getPosts()).thenReturn(posts);
//When
ForumPosts controllerOutput = exerciseController.posts();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
} |
17,125 | 0 | //This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} | TEST | true | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed); | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} |
17,125 | 1 | //When | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} | NONSATD | true | TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} |
17,125 | 2 | //Then | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} | NONSATD | true | //When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test")); | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} | @Test
public void transformedEndpointReturnsPostsWithCurrentDate() {
//This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test
//Given
TransformedForumPosts transformed = generateTransformedTestPosts();
when(exampleApiService.getTransformedPosts()).thenReturn(transformed);
//When
TransformedForumPosts controllerOutput = exerciseController.transformed();
//Then
assertEquals(controllerOutput.size(), 2);
assertTrue(controllerOutput.get(0).getTitle().contains("Test"));
assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST"));
assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d"));
} |
25,316 | 0 | // caused issues https://github.com/holgerbrandl/r4intellij/issues/79 | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result;
} | DEFECT | true | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>(); | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath())); | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result;
} |
25,316 | 1 | // does not work in tests | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result;
} | DEFECT | true | final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) { | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result; | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result;
} |
25,316 | 2 | // final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName); | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result;
} | NONSATD | true | final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) { | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result;
} | @Deprecated // caused issues https://github.com/holgerbrandl/r4intellij/issues/79
private static ArrayList<String> getInstallationFromPaths(@NotNull final String scriptName, @NotNull final String[] paths) {
final ArrayList<String> result = new ArrayList<String>();
for (String path : paths) {
// does not work in tests
final VirtualFile rootVDir = LocalFileSystem.getInstance().findFileByPath(path);
if (rootVDir != null) {
// final VirtualFile rScript = rootVDir.findFileByRelativePath("bin/" + scriptName);
final File rScript = findScript(scriptName, path);
if (rScript != null) {
result.add(FileUtil.toSystemDependentName(rScript.getPath()));
}
}
}
return result;
} |
33,512 | 0 | // TODO some way to make this change based on how long button is held? | @Override
public void doServerTick(World world)
{
super.doServerTick(world);
Entity rider = entity.getControllingPassenger();
pokemob.setGeneralState(GeneralStates.CONTROLLED, rider != null);
if (rider == null) return;
Config config = PokecubeCore.instance.getConfig();
boolean move = false;
entity.rotationYaw = pokemob.getHeading();
boolean shouldControl = entity.onGround || pokemob.floats();
boolean verticalControl = false;
boolean waterSpeed = false;
boolean airSpeed = !entity.onGround;
boolean canFly = pokemob.canUseFly();
boolean canSurf = pokemob.canUseSurf();
boolean canDive = pokemob.canUseDive();
if (rider instanceof EntityPlayerMP)
{
EntityPlayer player = (EntityPlayer) rider;
IPermissionHandler handler = PermissionAPI.getPermissionHandler();
PlayerContext context = new PlayerContext(player);
PokedexEntry entry = pokemob.getPokedexEntry();
if (config.permsFly && canFly
&& !handler.hasPermission(player.getGameProfile(), Permissions.FLYPOKEMOB, context))
{
canFly = false;
}
if (config.permsFlySpecific && canFly
&& !handler.hasPermission(player.getGameProfile(), Permissions.FLYSPECIFIC.get(entry), context))
{
canFly = false;
}
if (config.permsSurf && canSurf
&& !handler.hasPermission(player.getGameProfile(), Permissions.SURFPOKEMOB, context))
{
canSurf = false;
}
if (config.permsSurfSpecific && canSurf
&& !handler.hasPermission(player.getGameProfile(), Permissions.SURFSPECIFIC.get(entry), context))
{
canSurf = false;
}
if (config.permsDive && canDive
&& !handler.hasPermission(player.getGameProfile(), Permissions.DIVEPOKEMOB, context))
{
canDive = false;
}
if (config.permsDiveSpecific && canDive
&& !handler.hasPermission(player.getGameProfile(), Permissions.DIVESPECIFIC.get(entry), context))
{
canDive = false;
}
}
if (canFly) for (int i = 0; i < PokecubeMod.core.getConfig().flyDimBlacklist.length; i++)
if (PokecubeMod.core.getConfig().flyDimBlacklist[i] == world.provider.getDimension())
{
canFly = false;
break;
}
if (canFly) shouldControl = verticalControl = PokecubeMod.core.getConfig().flyEnabled || shouldControl;
if ((canSurf || canDive) && (waterSpeed = entity.isInWater()))
shouldControl = verticalControl = PokecubeMod.core.getConfig().surfEnabled || shouldControl;
if (waterSpeed) airSpeed = false;
Entity controller = rider;
if (pokemob.getPokedexEntry().shouldDive)
{
PotionEffect vision = new PotionEffect(Potion.getPotionFromResourceLocation("night_vision"), 300, 1, true,
false);
ItemStack stack = new ItemStack(Blocks.BARRIER);
vision.setCurativeItems(Lists.newArrayList(stack));
for (Entity e : entity.getRecursivePassengers())
{
if (e instanceof EntityLivingBase)
{
if (entity.isInWater())
{
((EntityLivingBase) e).addPotionEffect(vision);
((EntityLivingBase) e).setAir(300);
}
else((EntityLivingBase) e).curePotionEffects(stack);
}
}
}
float speedFactor = (float) (1 + Math.sqrt(pokemob.getPokedexEntry().getStatVIT()) / (10F));
float moveSpeed = (float) (0.25f * throttle * speedFactor);
if (forwardInputDown)
{
move = true;
float f = moveSpeed / 2;
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
if (shouldControl)
{
if (!entity.onGround) f *= 2;
entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f;
}
else if (entity.isInLava() || entity.isInWater())
{
f *= 0.1;
entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f;
}
}
if (backInputDown)
{
move = true;
float f = -moveSpeed / 4;
if (shouldControl)
{
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f;
}
}
if (upInputDown)
{
if (entity.onGround)
{
entity.getJumpHelper().setJumping();
}
else if (verticalControl)
{
entity.motionY += 0.1 * throttle;
}
else if (entity.isInLava() || entity.isInWater())
{
entity.motionY += 0.05 * throttle;
}
}
if (downInputDown)
{
if (verticalControl && !entity.onGround)
{
entity.motionY -= 0.1 * throttle;
}
}
else if (!verticalControl && !entity.onGround)
{
entity.motionY -= 0.1;
}
if (!followOwnerLook)
{// TODO some way to make this change based on how long button is held?
if (leftInputDown)
{
pokemob.setHeading(pokemob.getHeading() - 5);
}
if (rightInputDown)
{
pokemob.setHeading(pokemob.getHeading() + 5);
}
}
else if (!entity.getPassengers().isEmpty())
{
pokemob.setHeading(controller.rotationYaw);
float f = moveSpeed / 2;
if (leftInputDown)
{
move = true;
if (shouldControl)
{
if (!entity.onGround) f *= 2;
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
else if (entity.isInLava() || entity.isInWater())
{
f *= 0.1;
entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
}
if (rightInputDown)
{
move = true;
if (shouldControl)
{
if (!entity.onGround) f *= 2;
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
else if (entity.isInLava() || entity.isInWater())
{
f *= 0.1;
entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
}
}
if (!move)
{
entity.motionX *= 0.5;
entity.motionZ *= 0.5;
}
// Sync the rotations.
entity.setRenderYawOffset(pokemob.getHeading());
entity.setRotationYawHead(pokemob.getHeading());
} | DESIGN | true | }
if (!followOwnerLook)
{// TODO some way to make this change based on how long button is held?
if (leftInputDown)
{ | if (verticalControl && !entity.onGround)
{
entity.motionY -= 0.1 * throttle;
}
}
else if (!verticalControl && !entity.onGround)
{
entity.motionY -= 0.1;
}
if (!followOwnerLook)
{// TODO some way to make this change based on how long button is held?
if (leftInputDown)
{
pokemob.setHeading(pokemob.getHeading() - 5);
}
if (rightInputDown)
{
pokemob.setHeading(pokemob.getHeading() + 5);
}
}
else if (!entity.getPassengers().isEmpty()) | {
entity.motionY += 0.1 * throttle;
}
else if (entity.isInLava() || entity.isInWater())
{
entity.motionY += 0.05 * throttle;
}
}
if (downInputDown)
{
if (verticalControl && !entity.onGround)
{
entity.motionY -= 0.1 * throttle;
}
}
else if (!verticalControl && !entity.onGround)
{
entity.motionY -= 0.1;
}
if (!followOwnerLook)
{// TODO some way to make this change based on how long button is held?
if (leftInputDown)
{
pokemob.setHeading(pokemob.getHeading() - 5);
}
if (rightInputDown)
{
pokemob.setHeading(pokemob.getHeading() + 5);
}
}
else if (!entity.getPassengers().isEmpty())
{
pokemob.setHeading(controller.rotationYaw);
float f = moveSpeed / 2;
if (leftInputDown)
{
move = true;
if (shouldControl)
{
if (!entity.onGround) f *= 2;
if (airSpeed) f *= config.flySpeedFactor; |
33,512 | 1 | // Sync the rotations. | @Override
public void doServerTick(World world)
{
super.doServerTick(world);
Entity rider = entity.getControllingPassenger();
pokemob.setGeneralState(GeneralStates.CONTROLLED, rider != null);
if (rider == null) return;
Config config = PokecubeCore.instance.getConfig();
boolean move = false;
entity.rotationYaw = pokemob.getHeading();
boolean shouldControl = entity.onGround || pokemob.floats();
boolean verticalControl = false;
boolean waterSpeed = false;
boolean airSpeed = !entity.onGround;
boolean canFly = pokemob.canUseFly();
boolean canSurf = pokemob.canUseSurf();
boolean canDive = pokemob.canUseDive();
if (rider instanceof EntityPlayerMP)
{
EntityPlayer player = (EntityPlayer) rider;
IPermissionHandler handler = PermissionAPI.getPermissionHandler();
PlayerContext context = new PlayerContext(player);
PokedexEntry entry = pokemob.getPokedexEntry();
if (config.permsFly && canFly
&& !handler.hasPermission(player.getGameProfile(), Permissions.FLYPOKEMOB, context))
{
canFly = false;
}
if (config.permsFlySpecific && canFly
&& !handler.hasPermission(player.getGameProfile(), Permissions.FLYSPECIFIC.get(entry), context))
{
canFly = false;
}
if (config.permsSurf && canSurf
&& !handler.hasPermission(player.getGameProfile(), Permissions.SURFPOKEMOB, context))
{
canSurf = false;
}
if (config.permsSurfSpecific && canSurf
&& !handler.hasPermission(player.getGameProfile(), Permissions.SURFSPECIFIC.get(entry), context))
{
canSurf = false;
}
if (config.permsDive && canDive
&& !handler.hasPermission(player.getGameProfile(), Permissions.DIVEPOKEMOB, context))
{
canDive = false;
}
if (config.permsDiveSpecific && canDive
&& !handler.hasPermission(player.getGameProfile(), Permissions.DIVESPECIFIC.get(entry), context))
{
canDive = false;
}
}
if (canFly) for (int i = 0; i < PokecubeMod.core.getConfig().flyDimBlacklist.length; i++)
if (PokecubeMod.core.getConfig().flyDimBlacklist[i] == world.provider.getDimension())
{
canFly = false;
break;
}
if (canFly) shouldControl = verticalControl = PokecubeMod.core.getConfig().flyEnabled || shouldControl;
if ((canSurf || canDive) && (waterSpeed = entity.isInWater()))
shouldControl = verticalControl = PokecubeMod.core.getConfig().surfEnabled || shouldControl;
if (waterSpeed) airSpeed = false;
Entity controller = rider;
if (pokemob.getPokedexEntry().shouldDive)
{
PotionEffect vision = new PotionEffect(Potion.getPotionFromResourceLocation("night_vision"), 300, 1, true,
false);
ItemStack stack = new ItemStack(Blocks.BARRIER);
vision.setCurativeItems(Lists.newArrayList(stack));
for (Entity e : entity.getRecursivePassengers())
{
if (e instanceof EntityLivingBase)
{
if (entity.isInWater())
{
((EntityLivingBase) e).addPotionEffect(vision);
((EntityLivingBase) e).setAir(300);
}
else((EntityLivingBase) e).curePotionEffects(stack);
}
}
}
float speedFactor = (float) (1 + Math.sqrt(pokemob.getPokedexEntry().getStatVIT()) / (10F));
float moveSpeed = (float) (0.25f * throttle * speedFactor);
if (forwardInputDown)
{
move = true;
float f = moveSpeed / 2;
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
if (shouldControl)
{
if (!entity.onGround) f *= 2;
entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f;
}
else if (entity.isInLava() || entity.isInWater())
{
f *= 0.1;
entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f;
}
}
if (backInputDown)
{
move = true;
float f = -moveSpeed / 4;
if (shouldControl)
{
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f;
}
}
if (upInputDown)
{
if (entity.onGround)
{
entity.getJumpHelper().setJumping();
}
else if (verticalControl)
{
entity.motionY += 0.1 * throttle;
}
else if (entity.isInLava() || entity.isInWater())
{
entity.motionY += 0.05 * throttle;
}
}
if (downInputDown)
{
if (verticalControl && !entity.onGround)
{
entity.motionY -= 0.1 * throttle;
}
}
else if (!verticalControl && !entity.onGround)
{
entity.motionY -= 0.1;
}
if (!followOwnerLook)
{// TODO some way to make this change based on how long button is held?
if (leftInputDown)
{
pokemob.setHeading(pokemob.getHeading() - 5);
}
if (rightInputDown)
{
pokemob.setHeading(pokemob.getHeading() + 5);
}
}
else if (!entity.getPassengers().isEmpty())
{
pokemob.setHeading(controller.rotationYaw);
float f = moveSpeed / 2;
if (leftInputDown)
{
move = true;
if (shouldControl)
{
if (!entity.onGround) f *= 2;
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
else if (entity.isInLava() || entity.isInWater())
{
f *= 0.1;
entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
}
if (rightInputDown)
{
move = true;
if (shouldControl)
{
if (!entity.onGround) f *= 2;
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
else if (entity.isInLava() || entity.isInWater())
{
f *= 0.1;
entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
}
}
if (!move)
{
entity.motionX *= 0.5;
entity.motionZ *= 0.5;
}
// Sync the rotations.
entity.setRenderYawOffset(pokemob.getHeading());
entity.setRotationYawHead(pokemob.getHeading());
} | NONSATD | true | entity.motionZ *= 0.5;
}
// Sync the rotations.
entity.setRenderYawOffset(pokemob.getHeading());
entity.setRotationYawHead(pokemob.getHeading()); | entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
}
}
if (!move)
{
entity.motionX *= 0.5;
entity.motionZ *= 0.5;
}
// Sync the rotations.
entity.setRenderYawOffset(pokemob.getHeading());
entity.setRotationYawHead(pokemob.getHeading());
} | if (!entity.onGround) f *= 2;
if (airSpeed) f *= config.flySpeedFactor;
else if (waterSpeed) f *= config.surfSpeedFactor;
else f *= config.groundSpeedFactor;
entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
else if (entity.isInLava() || entity.isInWater())
{
f *= 0.1;
entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f;
entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f;
}
}
}
if (!move)
{
entity.motionX *= 0.5;
entity.motionZ *= 0.5;
}
// Sync the rotations.
entity.setRenderYawOffset(pokemob.getHeading());
entity.setRotationYawHead(pokemob.getHeading());
} |
17,130 | 0 | /** Updates the task */ | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | NONSATD | true | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} |
17,130 | 1 | //this.host.getEntitySenses().canSee(this.attackTarget); | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | NONSATD | true | {
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{ | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{ | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{ |
17,130 | 2 | // TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f); | @Override
public void updateTask()
{
double distanceFromTarget = this.host.getDistanceSq(host.getAttackTarget().posX, host.getAttackTarget().boundingBox.minY, host.getAttackTarget().posZ);
boolean canSeeTarget = true; //this.host.getEntitySenses().canSee(this.attackTarget);
if (canSeeTarget)
{
++this.targetTimeLost;
}
else
{
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | DESIGN | true | }
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
} | }
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} | {
this.targetTimeLost = 0;
}
if (distanceFromTarget <= (double) this.followDistance && this.targetTimeLost >= 20)
{
this.host.getNavigator().clearPathEntity();
}
else
{
this.host.getNavigator().tryMoveToEntityLiving(host.getAttackTarget(), this.entityMoveSpeed);
}
this.host.getLookHelper().setLookPositionWithEntity(host.getAttackTarget(), 30.0F, 30.0F);
float f;
if (--this.rangedAttackTime == 0)
{
if (distanceFromTarget > (double) this.followDistance || !canSeeTarget)
{
return;
}
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
// TODO replace this.rangedAttackEntityHost.attackEntityWithRangedAttack(thost.getAttackTarget(), f);
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
else if (this.rangedAttackTime < 0)
{
f = MathHelper.sqrt_double(distanceFromTarget) / this.attackRange;
this.rangedAttackTime = MathHelper.floor_float(f * (float) (this.maxRangedAttackTime - this.minRangedAttackTime) + (float) this.minRangedAttackTime);
}
} |
748 | 0 | /**Method called from Server when the 'api/todos/new'endpoint is recieved.
* Gets specified todo info from request and calls addNewTodo helper method
* to append that info to a document
*
* @param req the HTTP request
* @param res the HTTP response
* @return a boolean as whether the todo was added successfully or not
*/ | public boolean addNewTodo(Request req, Response res)
{
res.type("application/json");
Object o = JSON.parse(req.body());
try {
if(o.getClass().equals(BasicDBObject.class))
{
try {
BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body");
String category = dbO.getString("category");
System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']');
return todoController.addNewTodo(owner, category, body, status);
}
catch(NullPointerException e)
{
System.err.println("A value was malformed or omitted, new todo request failed.");
return false;
}
}
else
{
System.err.println("Expected BasicDBObject, received " + o.getClass());
return false;
}
}
catch(RuntimeException ree)
{
ree.printStackTrace();
return false;
}
} | NONSATD | true | public boolean addNewTodo(Request req, Response res)
{
res.type("application/json");
Object o = JSON.parse(req.body());
try {
if(o.getClass().equals(BasicDBObject.class))
{
try {
BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body");
String category = dbO.getString("category");
System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']');
return todoController.addNewTodo(owner, category, body, status);
}
catch(NullPointerException e)
{
System.err.println("A value was malformed or omitted, new todo request failed.");
return false;
}
}
else
{
System.err.println("Expected BasicDBObject, received " + o.getClass());
return false;
}
}
catch(RuntimeException ree)
{
ree.printStackTrace();
return false;
}
} | public boolean addNewTodo(Request req, Response res)
{
res.type("application/json");
Object o = JSON.parse(req.body());
try {
if(o.getClass().equals(BasicDBObject.class))
{
try {
BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body");
String category = dbO.getString("category");
System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']');
return todoController.addNewTodo(owner, category, body, status);
}
catch(NullPointerException e)
{
System.err.println("A value was malformed or omitted, new todo request failed.");
return false;
}
}
else
{
System.err.println("Expected BasicDBObject, received " + o.getClass());
return false;
}
}
catch(RuntimeException ree)
{
ree.printStackTrace();
return false;
}
} | public boolean addNewTodo(Request req, Response res)
{
res.type("application/json");
Object o = JSON.parse(req.body());
try {
if(o.getClass().equals(BasicDBObject.class))
{
try {
BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body");
String category = dbO.getString("category");
System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']');
return todoController.addNewTodo(owner, category, body, status);
}
catch(NullPointerException e)
{
System.err.println("A value was malformed or omitted, new todo request failed.");
return false;
}
}
else
{
System.err.println("Expected BasicDBObject, received " + o.getClass());
return false;
}
}
catch(RuntimeException ree)
{
ree.printStackTrace();
return false;
}
} |
748 | 1 | //For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go | public boolean addNewTodo(Request req, Response res)
{
res.type("application/json");
Object o = JSON.parse(req.body());
try {
if(o.getClass().equals(BasicDBObject.class))
{
try {
BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body");
String category = dbO.getString("category");
System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']');
return todoController.addNewTodo(owner, category, body, status);
}
catch(NullPointerException e)
{
System.err.println("A value was malformed or omitted, new todo request failed.");
return false;
}
}
else
{
System.err.println("Expected BasicDBObject, received " + o.getClass());
return false;
}
}
catch(RuntimeException ree)
{
ree.printStackTrace();
return false;
}
} | DEFECT | true | BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body"); | public boolean addNewTodo(Request req, Response res)
{
res.type("application/json");
Object o = JSON.parse(req.body());
try {
if(o.getClass().equals(BasicDBObject.class))
{
try {
BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body");
String category = dbO.getString("category");
System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']');
return todoController.addNewTodo(owner, category, body, status);
}
catch(NullPointerException e)
{
System.err.println("A value was malformed or omitted, new todo request failed.");
return false; | public boolean addNewTodo(Request req, Response res)
{
res.type("application/json");
Object o = JSON.parse(req.body());
try {
if(o.getClass().equals(BasicDBObject.class))
{
try {
BasicDBObject dbO = (BasicDBObject) o;
String owner = dbO.getString("owner");
//For some reason age is a string right now, caused by angular.
//This is a problem and should not be this way but here ya go
boolean status = dbO.getBoolean("status");
String body = dbO.getString("body");
String category = dbO.getString("category");
System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']');
return todoController.addNewTodo(owner, category, body, status);
}
catch(NullPointerException e)
{
System.err.println("A value was malformed or omitted, new todo request failed.");
return false;
}
}
else
{
System.err.println("Expected BasicDBObject, received " + o.getClass());
return false;
}
}
catch(RuntimeException ree)
{ |
8,942 | 0 | // TODO: allow user to not choose a date (and make the datepicker look a lot better) | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>(
this, android.R.layout.simple_list_item_1, TodoItem.Priority.values());
spPriority.setAdapter(priorityAdapter);
int priorityIndex = item.getPriority().ordinal();
spPriority.setSelection(priorityIndex);
} | DESIGN | true | etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate(); | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT); | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>(
this, android.R.layout.simple_list_item_1, TodoItem.Priority.values());
spPriority.setAdapter(priorityAdapter);
int priorityIndex = item.getPriority().ordinal(); |
8,942 | 1 | /*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/ | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>(
this, android.R.layout.simple_list_item_1, TodoItem.Priority.values());
spPriority.setAdapter(priorityAdapter);
int priorityIndex = item.getPriority().ordinal();
spPriority.setSelection(priorityIndex);
} | NONSATD | true | String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>( | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>(
this, android.R.layout.simple_list_item_1, TodoItem.Priority.values());
spPriority.setAdapter(priorityAdapter);
int priorityIndex = item.getPriority().ordinal();
spPriority.setSelection(priorityIndex);
} | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>(
this, android.R.layout.simple_list_item_1, TodoItem.Priority.values());
spPriority.setAdapter(priorityAdapter);
int priorityIndex = item.getPriority().ordinal();
spPriority.setSelection(priorityIndex);
} |
752 | 0 | //todo so currently we execute the qstat for each job but we can use user based monitoring
//todo or we should concatenate all the commands and execute them in one go and parse the response | public JobState getJobStatus(MonitorID monitorID) throws SSHApiException {
String jobID = monitorID.getJobID();
//todo so currently we execute the qstat for each job but we can use user based monitoring
//todo or we should concatenate all the commands and execute them in one go and parse the response
return getStatusFromString(cluster.getJobStatus(jobID).toString());
} | DESIGN | true | public JobState getJobStatus(MonitorID monitorID) throws SSHApiException {
String jobID = monitorID.getJobID();
//todo so currently we execute the qstat for each job but we can use user based monitoring
//todo or we should concatenate all the commands and execute them in one go and parse the response
return getStatusFromString(cluster.getJobStatus(jobID).toString());
} | public JobState getJobStatus(MonitorID monitorID) throws SSHApiException {
String jobID = monitorID.getJobID();
//todo so currently we execute the qstat for each job but we can use user based monitoring
//todo or we should concatenate all the commands and execute them in one go and parse the response
return getStatusFromString(cluster.getJobStatus(jobID).toString());
} | public JobState getJobStatus(MonitorID monitorID) throws SSHApiException {
String jobID = monitorID.getJobID();
//todo so currently we execute the qstat for each job but we can use user based monitoring
//todo or we should concatenate all the commands and execute them in one go and parse the response
return getStatusFromString(cluster.getJobStatus(jobID).toString());
} |
25,329 | 0 | // This isn't good, the Jedis object is not thread safe | public void shutdown() {
try {
LOGGER.info("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
jedis.disconnect();
} catch (Exception e) {
LOGGER.error("Caught exception while shutting down: " + e.getMessage());
}
} | DESIGN | true | LOGGER.info("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
jedis.disconnect();
} catch (Exception e) { | public void shutdown() {
try {
LOGGER.info("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
jedis.disconnect();
} catch (Exception e) {
LOGGER.error("Caught exception while shutting down: " + e.getMessage());
}
} | public void shutdown() {
try {
LOGGER.info("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
jedis.disconnect();
} catch (Exception e) {
LOGGER.error("Caught exception while shutting down: " + e.getMessage());
}
} |
776 | 0 | // TODO This will be implemented in the next version | @Override
public int write(ChannelBuffer cb) {
// TODO This will be implemented in the next version
return 0;
} | IMPLEMENTATION | true | @Override
public int write(ChannelBuffer cb) {
// TODO This will be implemented in the next version
return 0;
} | @Override
public int write(ChannelBuffer cb) {
// TODO This will be implemented in the next version
return 0;
} | @Override
public int write(ChannelBuffer cb) {
// TODO This will be implemented in the next version
return 0;
} |
781 | 0 | // TODO: smarter initialization of the map | private Map<String, T> getChoiceMap() {
if (choiceMap == null || alwaysReload()) {
Collection<T> choices = loadChoices();
choiceMap = new HashMap<>();
for (T choice: choices) {
// TODO: smarter initialization of the map
choiceMap.put(choice.getLocalPart(), choice);
}
}
return choiceMap;
} | DESIGN | true | choiceMap = new HashMap<>();
for (T choice: choices) {
// TODO: smarter initialization of the map
choiceMap.put(choice.getLocalPart(), choice);
} | private Map<String, T> getChoiceMap() {
if (choiceMap == null || alwaysReload()) {
Collection<T> choices = loadChoices();
choiceMap = new HashMap<>();
for (T choice: choices) {
// TODO: smarter initialization of the map
choiceMap.put(choice.getLocalPart(), choice);
}
}
return choiceMap;
} | private Map<String, T> getChoiceMap() {
if (choiceMap == null || alwaysReload()) {
Collection<T> choices = loadChoices();
choiceMap = new HashMap<>();
for (T choice: choices) {
// TODO: smarter initialization of the map
choiceMap.put(choice.getLocalPart(), choice);
}
}
return choiceMap;
} |
784 | 0 | //Fix or deprecate fromExecutor, this test might randomly hang on CI | @Test
@Ignore //Fix or deprecate fromExecutor, this test might randomly hang on CI
public void rejectedExecutionExceptionOnErrorSignalExecutor()
throws InterruptedException {
Exception exception = new IllegalStateException();
final AtomicReference<Throwable> throwableInOnOperatorError =
new AtomicReference<>();
final AtomicReference<Object> dataInOnOperatorError = new AtomicReference<>();
try {
CountDownLatch hookLatch = new CountDownLatch(2);
Hooks.onOperatorError((t, d) -> {
throwableInOnOperatorError.set(t);
dataInOnOperatorError.set(d);
hookLatch.countDown();
return t;
});
ExecutorService executor = newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(1);
AssertSubscriber<Integer> assertSubscriber = new AssertSubscriber<>();
Flux.range(0, 5)
.publishOn(fromExecutorService(executor))
.doOnNext(s -> {
try {
latch.await();
}
catch (InterruptedException e) {
throw Exceptions.propagate(exception);
}
})
.publishOn(fromExecutor(executor))
.subscribe(assertSubscriber);
executor.shutdownNow();
assertSubscriber.assertNoValues()
.assertNoError()
.assertNotComplete();
hookLatch.await();
assertThat(throwableInOnOperatorError.get()).isInstanceOf(RejectedExecutionException.class);
assertThat(throwableInOnOperatorError.get().getSuppressed()[0]).isSameAs(exception);
}
finally {
Hooks.resetOnOperatorError();
}
} | TEST | true | @Test
@Ignore //Fix or deprecate fromExecutor, this test might randomly hang on CI
public void rejectedExecutionExceptionOnErrorSignalExecutor()
throws InterruptedException { | @Test
@Ignore //Fix or deprecate fromExecutor, this test might randomly hang on CI
public void rejectedExecutionExceptionOnErrorSignalExecutor()
throws InterruptedException {
Exception exception = new IllegalStateException();
final AtomicReference<Throwable> throwableInOnOperatorError =
new AtomicReference<>();
final AtomicReference<Object> dataInOnOperatorError = new AtomicReference<>();
try {
CountDownLatch hookLatch = new CountDownLatch(2);
Hooks.onOperatorError((t, d) -> {
throwableInOnOperatorError.set(t); | @Test
@Ignore //Fix or deprecate fromExecutor, this test might randomly hang on CI
public void rejectedExecutionExceptionOnErrorSignalExecutor()
throws InterruptedException {
Exception exception = new IllegalStateException();
final AtomicReference<Throwable> throwableInOnOperatorError =
new AtomicReference<>();
final AtomicReference<Object> dataInOnOperatorError = new AtomicReference<>();
try {
CountDownLatch hookLatch = new CountDownLatch(2);
Hooks.onOperatorError((t, d) -> {
throwableInOnOperatorError.set(t);
dataInOnOperatorError.set(d);
hookLatch.countDown();
return t;
});
ExecutorService executor = newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(1);
AssertSubscriber<Integer> assertSubscriber = new AssertSubscriber<>();
Flux.range(0, 5)
.publishOn(fromExecutorService(executor))
.doOnNext(s -> { |
25,367 | 0 | // TODO what happens if solver hasn't started yet (solve() is called asynchronously) | void stopSolver() {
if (solverFuture != null) {
// TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions
try {
solverFuture.get();
solverFuture = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Failed to stop solver", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed to stop solver", e);
}
}
} | DESIGN | true | void stopSolver() {
if (solverFuture != null) {
// TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions | void stopSolver() {
if (solverFuture != null) {
// TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions
try {
solverFuture.get();
solverFuture = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Failed to stop solver", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed to stop solver", e); | void stopSolver() {
if (solverFuture != null) {
// TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions
try {
solverFuture.get();
solverFuture = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Failed to stop solver", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed to stop solver", e);
}
}
} |
25,367 | 1 | // make sure solver has terminated and propagate exceptions | void stopSolver() {
if (solverFuture != null) {
// TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions
try {
solverFuture.get();
solverFuture = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Failed to stop solver", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed to stop solver", e);
}
}
} | NONSATD | true | // TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions
try {
solverFuture.get(); | void stopSolver() {
if (solverFuture != null) {
// TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions
try {
solverFuture.get();
solverFuture = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Failed to stop solver", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed to stop solver", e);
}
} | void stopSolver() {
if (solverFuture != null) {
// TODO what happens if solver hasn't started yet (solve() is called asynchronously)
solver.terminateEarly();
// make sure solver has terminated and propagate exceptions
try {
solverFuture.get();
solverFuture = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Failed to stop solver", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed to stop solver", e);
}
}
} |
25,373 | 0 | //todo[nik] implement? | protected void evaluateAndShowHint() {
myEvaluator.evaluate(myExpression, new XEvaluationCallbackBase() {
public void evaluated(@NotNull final XValue result) {
result.computePresentation(new XValueNode() {
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value, boolean hasChildren) {
setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, hasChildren);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String separator, @NonNls @NotNull String value,
boolean hasChildren) {
setPresentation(icon, type, separator, value, null, hasChildren);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value,
@Nullable NotNullFunction<String, String> valuePresenter, boolean hasChildren) {
setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren);
}
@Override
public void setGroupingPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean expand) {
setPresentation(icon, value, valuePresenter, true);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean hasChildren) {
doSetPresentation(icon, null, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value, @Nullable final NotNullFunction<String, String> valuePresenter, final boolean hasChildren) {
doSetPresentation(icon, type, separator, value, valuePresenter == null ? null : new XValuePresenterAdapter(valuePresenter), hasChildren);
}
private void doSetPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @Nullable final String value, @Nullable final XValuePresenter valuePresenter, final boolean hasChildren) {
AppUIUtil.invokeOnEdt(new Runnable() {
public void run() {
doShowHint(result, separator, value, type, valuePresenter == null ? XValueNodeImpl.DEFAULT_VALUE_PRESENTER : valuePresenter, hasChildren);
}
});
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, value, hasChildren);
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, separator, value, hasChildren);
}
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() {
//todo[nik]
return false;
}
}, XValuePlace.TOOLTIP);
}
public void errorOccurred(@NotNull final String errorMessage) {
LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage);
}
}, myExpressionPosition);
} | IMPLEMENTATION | true | }
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() { | public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, value, hasChildren);
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, separator, value, hasChildren);
}
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() {
//todo[nik]
return false;
}
}, XValuePlace.TOOLTIP);
}
public void errorOccurred(@NotNull final String errorMessage) {
LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage);
} | doSetPresentation(icon, type, separator, value, valuePresenter == null ? null : new XValuePresenterAdapter(valuePresenter), hasChildren);
}
private void doSetPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @Nullable final String value, @Nullable final XValuePresenter valuePresenter, final boolean hasChildren) {
AppUIUtil.invokeOnEdt(new Runnable() {
public void run() {
doShowHint(result, separator, value, type, valuePresenter == null ? XValueNodeImpl.DEFAULT_VALUE_PRESENTER : valuePresenter, hasChildren);
}
});
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, value, hasChildren);
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, separator, value, hasChildren);
}
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() {
//todo[nik]
return false;
}
}, XValuePlace.TOOLTIP);
}
public void errorOccurred(@NotNull final String errorMessage) {
LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage);
}
}, myExpressionPosition);
} |
25,373 | 1 | //todo[nik] | protected void evaluateAndShowHint() {
myEvaluator.evaluate(myExpression, new XEvaluationCallbackBase() {
public void evaluated(@NotNull final XValue result) {
result.computePresentation(new XValueNode() {
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value, boolean hasChildren) {
setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, hasChildren);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String separator, @NonNls @NotNull String value,
boolean hasChildren) {
setPresentation(icon, type, separator, value, null, hasChildren);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value,
@Nullable NotNullFunction<String, String> valuePresenter, boolean hasChildren) {
setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren);
}
@Override
public void setGroupingPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean expand) {
setPresentation(icon, value, valuePresenter, true);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean hasChildren) {
doSetPresentation(icon, null, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren);
}
@Override
public void setPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value, @Nullable final NotNullFunction<String, String> valuePresenter, final boolean hasChildren) {
doSetPresentation(icon, type, separator, value, valuePresenter == null ? null : new XValuePresenterAdapter(valuePresenter), hasChildren);
}
private void doSetPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @Nullable final String value, @Nullable final XValuePresenter valuePresenter, final boolean hasChildren) {
AppUIUtil.invokeOnEdt(new Runnable() {
public void run() {
doShowHint(result, separator, value, type, valuePresenter == null ? XValueNodeImpl.DEFAULT_VALUE_PRESENTER : valuePresenter, hasChildren);
}
});
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, value, hasChildren);
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, separator, value, hasChildren);
}
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() {
//todo[nik]
return false;
}
}, XValuePlace.TOOLTIP);
}
public void errorOccurred(@NotNull final String errorMessage) {
LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage);
}
}, myExpressionPosition);
} | NONSATD | true | }
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() { | public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, value, hasChildren);
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, separator, value, hasChildren);
}
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() {
//todo[nik]
return false;
}
}, XValuePlace.TOOLTIP);
}
public void errorOccurred(@NotNull final String errorMessage) {
LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage);
} | doSetPresentation(icon, type, separator, value, valuePresenter == null ? null : new XValuePresenterAdapter(valuePresenter), hasChildren);
}
private void doSetPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @Nullable final String value, @Nullable final XValuePresenter valuePresenter, final boolean hasChildren) {
AppUIUtil.invokeOnEdt(new Runnable() {
public void run() {
doShowHint(result, separator, value, type, valuePresenter == null ? XValueNodeImpl.DEFAULT_VALUE_PRESENTER : valuePresenter, hasChildren);
}
});
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, value, hasChildren);
}
public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator,
@NonNls @NotNull final String value,
final boolean hasChildren) {
setPresentation(icon, type, separator, value, hasChildren);
}
public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) {
//todo[nik] implement?
}
public boolean isObsolete() {
//todo[nik]
return false;
}
}, XValuePlace.TOOLTIP);
}
public void errorOccurred(@NotNull final String errorMessage) {
LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage);
}
}, myExpressionPosition);
} |
17,189 | 0 | // TODO: would it make sense to return buffers asynchronously? | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | DESIGN | true | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} |
17,189 | 1 | // not a power of two, add one more | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | NONSATD | true | }
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2; | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
} | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize); |
17,189 | 2 | // TODO: reserving the entire thing is not ideal before we alloc anything. Interleave? | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | DESIGN | true | int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0; | throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated. | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
} |
17,189 | 3 | // TODO: pool of objects? | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | DESIGN | true | for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them. | int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do { | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex); |
17,189 | 4 | // First try to quickly lock some of the correct-sized free lists and allocate from them. | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | NONSATD | true | dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) { | freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return; | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky. |
17,189 | 5 | // Next arena is being allocated. | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | NONSATD | true | int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0; | // TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
} | throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2. |
17,189 | 6 | // TODO: check if it can still happen; count should take care of this. | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | IMPLEMENTATION | true | int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
} | int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us. | int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand" |
17,189 | 7 | // TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | DESIGN | true | } while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once | if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare. | // First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom()); |
17,189 | 8 | // Try to split bigger blocks. TODO: again, ideally we would tryLock at least once | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | DESIGN | true | // But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize); | // might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize); | }
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} |
17,189 | 9 | // Shouldn't happen. | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | NONSATD | true | for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx; | // block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
} | // TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} |
17,189 | 10 | // Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare. | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | NONSATD | true | }
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize); | // But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom()); | // we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} |
8,997 | 0 | // This is the NAME of the rule, not a reference to it!! | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} | NONSATD | true | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName, | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) { | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} |
8,997 | 1 | // This is, on other hand, is a reference to the parent rule (because it's used in inheritance) | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} | NONSATD | true | addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) { | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this.. | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} |
8,997 | 2 | // need compilation for this.. | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} | DOCUMENTATION | true | }
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO | // This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} |
8,997 | 3 | // TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE); | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} | NONSATD | true | visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr); | if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} | protected void visit(final RuleDescr descr) {
// This is the NAME of the rule, not a reference to it!!
String ruleName = getPackagePrefix() + descr.getName();
addResource(ruleName,
ResourceType.RULE);
// This is, on other hand, is a reference to the parent rule (because it's used in inheritance)
String parentRuleName = descr.getParentName();
if (parentRuleName != null) {
addResourceReference(parentRuleName,
ResourceType.RULE);
}
for (AttributeDescr d : descr.getAttributes().values()) {
visit(d);
}
visit(descr.getLhs());
visitConsequence(descr.getConsequence()); // need compilation for this..
for (String namedConsequence : descr.getNamedConsequences().keySet()) {
// TODO
// ? addResourceReference(namedConsequence, PartType.NAMED_CONSEQUENCE);
}
visitAnnos(descr);
} |
17,191 | 0 | // not allocated yet | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1; | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally { | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx); |
17,191 | 1 | // Try to allocate from target-sized free list, maybe we'll get lucky. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize); | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx]; |
17,191 | 2 | // Header for newly allocated used blocks. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting. | freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining); |
17,191 | 3 | // Number of headers (smallest blocks) per target block. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | }
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into | try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake; |
17,191 | 4 | // Next free list from which we will be splitting. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the | // Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx]; | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains. |
17,191 | 5 | // Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx); | ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData; |
17,191 | 6 | // How many ways each block splits into target size. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder. | }
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size. | int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts. |
17,191 | 7 | // How many target-sized blocks remain from last split. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx]; | byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining); | freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset); |
17,191 | 8 | // The header index for the beginning of the remainder. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock(); | int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake; | try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
} |
17,191 | 9 | // Index of the next free block to split. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset; | // blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData; | remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
} |
17,191 | 10 | // We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake; | assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts. | freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined |
17,191 | 11 | // Whatever remains. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) { | FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head. | int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx; |
17,191 | 12 | // Take toTake blocks by splitting the block at offset. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData; | splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally { | // Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) { |
17,191 | 13 | // TODO: this could be done out of the lock, we only need to take the blocks out. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | DESIGN | true | for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
} | while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) { | while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock(); |
17,191 | 14 | // If anything remains, this is where it starts. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | ((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
} | // which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined | int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader); |
17,191 | 15 | // In the end, update free list head. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock(); | lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx; | FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
} |
17,191 | 16 | // We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index. | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | NONSATD | true | }
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) { | ((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock(); | int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
} |
25,388 | 0 | // this method supports only guest network creation | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | DESIGN | true | final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method"); | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState()); |
25,388 | 1 | //check resource limits | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | }
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled); | final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
} | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true; |
25,388 | 2 | // Validate network offering | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO | // this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState()); | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true |
25,388 | 3 | // see NetworkOfferingVO | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | // Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId"); | s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex; | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); |
25,388 | 4 | // Validate physical network | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java | if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
} | final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic); |
25,388 | 5 | // see PhysicalNetworkVO.java | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | // Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId"); | }
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) { | final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed |
25,388 | 6 | // Validate zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true | if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
} | _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true; |
25,388 | 7 | // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | // Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); | final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { | // Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone"); |
25,388 | 8 | // Only one guest network is supported in Basic zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) { | boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) { | ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else { |
25,388 | 9 | // if zone is basic, only Shared network offerings w/o source nat service are allowed | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled " | if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) { | // see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) { |
25,388 | 10 | // Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone"); | } else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic); | if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) { |
25,388 | 11 | //don't allow eip/elb networks in Advance zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | }
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic); | }
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null; | vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks |
25,388 | 12 | //TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | IMPLEMENTATION | true | throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) { | }
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk); | if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone " |
25,388 | 13 | // Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation | final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName()); | //don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri)); |
25,388 | 14 | //don't allow to specify vlan tag used by physical network for dynamic vlan allocation | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | // Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " | if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){ | throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty |