index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/mqttproxy/Unsuback.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.mqttproxy;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
/**
* This class represents the MQTT UNSUBACK message.
*/
public class Unsuback {
private static final String TAG = "MqttUnsubscribe";
private static final String TYPE_KEY = "w";
private static final String MSGID_KEY = "i";
/**
* MQTT message type.
*/
public int type;
/**
* MQTT message ID.
*/
public int msgID;
public byte[] encode() {
byte[] unsubackBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, type)
.put(MSGID_KEY, msgID)
.end()
.build());
unsubackBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return unsubackBytes;
}
}
| 9,000 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/SaveNetworkReq.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.SAVE_NETWORK_REQ;
/**
* Save network request.
*/
public class SaveNetworkReq {
/**
* SSID of the network to be saved.
*/
public String ssid;
/**
* BSSID of the network to be saved.
*/
public byte[] bssid;
/**
* Password of the network to be saved.
*/
public String psk;
/**
* Network security type.
*/
public int security;
/**
* Current index of the network to be saved.
*/
public int index;
/**
* Connect immediately or just save for later.
*/
public boolean connect = true;
private static final String TAG = "SaveNetworkRequest";
private static final String INDEX_KEY = "g";
private static final String SSID_KEY = "r";
private static final String BSSID_KEY = "b";
private static final String PSK_KEY = "m";
private static final String SECURITY_KEY = "q";
private static final String TYPE_KEY = "w";
private static final String CONNECT_KEY = "y";
public byte[] encode() {
byte[] SaveNetworkRequestBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, SAVE_NETWORK_REQ)
.put(INDEX_KEY, index)
.put(SSID_KEY, ssid)
.put(BSSID_KEY, bssid)
.put(PSK_KEY, psk)
.put(SECURITY_KEY, security)
.put(CONNECT_KEY, connect)
.end()
.build());
SaveNetworkRequestBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return SaveNetworkRequestBytes;
}
}
| 9,001 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/DeleteNetworkResp.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.util.List;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
import lombok.Getter;
/**
* Delete network response
*/
@Getter
public class DeleteNetworkResp {
/**
* Status of the operation. 0 for success.
*/
int status;
public String toString() {
return String.format("DeleteNetworkResponse ->\n status: %d", status);
}
private static final String TAG = "DeleteNetworkResponse";
private static final String STATUS_KEY = "s";
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(STATUS_KEY));
status = ((UnsignedInteger) dataItem).getValue().intValue();
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 9,002 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/SaveNetworkResp.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.util.List;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
import lombok.Getter;
/**
* Save network response
*/
@Getter
public class SaveNetworkResp {
/**
* Status of the operation. 0 for success.
*/
int status;
public String toString() {
return String.format("SaveNetworkResponse ->\n status: %d", status);
}
private static final String TAG = "SaveNetworkResponse";
private static final String STATUS_KEY = "s";
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(STATUS_KEY));
status = ((UnsignedInteger) dataItem).getValue().intValue();
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 9,003 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/DeleteNetworkReq.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.DELETE_NETWORK_REQ;
/**
* Delete network request.
*/
public class DeleteNetworkReq {
/**
* The index of the saved network to be deleted.
*/
public int index;
private static final String TAG = "DeleteNetworkRequest";
private static final String INDEX_KEY = "g";
private static final String TYPE_KEY = "w";
public byte[] encode() {
byte[] DeleteNetworkRequestBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, DELETE_NETWORK_REQ)
.put(INDEX_KEY, index)
.end()
.build());
DeleteNetworkRequestBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return DeleteNetworkRequestBytes;
}
}
| 9,004 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/EditNetworkReq.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.EDIT_NETWORK_REQ;
/**
* Edit network request
*/
public class EditNetworkReq {
/**
* The index of the saved network to be edited.
*/
public int index;
/**
* The new index of the saved network. Must be one of the existing indices of saved networks.
*/
public int newIndex;
private static final String TAG = "EditNetworkRequest";
private static final String INDEX_KEY = "g";
private static final String NEWINDEX_KEY = "j";
private static final String TYPE_KEY = "w";
public byte[] encode() {
byte[] EditNetworkRequestBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, EDIT_NETWORK_REQ)
.put(INDEX_KEY, index)
.put(NEWINDEX_KEY, newIndex)
.end()
.build());
EditNetworkRequestBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return EditNetworkRequestBytes;
}
}
| 9,005 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/ListNetworkReq.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.LIST_NETWORK_REQ;
/**
* List network request
*/
public class ListNetworkReq {
/**
* Maximum total number of networks to return.
*/
public int maxNetworks;
/**
* Time in seconds for BLE device to scan available networks.
*/
public int timeout;
private static final String TAG = "ListNetworkRequest";
private static final String MAXNETWORKS_KEY = "h";
private static final String TIMEOUT_KEY = "t";
private static final String TYPE_KEY = "w";
public byte[] encode() {
byte[] ListNetworkRequestBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
.addMap()
.put(TYPE_KEY, LIST_NETWORK_REQ)
.put(MAXNETWORKS_KEY, maxNetworks)
.put(TIMEOUT_KEY, timeout)
.end()
.build());
ListNetworkRequestBytes = baos.toByteArray();
} catch (CborException e) {
Log.e(TAG, "Failed to encode.", e);
}
return ListNetworkRequestBytes;
}
}
| 9,006 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/ListNetworkResp.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.util.Formatter;
import java.util.List;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.ByteString;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.NegativeInteger;
import co.nstant.in.cbor.model.Number;
import co.nstant.in.cbor.model.SimpleValue;
import co.nstant.in.cbor.model.SimpleValueType;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
import lombok.Getter;
/**
* List network response
*/
@Getter
public class ListNetworkResp {
private static final String TAG = "ListNetworkResponse";
private static final String STATUS_KEY = "s";
private static final String SSID_KEY = "r";
private static final String BSSID_KEY = "b";
private static final String SECURITY_KEY = "q";
private static final String HIDDEN_KEY = "f";
private static final String RSSI_KEY = "p";
private static final String CONNECTED_KEY = "e";
private static final String INDEX_KEY = "g";
private static final String LAST_NETWORK_KEY = "l";
/**
* Status of the operation. 0 for success.
*/
private int status;
/**
* SSID of the scanned network.
*/
private String ssid;
/**
* BSSID of the scanned network.
*/
private byte[] bssid;
/**
* Network security type.
*/
private int security;
/**
* Whether the network is hidden.
*/
private Boolean hidden;
/**
* RSSI value of the scanned network.
*/
private int rssi;
/**
* Whether BLE device is connected to this network.
*/
private Boolean connected;
/**
* The index of this network. Index is used to indicate the connection preference of each saved
* network. For non-saved networks, the index is negative.
*/
private int index;
/**
* Whether this network is the last in the list.
*/
private Boolean last = false;
public String toString() {
return String.format("List network response -> Status: %d ssid: %s bssid: %s security: %d hidden: %s" +
" rssi: %d connected: %s index: %d, last :%s", status, ssid, bytesToHexString(bssid), security,
hidden ? "true":"false", rssi, connected ? "true":"false", index, last ? "true" : "false");
}
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(STATUS_KEY));
status = ((UnsignedInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(SSID_KEY));
ssid = ((UnicodeString) dataItem).getString();
dataItem = map.get(new UnicodeString(BSSID_KEY));
bssid = ((ByteString) dataItem).getBytes();
dataItem = map.get(new UnicodeString(SECURITY_KEY));
security = ((UnsignedInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(HIDDEN_KEY));
hidden = (((SimpleValue) dataItem).getSimpleValueType() == SimpleValueType.TRUE) ? true : false;
dataItem = map.get(new UnicodeString(RSSI_KEY));
rssi = ((NegativeInteger) dataItem).getValue().intValue();
dataItem = map.get(new UnicodeString(CONNECTED_KEY));
connected = (((SimpleValue) dataItem).getSimpleValueType() == SimpleValueType.TRUE) ? true : false;
dataItem = map.get(new UnicodeString(INDEX_KEY));
index = ((Number) dataItem).getValue().intValue();
final UnicodeString lastNetworkKey = new UnicodeString(LAST_NETWORK_KEY);
if(map.getKeys().contains(lastNetworkKey)) {
dataItem = map.get(lastNetworkKey);
last = (((SimpleValue) dataItem).getSimpleValueType() == SimpleValueType.TRUE);
}
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
Formatter formatter = new Formatter(sb);
for (int i =0; i< bytes.length; i++) {
formatter.format("%02x", bytes[i]);
if(i < bytes.length -1)
formatter.format(":");
}
return sb.toString();
}
}
| 9,007 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/networkconfig/EditNetworkResp.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.networkconfig;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.util.List;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
import lombok.Getter;
/**
* Edit network response
*/
@Getter
public class EditNetworkResp {
/**
* Status of the operation. 0 for success.
*/
int status;
public String toString() {
return String.format("EditNetworkResponse ->\n status: %d", status);
}
private static final String TAG = "EditNetworkResponse";
private static final String STATUS_KEY = "s";
public boolean decode(byte[] cborEncodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(cborEncodedBytes);
try {
List<DataItem> dataItems = new CborDecoder(bais).decode();
// process data item
Map map = (Map) dataItems.get(0);
DataItem dataItem = map.get(new UnicodeString(STATUS_KEY));
status = ((UnsignedInteger) dataItem).getValue().intValue();
return true;
} catch (CborException e) {
Log.e(TAG,"Failed to decode.", e);
return false;
} catch (IndexOutOfBoundsException e) {
return false;
}
}
}
| 9,008 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/deviceinfo/Mtu.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.deviceinfo;
/**
* This class represents the mtu object transferred between ble device and the SDK.
* When SDK sends a read characteristic command to device to get the current mtu size, this object
* is returned in the response.
*/
public class Mtu {
public String mtu;
}
| 9,009 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/deviceinfo/BrokerEndpoint.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.deviceinfo;
/**
* This class represents the broker endpoint object that is transferred between ble device and SDK.
* When SDK sends a read characteristic command to the ble device, this class object is returned in
* the response back to SDK.
* The broker endpoint is the AWS IoT endpoint from AWS IOT Console.
*/
public class BrokerEndpoint {
public String brokerEndpoint;
}
| 9,010 |
0 | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk | Create_ds/amazon-freertos-ble-android-sdk/amazonfreertossdk/src/main/java/software/amazon/freertos/amazonfreertossdk/deviceinfo/Version.java | /*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk.deviceinfo;
/**
* This class represents the AmazonFreeRTOS BLE library version running on the device. When SDK
* sends a read characteristic command to get the BLE library version on the device, this object
* is returned in the response.
*/
public class Version {
public String version;
}
| 9,011 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/WifiProvisionFragment.java | package software.amazon.freertos.demo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSDevice;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSManager;
import software.amazon.freertos.amazonfreertossdk.NetworkConfigCallback;
import software.amazon.freertos.amazonfreertossdk.networkconfig.*;
import static android.support.v7.widget.helper.ItemTouchHelper.ACTION_STATE_SWIPE;
import static android.support.v7.widget.helper.ItemTouchHelper.DOWN;
import static android.support.v7.widget.helper.ItemTouchHelper.LEFT;
import static android.support.v7.widget.helper.ItemTouchHelper.UP;
public class WifiProvisionFragment extends Fragment {
private static final String TAG = "WifiFragment";
private static final String DIALOG_TAG = "WiFiCredentialDialogTag";
private static final int SAVED_NETWORK_RSSI = -100;
private static final int REQUEST_CODE = 0;
private String mDeviceMacAddr;
private AmazonFreeRTOSDevice mDevice;
private RecyclerView mWifiInfoRecyclerView;
private WifiInfoAdapter mWifiInfoAdapter;
private List<WifiInfo> mWifiInfoList = new ArrayList<>();
private HashMap<String, WifiInfo> mBssid2WifiInfoMap = new HashMap<>();
private Handler mHandler = new Handler(Looper.getMainLooper());
private AmazonFreeRTOSManager mAmazonFreeRTOSManager;
private class WifiInfoHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mSsidTextView;
private TextView mRssiTextView;
private TextView mBssidTextView;
private TextView mNetworkTypeTextView;
private WifiInfo mWifiInfo;
private Fragment mHostingFragment;
public WifiInfoHolder(LayoutInflater inflater, ViewGroup parent, Fragment fragment) {
super(inflater.inflate(R.layout.list_wifi_info, parent, false));
mHostingFragment = fragment;
mSsidTextView = (TextView) itemView.findViewById(R.id.ssid_name);
mRssiTextView = (TextView) itemView.findViewById(R.id.rssi_value);
mBssidTextView = (TextView) itemView.findViewById(R.id.bssid_name);
mNetworkTypeTextView = (TextView) itemView.findViewById(R.id.network_type);
itemView.setOnClickListener(this);
}
public void bind(WifiInfo wifiInfo) {
mWifiInfo = wifiInfo;
mSsidTextView.setText(mWifiInfo.getSsid());
mRssiTextView.setText(getResources().getString(R.string.rssi_value, mWifiInfo.getRssi()));
mBssidTextView.setText(bssidToString(mWifiInfo.getBssid()));
mNetworkTypeTextView.setText(mWifiInfo.getNetworkTypeName());
if (SAVED_NETWORK_RSSI == mWifiInfo.getRssi()) {
int colorAccent = getResources().getColor(R.color.colorAccent, null);
mSsidTextView.setTextColor(colorAccent);
mBssidTextView.setTextColor(colorAccent);
mRssiTextView.setTextColor(colorAccent);
mNetworkTypeTextView.setTextColor(colorAccent);
}
if (mWifiInfo.isConnected()) {
int colorPrimary = getResources().getColor(R.color.colorPrimary, null);
mSsidTextView.setTextColor(colorPrimary);
mBssidTextView.setTextColor(colorPrimary);
mRssiTextView.setTextColor(colorPrimary);
mNetworkTypeTextView.setTextColor(colorPrimary);
}
}
@Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
WifiCredentialFragment dialog = WifiCredentialFragment.newInstance(
mWifiInfo.getSsid(), bssidToString(mWifiInfo.getBssid()));
dialog.setTargetFragment(mHostingFragment, REQUEST_CODE);
dialog.show(manager, DIALOG_TAG);
}
}
private class WifiInfoAdapter extends RecyclerView.Adapter<WifiInfoHolder> {
private List<WifiInfo> mWifiInfoList;
private Fragment mHostingFragment;
public WifiInfoAdapter(List<WifiInfo> wifiInfos, Fragment fragment) {
mWifiInfoList = wifiInfos;
mHostingFragment = fragment;
}
@Override
public WifiInfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new WifiInfoHolder(layoutInflater, parent, mHostingFragment);
}
@Override
public void onBindViewHolder(WifiInfoHolder holder, int position) {
WifiInfo wifiInfo = mWifiInfoList.get(position);
holder.bind(wifiInfo);
}
@Override
public int getItemCount() {
return mWifiInfoList.size();
}
public void deleteItem(int position) {
WifiInfo wifiInfo = mWifiInfoList.get(position);
deleteNetwork(wifiInfo.getIndex());
mWifiInfoList.remove(position);
notifyItemRemoved(position);
}
public WifiInfo getItem(int position) {
return mWifiInfoList.get(position);
}
public void moveItem(int oldPosition, int newPosition) {
WifiInfo oldWifiInfo = mWifiInfoList.get(oldPosition);
mWifiInfoList.remove(oldPosition);
mWifiInfoList.add(newPosition, oldWifiInfo);
notifyItemMoved(oldPosition, newPosition);
}
public void reorderItem(int fromIndex, int toIndex) {
if (fromIndex != toIndex) {
Log.d(TAG, "Reordering item: [" + fromIndex + "] -> [" + toIndex + "]");
editNetwork(fromIndex, toIndex);
}
}
}
private class DragSwipeController extends ItemTouchHelper.SimpleCallback {
private WifiInfoAdapter mAdapter;
private Drawable mDeleteIcon;
private final ColorDrawable mDeleteBackground;
private boolean mMoving;
private int mFromIndex, mToIndex;
public DragSwipeController(WifiInfoAdapter adapter) {
super(UP|DOWN, LEFT);
mAdapter = adapter;
mDeleteIcon = ContextCompat.getDrawable(getContext(), R.drawable.ic_delete);
mDeleteBackground = new ColorDrawable(Color.RED);
mMoving = false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mAdapter.deleteItem(position);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
if (!mMoving) {
mFromIndex = viewHolder.getAdapterPosition();
mMoving = true;
}
mAdapter.moveItem(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
if (mMoving) {
mToIndex = viewHolder.getAdapterPosition();
mMoving = false;
mAdapter.reorderItem(mFromIndex, mToIndex);
}
}
@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int position = viewHolder.getAdapterPosition();
WifiInfo wifiInfo = mAdapter.getItem(position);
if (SAVED_NETWORK_RSSI != wifiInfo.getRssi()) {
return 0;
}
return super.getSwipeDirs(recyclerView, viewHolder);
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
float dX, float dY, int actionState, boolean isCurrentlyActive) {
View itemView = viewHolder.itemView;
if (actionState == ACTION_STATE_SWIPE) {
float alpha = 1 - (Math.abs(dX) / recyclerView.getWidth());
itemView.setAlpha(alpha);
}
int iconMargin = (itemView.getHeight() - mDeleteIcon.getIntrinsicHeight()) / 2;
int iconTop = itemView.getTop() + (itemView.getHeight() - mDeleteIcon.getIntrinsicHeight()) / 2;
int iconBottom = iconTop + mDeleteIcon.getIntrinsicHeight();
int iconLeft = itemView.getRight() - iconMargin - mDeleteIcon.getIntrinsicWidth();
int iconRight = itemView.getRight() - iconMargin;
mDeleteIcon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
mDeleteBackground.setBounds(itemView.getRight() + ((int) dX) ,
itemView.getTop(), itemView.getRight(), itemView.getBottom());
mDeleteBackground.draw(c);
mDeleteIcon.draw(c);
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDeviceMacAddr = getActivity().getIntent().getStringExtra(WifiProvisionActivity.EXTRA_DEVICE_MAC);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_wifi_provision, container, false);
mWifiInfoRecyclerView = (RecyclerView) view.findViewById(R.id.wifi_recycler_view);
mWifiInfoRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mWifiInfoAdapter = new WifiInfoAdapter(mWifiInfoList, this);
mWifiInfoRecyclerView.setAdapter(mWifiInfoAdapter);
DragSwipeController dragSwipeController = new DragSwipeController(mWifiInfoAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(dragSwipeController);
itemTouchHelper.attachToRecyclerView(mWifiInfoRecyclerView);
mAmazonFreeRTOSManager = AmazonFreeRTOSAgent.getAmazonFreeRTOSManager(getActivity());
mDevice = mAmazonFreeRTOSManager.getConnectedDevice(mDeviceMacAddr);
listNetworks();
return view;
}
private NetworkConfigCallback mNetworkConfigCallback = new NetworkConfigCallback() {
@Override
public void onListNetworkResponse(final ListNetworkResp response) {
mHandler.post(new Runnable() {
@Override
public void run() {
WifiInfo wifiInfo = new WifiInfo(response.getSsid(), response.getBssid(),
response.getRssi(), response.getSecurity(), response.getIndex(),
response.getConnected());
if (!mWifiInfoList.contains(wifiInfo)) {
mWifiInfoList.add(wifiInfo);
mBssid2WifiInfoMap.put(bssidToString(wifiInfo.getBssid()), wifiInfo);
mWifiInfoAdapter.notifyDataSetChanged();
}
}
});
}
@Override
public void onSaveNetworkResponse(final SaveNetworkResp response) {
refreshUI();
}
@Override
public void onDeleteNetworkResponse(final DeleteNetworkResp response) {
refreshUI();
}
@Override
public void onEditNetworkResponse(EditNetworkResp response) {
refreshUI();
}
private void refreshUI() {
mHandler.post(new Runnable() {
@Override
public void run() {
listNetworks();
}
});
}
};
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE) {
String pw = data.getStringExtra(WifiCredentialFragment.EXTRA_WIFI_PW);
String bssid = data.getStringExtra(WifiCredentialFragment.EXTRA_WIFI_BSSID);
saveNetwork(bssid, pw);
}
}
private void saveNetwork(String bssid, String pw) {
SaveNetworkReq saveNetworkReq = new SaveNetworkReq();
WifiInfo wifiInfo = mBssid2WifiInfoMap.get(bssid);
saveNetworkReq.ssid = wifiInfo.getSsid();
saveNetworkReq.bssid = wifiInfo.getBssid();
saveNetworkReq.psk = pw;
saveNetworkReq.security = wifiInfo.getNetworkType();
saveNetworkReq.index = wifiInfo.getIndex();
if (mDevice != null) {
mDevice.saveNetwork(saveNetworkReq, mNetworkConfigCallback);
} else {
Log.e(TAG, "Device is not found. " + mDeviceMacAddr);
}
}
private void listNetworks() {
mWifiInfoList.clear();
ListNetworkReq listNetworkReq = new ListNetworkReq();
listNetworkReq.maxNetworks = 20;
listNetworkReq.timeout = 5;
if (mDevice != null) {
mDevice.listNetworks(listNetworkReq, mNetworkConfigCallback);
} else {
Log.e(TAG, "Device is not found. " + mDeviceMacAddr);
}
}
private void deleteNetwork(int index) {
DeleteNetworkReq deleteNetworkReq = new DeleteNetworkReq();
deleteNetworkReq.index = index;
if (mDevice != null) {
mDevice.deleteNetwork(deleteNetworkReq, mNetworkConfigCallback);
} else {
Log.e(TAG, "Device is not found. " + mDeviceMacAddr);
}
}
private void editNetwork(int oldIndex, int newIndex) {
EditNetworkReq editNetworkReq = new EditNetworkReq();
editNetworkReq.index = oldIndex;
editNetworkReq.newIndex = newIndex;
if (mDevice != null) {
mDevice.editNetwork(editNetworkReq, mNetworkConfigCallback);
} else {
Log.e(TAG, "Device is not found. " + mDeviceMacAddr);
}
}
private String bssidToString(byte[] bssid) {
StringBuilder sb = new StringBuilder(18);
for (byte b : bssid) {
if (sb.length() > 0)
sb.append(':');
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
| 9,012 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/DeviceScanFragment.java | package software.amazon.freertos.demo;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.PopupMenu;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.mobile.client.AWSMobileClient;
import java.util.ArrayList;
import java.util.List;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSDevice;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSManager;
import software.amazon.freertos.amazonfreertossdk.BleConnectionStatusCallback;
import software.amazon.freertos.amazonfreertossdk.BleScanResultCallback;
public class DeviceScanFragment extends Fragment {
private static final String TAG = "DeviceScanFragment";
private boolean mqttOn = true;
private RecyclerView mBleDeviceRecyclerView;
private BleDeviceAdapter mBleDeviceAdapter;
List<BleDevice> mBleDevices = new ArrayList<>();
private static final int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_FINE_LOCATION = 1;
private Button scanButton;
private AmazonFreeRTOSManager mAmazonFreeRTOSManager;
private class BleDeviceHolder extends RecyclerView.ViewHolder {
private TextView mBleDeviceNameTextView;
private TextView mBleDeviceMacTextView;
private Switch mBleDeviceSwitch;
private TextView mMenuTextView;
private BleDevice mBleDevice;
private AmazonFreeRTOSDevice aDevice = null;
private boolean autoReconnect = true;
public BleDeviceHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_device, parent, false));
mBleDeviceNameTextView = (TextView) itemView.findViewById(R.id.device_name);
mBleDeviceMacTextView = (TextView) itemView.findViewById(R.id.device_mac);
mBleDeviceSwitch = (Switch) itemView.findViewById(R.id.connect_switch);
mMenuTextView = (TextView) itemView.findViewById(R.id.menu_option);
}
private final CompoundButton.OnCheckedChangeListener deviceConnectListener =
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton v, boolean isChecked) {
Log.i(TAG, "Connect switch isChecked: " + (isChecked ? "ON" : "OFF"));
if (isChecked) {
connectDevice();
} else {
disconnectDevice();
resetUI();
}
}
};
private void connectDevice() {
if (aDevice == null) {
AWSCredentialsProvider credentialsProvider = AWSMobileClient.getInstance();
aDevice = mAmazonFreeRTOSManager.connectToDevice(mBleDevice.getBluetoothDevice(),
connectionStatusCallback, credentialsProvider, autoReconnect);
}
}
private void disconnectDevice() {
if (aDevice != null) {
/* Save to a temporary variable so that callback triggered will not disconnect twice. */
final AmazonFreeRTOSDevice deviceToDisconnect = aDevice;
aDevice = null;
mAmazonFreeRTOSManager.disconnectFromDevice(deviceToDisconnect);
}
}
private final View.OnClickListener deviceMenuListener = new View.OnClickListener(){
@Override
public void onClick(View view) {
Log.i(TAG, "Click menu.");
PopupMenu popup = new PopupMenu(getContext(), mMenuTextView);
popup.inflate(R.menu.options_menu);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.wifi_provisioning_menu_id:
Intent intentToStartWifiProvision
= WifiProvisionActivity.newIntent(getActivity(), mBleDevice.getMacAddr());
startActivity(intentToStartWifiProvision);
return true;
case R.id.mqtt_proxy_menu_id:
Toast.makeText(getContext(),"Already signed in",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
popup.show();
}
};
public void bind(BleDevice bleDevice) {
mBleDevice = bleDevice;
mBleDeviceNameTextView.setText(mBleDevice.getName());
mBleDeviceMacTextView.setText(mBleDevice.getMacAddr());
resetUI();
}
final BleConnectionStatusCallback connectionStatusCallback = new BleConnectionStatusCallback() {
@Override
public void onBleConnectionStatusChanged(AmazonFreeRTOSConstants.BleConnectionState connectionStatus) {
Log.i(TAG, "BLE connection status changed to: " + connectionStatus);
if (connectionStatus == AmazonFreeRTOSConstants.BleConnectionState.BLE_INITIALIZED) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mMenuTextView.setEnabled(true);
mMenuTextView.setTextColor(getResources().getColor(R.color.colorAccent, null));
mBleDeviceSwitch.setChecked(true);
}
});
} else if (connectionStatus == AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED) {
if(!autoReconnect) {
disconnectDevice();
}
resetUI();
}
}
};
private void resetUI() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
/* Reset the UI without invoking the listeners */
mBleDeviceSwitch.setOnCheckedChangeListener(null);
mMenuTextView.setOnClickListener(null);
mMenuTextView.setEnabled(false);
mMenuTextView.setTextColor(Color.GRAY);
mBleDeviceSwitch.setChecked(false);
mBleDeviceSwitch.setOnCheckedChangeListener(deviceConnectListener);
mMenuTextView.setOnClickListener(deviceMenuListener);
}
});
}
}
private class BleDeviceAdapter extends RecyclerView.Adapter<BleDeviceHolder> {
private List<BleDevice> mDeviceList;
public BleDeviceAdapter(List<BleDevice> devices) {
mDeviceList = devices;
}
@Override
public BleDeviceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new BleDeviceHolder(layoutInflater, parent);
}
@Override
public void onBindViewHolder(BleDeviceHolder holder, int position) {
BleDevice device = mDeviceList.get(position);
holder.bind(device);
}
@Override
public int getItemCount() {
return mDeviceList.size();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_device_scan, container, false);
//Enabling Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// requesting user to grant permission.
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_FINE_LOCATION);
//Getting AmazonFreeRTOSManager
mAmazonFreeRTOSManager = AmazonFreeRTOSAgent.getAmazonFreeRTOSManager(getActivity());
scanButton = (Button)view.findViewById(R.id.scanbutton);
scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "Scan button clicked.");
mAmazonFreeRTOSManager.startScanDevices(new BleScanResultCallback() {
@Override
public void onBleScanResult(ScanResult result) {
BleDevice thisDevice = new BleDevice(result.getDevice().getName(),
result.getDevice().getAddress(), result.getDevice());
if (!mBleDevices.contains(thisDevice)) {
Log.d(TAG, "new ble device found. Mac: " + thisDevice.getMacAddr());
mBleDevices.add(thisDevice);
mBleDeviceAdapter.notifyDataSetChanged();
}
}
}, 10000);
}
});
//RecyclerView for displaying list of BLE devices.
mBleDeviceRecyclerView = (RecyclerView) view.findViewById(R.id.device_recycler_view);
mBleDeviceRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mBleDeviceAdapter = new BleDeviceAdapter(mBleDevices);
mBleDeviceRecyclerView.setAdapter(mBleDeviceAdapter);
if (mqttOn) {
Intent intentToStartAuthenticator
= AuthenticatorActivity.newIntent(getActivity());
startActivity(intentToStartAuthenticator);
}
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_device_scan, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
AWSMobileClient.getInstance().signOut();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == getActivity().RESULT_OK) {
Log.i(TAG, "Successfully enabled bluetooth");
} else {
Log.w(TAG, "Failed to enable bluetooth");
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_FINE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "ACCESS_FINE_LOCATION granted.");
} else {
Log.w(TAG, "ACCESS_FINE_LOCATION denied");
scanButton.setEnabled(false);
}
}
}
}
}
| 9,013 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/AuthenticatorActivity.java | package software.amazon.freertos.demo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.mobile.client.Callback;
import com.amazonaws.mobile.client.SignInUIOptions;
import com.amazonaws.mobile.client.UserStateDetails;
import com.amazonaws.regions.Region;
import com.amazonaws.services.iot.AWSIotClient;
import com.amazonaws.services.iot.model.AttachPolicyRequest;
import java.util.concurrent.CountDownLatch;
public class AuthenticatorActivity extends AppCompatActivity {
private final static String TAG = "AuthActivity";
private HandlerThread handlerThread;
private Handler handler;
public static Intent newIntent(Context packageContext) {
Intent intent = new Intent(packageContext, AuthenticatorActivity.class);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
if ( handlerThread == null ) {
handlerThread = new HandlerThread("SignInThread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
final CountDownLatch latch = new CountDownLatch(1);
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails userStateDetails) {
Log.i(TAG, "AWSMobileClient initialization onResult: " + userStateDetails.getUserState());
latch.countDown();
}
@Override
public void onError(Exception e) {
Log.e(TAG, "Initialization error.", e);
}
}
);
Log.d(TAG, "waiting for AWSMobileClient Initialization");
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
if (AWSMobileClient.getInstance().isSignedIn()) {
signinsuccessful();
finish();
} else {
AWSMobileClient.getInstance().showSignIn(
AuthenticatorActivity.this,
SignInUIOptions.builder()
.nextActivity(null)
.build(),
new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails result) {
Log.d(TAG, "onResult: " + result.getUserState());
switch (result.getUserState()) {
case SIGNED_IN:
Log.i(TAG, "logged in!");
signinsuccessful();
finish();
break;
case SIGNED_OUT:
Log.i(TAG, "onResult: User did not choose to sign-in");
break;
default:
AWSMobileClient.getInstance().signOut();
break;
}
}
@Override
public void onError(Exception e) {
Log.e(TAG, "onError: ", e);
}
}
);
}
}
});
}
private void signinsuccessful() {
try {
AWSCredentialsProvider credentialsProvider = AWSMobileClient.getInstance();
AWSIotClient awsIotClient = new AWSIotClient(credentialsProvider);
awsIotClient.setRegion(Region.getRegion(DemoConstants.AWS_IOT_REGION));
AttachPolicyRequest attachPolicyRequest = new AttachPolicyRequest()
.withPolicyName(DemoConstants.AWS_IOT_POLICY_NAME)
.withTarget(AWSMobileClient.getInstance().getIdentityId());
awsIotClient.attachPolicy(attachPolicyRequest);
Log.i(TAG, "Iot policy attached successfully.");
} catch (Exception e) {
Log.e(TAG, "Exception caught: ", e);
}
}
}
| 9,014 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/DeviceScanActivity.java | package software.amazon.freertos.demo;
import android.support.v4.app.Fragment;
public class DeviceScanActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return new DeviceScanFragment();
}
}
| 9,015 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/WifiProvisionActivity.java | package software.amazon.freertos.demo;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
public class WifiProvisionActivity extends SingleFragmentActivity {
public static final String EXTRA_DEVICE_MAC = "com.amazonaws.freertosandroid.device_mac";
@Override
protected Fragment createFragment() {
return new WifiProvisionFragment();
}
public static Intent newIntent(Context packageContext, String macAddr) {
Intent intent = new Intent(packageContext, WifiProvisionActivity.class);
intent.putExtra(EXTRA_DEVICE_MAC, macAddr);
return intent;
}
}
| 9,016 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/DemoConstants.java | package software.amazon.freertos.demo;
public class DemoConstants {
/*
* Replace with your AWS IoT policy name.
*/
final static String AWS_IOT_POLICY_NAME = "Your AWS IoT policy name";
/*
* Replace with your AWS IoT region, eg: us-west-2.
*/
final static String AWS_IOT_REGION = "us-west-2";
}
| 9,017 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/AmazonFreeRTOSAgent.java | package software.amazon.freertos.demo;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSManager;
/**
* A wrapper class to get the instance of AmazonFreeRTOSManager.
*/
public class AmazonFreeRTOSAgent {
private static AmazonFreeRTOSManager sAmazonFreeRTOSManager;
private static BluetoothAdapter sBluetoothAdapter;
private static final String TAG = "AmazonFreeRTOSAgent";
/**
* Return the instance of AmazonFreeRTOSManager. Initialize AmazonFreeRTOSManager if this is
* called for the first time.
* Bluetooth must be enabled before calling this method to get AmazonFreeRTOSManager.
* @param context
* @return The instance of AmazonFreeRTOSManager.
*/
public static AmazonFreeRTOSManager getAmazonFreeRTOSManager(Context context) {
if (sAmazonFreeRTOSManager == null) {
BluetoothManager bluetoothManager
= (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
sBluetoothAdapter = bluetoothManager.getAdapter();
sAmazonFreeRTOSManager = new AmazonFreeRTOSManager(context, sBluetoothAdapter);
}
return sAmazonFreeRTOSManager;
}
}
| 9,018 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/WifiCredentialFragment.java | package software.amazon.freertos.demo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class WifiCredentialFragment extends DialogFragment {
public static final String EXTRA_WIFI_PW = "com.amazon.freertos.wifipassword";
public static final String EXTRA_WIFI_BSSID = "com.amazon.freertos.wifibssid";
private static final String SSID = "ssid";
private static final String BSSID = "bssid";
private String mBssid;
public static WifiCredentialFragment newInstance(String ssid, String bssid) {
Bundle args = new Bundle();
args.putString(SSID, ssid);
args.putString(BSSID, bssid);
WifiCredentialFragment fragment = new WifiCredentialFragment();
fragment.setArguments(args);
return fragment;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String ssid = getArguments().getString(SSID);
mBssid = getArguments().getString(BSSID);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.wifi_credential_dialog, null);
TextView ssidTextView = (TextView) view.findViewById(R.id.ssid_name);
final EditText pwEditText = (EditText) view.findViewById(R.id.wifi_pw);
ssidTextView.setText(ssid);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(R.string.wifi_credential_dialog_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendResult(Activity.RESULT_OK, pwEditText.getText().toString());
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
private void sendResult(int resultCode, String result) {
if (getTargetFragment() == null) {
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_WIFI_PW, result);
intent.putExtra(EXTRA_WIFI_BSSID, mBssid);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
}
| 9,019 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/BleDevice.java | package software.amazon.freertos.demo;
import android.bluetooth.BluetoothDevice;
import java.util.Objects;
public class BleDevice {
private String name;
private String macAddr;
private BluetoothDevice mBluetoothDevice;
public BleDevice(String name, String macAddr, BluetoothDevice bluetoothDevice) {
this.name = name;
this.macAddr = macAddr;
mBluetoothDevice = bluetoothDevice;
}
public BluetoothDevice getBluetoothDevice() {
return mBluetoothDevice;
}
public void setBluetoothDevice(BluetoothDevice bluetoothDevice) {
mBluetoothDevice = bluetoothDevice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMacAddr() {
return macAddr;
}
public void setMacAddr(String macAddr) {
this.macAddr = macAddr;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BleDevice bleDevice = (BleDevice) o;
return Objects.equals(getMacAddr(), bleDevice.getMacAddr());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getMacAddr(), getBluetoothDevice());
}
}
| 9,020 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/SingleFragmentActivity.java | package software.amazon.freertos.demo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstract Fragment createFragment();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
}
| 9,021 |
0 | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos | Create_ds/amazon-freertos-ble-android-sdk/app/src/main/java/software/amazon/freertos/demo/WifiInfo.java | package software.amazon.freertos.demo;
import java.util.Objects;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class WifiInfo {
private static String[] NETWORK_TYPES = {"Open", "WEP", "WPA", "WPA2", "WPA2-Enterprise", "WPA3", "Other"};
private String ssid;
private byte[] bssid;
private int rssi;
private int networkType;
private int index;
private boolean connected;
public String getNetworkTypeName() {
return NETWORK_TYPES[networkType];
}
public WifiInfo(String ssid, byte[] bssid, int rssi, int networkType, int index, boolean connected) {
this.ssid = ssid;
this.bssid = bssid;
this.rssi = rssi;
this.networkType = networkType;
this.index = index;
this.connected = connected;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
WifiInfo wifiInfo = (WifiInfo) obj;
return Objects.equals(wifiInfo.getSsid(), ssid);
}
}
| 9,022 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/HeaderTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.amazonaws.proprot.Header.SslFlags;
import com.amazonaws.proprot.ProxyProtocolSpec.AddressFamily;
import com.amazonaws.proprot.ProxyProtocolSpec.TransportProtocol;
public class HeaderTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testValidate_defaultValid() {
new Header().validate();
}
@Test
public void testVerifyAddressFamilyTransportProtocolCombination_happyPath() {
AddressFamily addressFamily = AddressFamily.AF_INET;
TransportProtocol transportProtocol = TransportProtocol.UNSPEC;
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage(addressFamily.toString());
thrown.expectMessage(transportProtocol.toString());
thrown.expectMessage(Util.toHex(ProxyProtocolSpec.pack(addressFamily, transportProtocol)));
Header header = new Header();
header.setAddressFamily(addressFamily);
header.setTransportProtocol(transportProtocol);
header.validate();
}
@Test
public void testVerifyAddressSize() {
verifyAddressSize(AddressFamily.AF_INET, TransportProtocol.STREAM);
verifyAddressSize(AddressFamily.AF_INET6, TransportProtocol.STREAM);
verifyAddressSize(AddressFamily.AF_UNIX, TransportProtocol.STREAM);
verifyAddressSize(AddressFamily.AF_UNSPEC, TransportProtocol.UNSPEC);
}
private void verifyAddressSize(AddressFamily addressFamily, TransportProtocol transportProtocol) {
Header header = new Header();
header.setAddressFamily(addressFamily);
header.setTransportProtocol(transportProtocol);
// right size
{
setAddresses(header, addressFamily.getAddressSize());
header.validate();
}
// larger
{
setAddresses(header, addressFamily.getAddressSize() + 1);
try {
header.validate();
fail();
} catch (InvalidHeaderException expected) {}
}
// empty
if (addressFamily.getAddressSize() > 0) {
setAddresses(header, 0);
try {
header.validate();
fail();
} catch (InvalidHeaderException expected) {}
}
}
private void setAddresses(Header header, int addressSize) {
byte[] address = new byte[addressSize];
Arrays.fill(address, (byte) 0xF1);
header.setSrcAddress(address);
header.setDstAddress(address);
}
@Test
public void testSslContainerContains() {
Header header = new Header();
header.setSslFlags(SslFlags.getOptional(true, false, true, false));
header.setSslVersion(Optional.of("version 1"));
new Header().validate();
}
@Test
public void testSslContainerDoesNotContain() {
thrown.expect(InvalidHeaderException.class);
Header header = new Header();
header.setSslVersion(Optional.of("version 1"));
header.validate();
}
@Test
public void testEqualsHashCode() {
SslFlags flags1 = SslFlags.getOptional(true, true, true, true).get();
assertEquals(flags1, flags1);
assertFalse(flags1.equals(null));
assertFalse(flags1.equals(new Object()));
{
SslFlags flags2 = SslFlags.getOptional(true, true, true, true).get();
assertEquals(flags1, flags2);
assertEquals(flags1.hashCode(), flags2.hashCode());
assertEquals(flags1.getClient(), flags2.getClient());
}
{
SslFlags flags2 = SslFlags.getOptional(false, false, false, false).get();
assertFalse(flags1.equals(flags2));
assertFalse(flags1.hashCode() == flags2.hashCode());
}
}
@Test
public void testAddTlv_happyPath() {
Header header = new Header();
{
TlvRaw tlv = new TlvRaw();
tlv.setType(0xF3);
header.addTlv(tlv);
}
{
TlvRaw tlv = new TlvRaw();
tlv.setType(0xF4);
header.addTlv(tlv);
}
{
TlvSubTypeRaw tlv = new TlvSubTypeRaw();
tlv.setType(0xF4);
tlv.setSubType(0x14);
header.addTlv(tlv);
}
}
@Test
public void testAddTlv_immutable() {
thrown.expect(UnsupportedOperationException.class);
new Header().getTlvs().add(null);
}
@Test
public void testAddTlv_knownType() {
thrown.expect(InvalidHeaderException.class);
TlvRaw tlv = new TlvRaw();
tlv.setType(ProxyProtocolSpec.PP2_TYPE_ALPN);
new Header().addTlv(tlv);
}
@Test
public void testSslFlags() {
{
SslFlags flags = SslFlags.getOptional(0, false).get();
assertSame(flags, SslFlags.getOptional(false, false, false, false).get());
assertFalse(flags.isClientConnectedWithSsl());
assertFalse(flags.isClientProvidedCertDuringConnection());
assertFalse(flags.isClientProvidedCertDuringSession());
assertFalse(flags.isClientVerifiedCert());
}
{
SslFlags flags = SslFlags.getOptional(0xFF, true).get();
assertSame(flags, SslFlags.getOptional(true, true, true, true).get());
assertTrue(flags.isClientConnectedWithSsl());
assertTrue(flags.isClientProvidedCertDuringConnection());
assertTrue(flags.isClientProvidedCertDuringSession());
assertTrue(flags.isClientVerifiedCert());
}
}
}
| 9,023 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/ProxyProtocolTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.amazonaws.proprot.Header.SslFlags;
import com.amazonaws.proprot.ProxyProtocolSpec.AddressFamily;
import com.amazonaws.proprot.ProxyProtocolSpec.Command;
import com.amazonaws.proprot.ProxyProtocolSpec.TransportProtocol;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
public class ProxyProtocolTest {
private static final int TLV_TYPE = 0xF0;
private static final int TLV_SUB_TYPE = 0xEC;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testRoundtrip_ipv6() throws IOException {
final Header header = createBaseHeader();
header.setAlpn(Optional.of(new byte[] {3, 4, 5}));
header.setAuthority(Optional.of("authority 1"));
header.setSslFlags(SslFlags.getOptional(true, true, true, true));
header.setSslVersion(Optional.of("ssl version 1"));
header.setSslCommonName(Optional.of("ssl common name 1"));
header.setSslCipher(Optional.of("ssl cipher 1"));
header.setSslSigAlg(Optional.of("sig algorithm 1"));
header.setSslKeyAlg(Optional.of("key algorithm 1"));
header.setNetNS(Optional.of("Net namespace 1"));
TlvRaw tlv = new TlvRaw();
tlv.setType(TLV_TYPE);
tlv.setValue(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
header.addTlv(tlv);
ProxyProtocol protocol = new ProxyProtocol();
// write
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
// validate
assertEquals(header.getCommand(), header2.getCommand());
assertEquals(header.getAddressFamily(), header2.getAddressFamily());
assertEquals(header.getTransportProtocol(), header2.getTransportProtocol());
assertArrayEquals(header.getSrcAddress(), header2.getSrcAddress());
assertArrayEquals(header.getDstAddress(), header2.getDstAddress());
assertEquals(header.getSrcPort(), header2.getSrcPort());
assertEquals(header.getDstPort(), header2.getDstPort());
assertArrayEquals(header.getAlpn().get(), header2.getAlpn().get());
assertEquals(header.getAuthority(), header2.getAuthority());
assertEquals(header.getSslFlags(), header2.getSslFlags());
assertEquals(header.getSslVersion(), header2.getSslVersion());
assertEquals(header.getSslCommonName(), header2.getSslCommonName());
assertEquals(header.getSslCipher(), header2.getSslCipher());
assertEquals(header.getSslSigAlg(), header2.getSslSigAlg());
assertEquals(header.getSslKeyAlg(), header2.getSslKeyAlg());
assertEquals(header.getNetNS(), header2.getNetNS());
TlvRaw tlv2 = (TlvRaw) Iterables.getOnlyElement(header2.getTlvs());
assertEquals(tlv.getType(), tlv2.getType());
assertArrayEquals(tlv.getValue(), tlv2.getValue());
}
@Test
public void testRoundtrip_ipv4() throws IOException {
final Header header = new Header();
header.setCommand(Command.PROXY);
header.setAddressFamily(AddressFamily.AF_INET);
header.setTransportProtocol(TransportProtocol.STREAM);
header.setSrcAddress(InetAddress.getByName("196.168.1.1").getAddress());
header.setDstAddress(InetAddress.getByName("196.168.5.5").getAddress());
header.setSrcPort(1111);
header.setDstPort(2222);
TlvRaw tlv = new TlvRaw();
tlv.setType(0xF0);
tlv.setValue(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
header.addTlv(tlv);
// write
ProxyProtocol protocol = new ProxyProtocol();
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
// validate
assertEquals(header.getCommand(), header2.getCommand());
assertEquals(header.getAddressFamily(), header2.getAddressFamily());
assertEquals(header.getTransportProtocol(), header2.getTransportProtocol());
assertArrayEquals(header.getSrcAddress(), header2.getSrcAddress());
assertArrayEquals(header.getDstAddress(), header2.getDstAddress());
assertEquals(header.getSrcPort(), header2.getSrcPort());
assertEquals(header.getDstPort(), header2.getDstPort());
TlvRaw tlv2 = (TlvRaw) Iterables.getOnlyElement(header2.getTlvs());
assertEquals(tlv.getType(), tlv2.getType());
assertArrayEquals(tlv.getValue(), tlv2.getValue());
}
@Test
public void testRoundtrip_unix() throws IOException {
final Header header = new Header();
header.setCommand(Command.PROXY);
header.setAddressFamily(AddressFamily.AF_UNIX);
header.setTransportProtocol(TransportProtocol.STREAM);
header.setSrcAddress(new byte[] {11, 12, 13});
header.setDstAddress(new byte[] {11, 12, 13});
TlvRaw tlv = new TlvRaw();
tlv.setType(0xF0);
tlv.setValue(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
header.addTlv(tlv);
// write
ProxyProtocol protocol = new ProxyProtocol();
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
// validate
assertEquals(header.getCommand(), header2.getCommand());
assertEquals(header.getAddressFamily(), header2.getAddressFamily());
assertEquals(header.getTransportProtocol(), header2.getTransportProtocol());
assertArrayEquals(header.getSrcAddress(), header2.getSrcAddress());
assertArrayEquals(header.getDstAddress(), header2.getDstAddress());
assertEquals(header.getSrcPort(), header2.getSrcPort());
assertEquals(header.getDstPort(), header2.getDstPort());
TlvRaw tlv2 = (TlvRaw) Iterables.getOnlyElement(header2.getTlvs());
assertEquals(tlv.getType(), tlv2.getType());
assertArrayEquals(tlv.getValue(), tlv2.getValue());
}
@Test
public void testRoundtrip_unspec() throws IOException {
final Header header = new Header();
header.setCommand(Command.LOCAL);
header.setAddressFamily(AddressFamily.AF_UNSPEC);
header.setTransportProtocol(TransportProtocol.UNSPEC);
TlvRaw tlv = new TlvRaw();
tlv.setType(0xF0);
tlv.setValue(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
header.addTlv(tlv);
// write
ProxyProtocol protocol = new ProxyProtocol();
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
// validate
assertEquals(header.getCommand(), header2.getCommand());
assertEquals(header.getAddressFamily(), header2.getAddressFamily());
assertEquals(header.getTransportProtocol(), header2.getTransportProtocol());
assertArrayEquals(header.getSrcAddress(), header2.getSrcAddress());
assertArrayEquals(header.getDstAddress(), header2.getDstAddress());
assertEquals(0, header2.getSrcPort());
assertEquals(0, header2.getDstPort());
TlvRaw tlv2 = (TlvRaw) Iterables.getOnlyElement(header2.getTlvs());
assertEquals(tlv.getType(), tlv2.getType());
assertArrayEquals(tlv.getValue(), tlv2.getValue());
}
@Test
public void testRoundtrip_customAdapter() throws IOException {
final Header header = createBaseHeader();
TestTlv tlv = new TestTlv();
tlv.setValue(7);
header.addTlv(tlv);
ProxyProtocol protocol = new ProxyProtocol();
protocol.getAdapters().put(TLV_TYPE, new TestTlvAdapter());
// write
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
TestTlv tlv2 = (TestTlv) Iterables.getOnlyElement(header2.getTlvs());
assertEquals(tlv.getType(), tlv2.getType());
assertEquals(tlv.getValue(), tlv2.getValue());
}
@Test
public void testRoundtrip_subTypeAdapter() throws IOException {
final Header header = createBaseHeader();
TlvSubTypeRaw tlv = new TlvSubTypeRaw();
tlv.setType(TLV_SUB_TYPE);
tlv.setSubType(7);
tlv.setValue(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
header.addTlv(tlv);
ProxyProtocol protocol = new ProxyProtocol();
TlvSubTypeRawAdapter adapter = new TlvSubTypeRawAdapter(TLV_SUB_TYPE);
protocol.setAdapters(ImmutableList.of(adapter));
// write
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
TlvSubTypeRaw tlv2 = (TlvSubTypeRaw) Iterables.getOnlyElement(header2.getTlvs());
assertEquals(tlv.getType(), tlv2.getType());
assertArrayEquals(tlv.getValue(), tlv2.getValue());
}
@Test
public void testRoundtrip_noChecksum() throws IOException {
final Header header = createBaseHeader();
ProxyProtocol protocol = new ProxyProtocol();
protocol.setEnforceChecksum(false);
// write
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
protocol.read(in);
}
@Test
public void testRoundtrip_noUnknown() throws IOException {
final Header header = createBaseHeader();
TlvRaw tlv = new TlvRaw();
tlv.setType(TLV_TYPE);
tlv.setValue(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
header.addTlv(tlv);
ProxyProtocol protocol = new ProxyProtocol();
protocol.setReadUnknownTLVs(false);
// write
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
// validate
assertTrue(header2.getTlvs().isEmpty());
}
@Test
public void testEnforceSize_padding() throws IOException {
int headerSize = 200;
ProxyProtocol protocol = new ProxyProtocol();
protocol.setEnforcedSize(Optional.of(headerSize));
Header header = createBaseHeader();
// write
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
assertEquals(headerSize, out.toByteArray().length);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
assertTrue(header2.getTlvs().isEmpty());
}
@Test
public void testEnforceSize_paddingNoChecksum() throws IOException {
int headerSize = 200;
ProxyProtocol protocol = new ProxyProtocol();
protocol.setEnforceChecksum(false);
protocol.setEnforcedSize(Optional.of(headerSize));
Header header = createBaseHeader();
// write
ByteArrayOutputStream out = new ByteArrayOutputStream();
protocol.write(header, out);
assertEquals(headerSize, out.toByteArray().length);
// read
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Header header2 = protocol.read(in);
assertTrue(header2.getTlvs().isEmpty());
}
@Test
public void testEnforceSize_tooLong() throws IOException {
thrown.expect(InvalidHeaderException.class);
int headerSize = 5;
ProxyProtocol protocol = new ProxyProtocol();
protocol.setEnforcedSize(Optional.of(headerSize));
protocol.write(createBaseHeader(), new ByteArrayOutputStream());
}
@Test
public void testValidateAdapters_happyPath() {
int type = 0xEE;
new ProxyProtocol().setAdapters(Collections.singleton(new TlvRawAdapter(type)));
}
@Test
public void testValidateAdapters_invalidType() {
thrown.expect(IllegalArgumentException.class);
int type = ProxyProtocolSpec.PP2_TYPE_ALPN;
new ProxyProtocol().setAdapters(Collections.singleton(new TlvRawAdapter(type)));
}
@Test
public void testSetAdapters_happyPath() {
ProxyProtocol proxyProtocol = new ProxyProtocol();
TestTlvAdapter adapter = new TestTlvAdapter();
proxyProtocol.setAdapters(Collections.singleton(adapter));
assertSame(adapter, Iterables.getOnlyElement(proxyProtocol.getAdapters().values()));
}
@Test
public void testSetAdapters_duplicateType() {
thrown.expect(IllegalArgumentException.class);
ProxyProtocol proxyProtocol = new ProxyProtocol();
TestTlvAdapter adapter = new TestTlvAdapter();
proxyProtocol.setAdapters(
ImmutableList.of(adapter, new TlvRawAdapter(adapter.getType())));
}
private Header createBaseHeader() throws UnknownHostException {
Header header = new Header();
header.setCommand(Command.PROXY);
header.setAddressFamily(AddressFamily.AF_INET6);
header.setTransportProtocol(TransportProtocol.STREAM);
header.setSrcAddress(InetAddress.getByName("1::2").getAddress());
header.setDstAddress(InetAddress.getByName("3::4").getAddress());
header.setSrcPort(1111);
header.setDstPort(2222);
return header;
}
private static class TestTlv implements Tlv {
private int value;
@Override
public int getType() {
return TLV_TYPE;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
private static class TestTlvAdapter implements TlvAdapter<TestTlv> {
@Override
public int getType() {
return TLV_TYPE;
}
@Override
public TestTlv read(InputAssist inputAssist, int length) throws IOException {
assert length == 1;
TestTlv tlv = new TestTlv();
tlv.setValue(inputAssist.readByte());
return tlv;
}
@Override
public void writeValue(Tlv tlv, DataOutputStream out) throws IOException {
out.writeByte(((TestTlv) tlv).getValue());
}
}
}
| 9,024 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/TlvSubTypeRawAdapterTest.java | package com.amazonaws.proprot;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNull;
public class TlvSubTypeRawAdapterTest {
final TlvSubTypeRawAdapter subTypeAdapter = new TlvSubTypeRawAdapter(8);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testReadSubType() throws IOException {
DataInputStream in = new DataInputStream(new ByteArrayInputStream(
new byte[] { -128, 1, 2, 3, 4}));
TlvSubTypeRaw subTypeTlv = subTypeAdapter.read(new InputAssist(in, false), 4);
assertArrayEquals(new byte[] {1, 2, 3}, subTypeTlv.getValue());
}
@Test
public void testReadSubTypeWithNoValue() throws IOException {
DataInputStream in = new DataInputStream(new ByteArrayInputStream(new byte[]{-128}));
TlvSubTypeRaw subTypeTlv = subTypeAdapter.read(new InputAssist(in, false), 1);
assertArrayEquals(new byte[] {}, subTypeTlv.getValue());
}
@Test
public void testWriteSubTypeWithNoValue() throws IOException {
TlvSubTypeRaw subTypeTlv = new TlvSubTypeRaw();
subTypeTlv.setType(1);
subTypeTlv.setSubType(128);
subTypeTlv.setValue(new byte[]{});
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
subTypeAdapter.writeValue(subTypeTlv, out);
assertArrayEquals(new byte[]{-128}, buf.toByteArray());
}
@Test
public void testReadSubTypeWithEmptyArray() throws IOException {
thrown.expect(InvalidHeaderException.class);
DataInputStream in = new DataInputStream(new ByteArrayInputStream(
new byte[0]));
TlvSubTypeRaw subTypeTlv = subTypeAdapter.read(new InputAssist(in, false), 0);
assertArrayEquals(new byte[] {}, subTypeTlv.getValue());
}
@Test
public void testWriteValueForTlvSubType() throws IOException {
TlvSubTypeRaw tlv = new TlvSubTypeRaw();
int subType = 128;
byte[] value = new byte[] {1, 2, 3, 4};
byte[] expectedValue = new byte[] {(byte) subType, 1, 2, 3, 4};
tlv.setValue(value);
tlv.setSubType(subType);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
subTypeAdapter.writeValue(tlv, out);
assertArrayEquals(expectedValue, buf.toByteArray());
}
}
| 9,025 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/ParserTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static com.amazonaws.proprot.Util.toHex;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.amazonaws.proprot.Header.SslFlags;
import com.amazonaws.proprot.ProxyProtocolSpec.AddressFamily;
import com.amazonaws.proprot.ProxyProtocolSpec.Command;
import com.amazonaws.proprot.ProxyProtocolSpec.TransportProtocol;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Shorts;
public class ParserTest {
private static final Optional<SslFlags> SSL_FLAGS = SslFlags.getOptional(true, false, true, false);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testReadPrefix_happyPath() throws IOException {
newParser(ProxyProtocolSpec.PREFIX).readPrefix();
}
@Test
public void testReadPrefix_different() throws IOException {
byte[] data = ProxyProtocolSpec.PREFIX.clone();
data[2] = (byte) 0xFF;
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("0xff");
newParser(data).readPrefix();
}
@Test
public void testReadPrefix_truncated() throws IOException {
byte[] data = new byte[] {
ProxyProtocolSpec.PREFIX[0],
ProxyProtocolSpec.PREFIX[1],
ProxyProtocolSpec.PREFIX[2],
};
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage(Integer.toString(data.length));
newParser(data).readPrefix();
}
@Test
public void testReadPrefix_empty() throws IOException {
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("0");
newParser(new byte[0]).readPrefix();
}
@Test
public void testReadCommand_happyPath() throws IOException {
assertEquals(Command.PROXY, newParser(0x21).readCommand());
}
@Test
public void testReadCommand_badVersion() throws IOException {
thrown.expect(InvalidHeaderException.class);
// expected version 2
thrown.expectMessage("2");
// read version
thrown.expectMessage("0xf");
assertEquals(Command.PROXY, newParser(0xF1).readCommand());
}
@Test
public void testReadCommand_badValue() throws IOException {
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("0xd");
thrown.expectMessage(Command.class.getSimpleName());
assertEquals(Command.PROXY, newParser(0x2D).readCommand());
}
@Test
public void testGetAddressFamily_happyPath() {
assertEquals(AddressFamily.AF_UNIX,
newParser(new byte[0]).getAddressFamily(0x3F));
}
@Test
public void testGetAddressFamily_badValue() {
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("0xf");
newParser(new byte[0]).getAddressFamily(0xF1);
}
@Test
public void testGetTransportProtocol_happyPath() {
assertEquals(TransportProtocol.DGRAM,
newParser(new byte[0]).getTransportProtocol(0xF2));
}
@Test
public void testGetTransportProtocol_badValue() {
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("0xf");
newParser(new byte[0]).getTransportProtocol(0x1F);
}
@Test
public void testToString() {
assertEquals("[0xff, 0x0, 0xa]",
new Parser().toString(new byte[] {-1, 0, 10}));
}
@Test
public void testReadAddresses_ip4() throws IOException {
AddressFamily addressFamily = AddressFamily.AF_INET;
TransportProtocol transportProtocol = TransportProtocol.STREAM;
Command command = Command.PROXY;
int ipSize = addressFamily.getAddressSize();
int portSize = 2;
byte[] srcAddress = InetAddress.getByName("1.2.3.4").getAddress();
byte[] dstAddress = InetAddress.getByName("5.6.7.8").getAddress();
short srcPort = 501;
short dstPort = 601;
byte[] stream = Bytes.concat(srcAddress, dstAddress,
Shorts.toByteArray(srcPort), Shorts.toByteArray(dstPort));
assertEquals(ipSize * 2 + portSize * 2, stream.length);
Parser parser = newParser(stream);
Header header = new Header();
header.setCommand(command);
header.setAddressFamily(addressFamily);
header.setTransportProtocol(transportProtocol);
parser.readAddresses(header);
assertArrayEquals(srcAddress, header.getSrcAddress());
assertArrayEquals(dstAddress, header.getDstAddress());
assertEquals(srcPort, header.getSrcPort());
assertEquals(dstPort, header.getDstPort());
}
@Test
public void testReadAddresses_ip6() throws IOException {
AddressFamily addressFamily = AddressFamily.AF_INET6;
TransportProtocol transportProtocol = TransportProtocol.STREAM;
Command command = Command.PROXY;
int ipSize = addressFamily.getAddressSize();
int portSize = 2;
byte[] srcAddress = InetAddress.getByName("1:2:3:4:5:6:7:8").getAddress();
byte[] dstAddress = InetAddress.getByName("9:A:B:C:D:E:F:1").getAddress();
short srcPort = 501;
short dstPort = 601;
assertEquals(ipSize, srcAddress.length);
assertEquals(ipSize, dstAddress.length);
byte[] stream = Bytes.concat(srcAddress, dstAddress,
Shorts.toByteArray(srcPort), Shorts.toByteArray(dstPort));
assertEquals(ipSize * 2 + portSize * 2, stream.length);
Parser parser = newParser(stream);
Header header = new Header();
header.setCommand(command);
header.setAddressFamily(addressFamily);
header.setTransportProtocol(transportProtocol);
parser.readAddresses(header);
assertArrayEquals(srcAddress, header.getSrcAddress());
assertArrayEquals(dstAddress, header.getDstAddress());
assertEquals(srcPort, header.getSrcPort());
assertEquals(dstPort, header.getDstPort());
}
@Test
public void testReadAddresses_unix() throws IOException {
AddressFamily addressFamily = AddressFamily.AF_UNIX;
TransportProtocol transportProtocol = TransportProtocol.DGRAM;
Command command = Command.PROXY;
int addressSize = addressFamily.getAddressSize();
byte[] srcAddress = new byte[] {1,2,3,4};
byte[] srcPadding = new byte[addressSize - srcAddress.length];
byte[] dstAddress = new byte[] {6,7,8,9,10};
byte[] dstPadding = new byte[addressSize - dstAddress.length];
byte[] stream = Bytes.concat(srcAddress, srcPadding, dstAddress, dstPadding);
assertEquals(addressSize * 2, stream.length);
Parser parser = newParser(stream);
Header header = new Header();
header.setCommand(command);
header.setAddressFamily(addressFamily);
header.setTransportProtocol(transportProtocol);
parser.readAddresses(header);
assertEquals(0, header.getSrcPort());
assertEquals(0, header.getDstPort());
assertArrayEquals(srcAddress, header.getSrcAddress());
assertArrayEquals(dstAddress, header.getDstAddress());
}
@Test
public void testReadAddresses_unspec() throws IOException {
Parser parser = newParser(new byte[0]);
Header header = new Header();
header.setAddressFamily(AddressFamily.AF_UNSPEC);
parser.readAddresses(header);
assertArrayEquals(new byte[0], header.getSrcAddress());
assertArrayEquals(new byte[0], header.getDstAddress());
assertEquals(0, header.getSrcPort());
assertEquals(0, header.getDstPort());
}
@Test
public void testReadUnixAddress() throws IOException {
checkUnixAddressRoundtrip(new byte[] {1,2,3,4,5});
checkUnixAddressRoundtrip(new byte[0]);
byte[] b = new byte[AddressFamily.AF_UNIX.getAddressSize()];
Arrays.fill(b, (byte) 1);
checkUnixAddressRoundtrip(b);
}
private void checkUnixAddressRoundtrip(byte[] expected) throws IOException {
final byte[] b = Arrays.copyOf(expected, 200);
byte[] b2 = newParser(b).readUnixAddress("a string");
assertArrayEquals(expected, b2);
}
/**
* Reads 2 TLVs - one - declared, second - read as undeclared raw.
*/
@Test
public void testReadTLVs_happyPath() throws IOException {
TestTlvAdapter a = new TestTlvAdapter();
a.bytesToRead = 2;
int type2 = a.getType() + 1;
int type3 = ProxyProtocolSpec.PP2_TYPE_AUTHORITY;
byte[] data = new byte[] {
// TLV with the registered adapter
(byte) a.getType(), 0, (byte) a.bytesToRead, 1, 2,
// TLV without registered adapter
(byte) type2, 0, 4, 1, 2, 3, 4,
// TLV read to header
(byte) type3, 0, 3, 'a', 'b', 'c'};
Parser parser = newParser(data);
parser.getAssist().setHeaderSize(data.length);
parser.getAdapters().put(a.getType(), a);
Header header = new Header();
assertTrue(header.getTlvs().isEmpty());
assertFalse(header.getAuthority().isPresent());
parser.readTLVs(header);
assertEquals(2, header.getTlvs().size());
assertEquals(a.getType(), header.getTlvs().get(0).getType());
TlvRaw tlv = (TlvRaw) header.getTlvs().get(1);
assertEquals(type2, tlv.getType());
assertArrayEquals(new byte[] {1,2,3,4}, tlv.getValue());
assertEquals("abc", header.getAuthority().get());
}
@Test
public void testReadTLVSubTypes() throws IOException {
TlvSubTypeRawAdapter a = new TlvSubTypeRawAdapter(0Xf);
int type2 = a.getType() + 1;
int type3 = ProxyProtocolSpec.PP2_TYPE_AUTHORITY;
byte[] data = new byte[] {
// TLV with the registered TlvSubType adapter
(byte) a.getType(), 0, (byte) 3, 5, 1, 2,
// TLV without registered adapter
(byte) type2, 0, 4, 1, 2, 3, 4,
// TLV read to header
(byte) type3, 0, 3, 'a', 'b', 'c'};
Parser parser = newParser(data);
parser.getAssist().setHeaderSize(data.length);
parser.getAdapters().put(a.getType(), a);
Header header = new Header();
assertTrue(header.getTlvs().isEmpty());
assertFalse(header.getAuthority().isPresent());
parser.readTLVs(header);
assertEquals(2, header.getTlvs().size());
assertEquals(a.getType(), header.getTlvs().get(0).getType());
TlvSubTypeRaw tlv0 = (TlvSubTypeRaw) header.getTlvs().get(0);
TlvRaw tlv = (TlvRaw) header.getTlvs().get(1);
assertEquals(type2, tlv.getType());
assertArrayEquals(new byte[] {1,2,3,4}, tlv.getValue());
assertEquals("abc", header.getAuthority().get());
}
@Test
public void testReadTLVs_twoTlvsOfSameType() throws IOException {
int type = 0x55;
byte[] data = new byte[] {
(byte) type, 0, 4, 1, 2, 3, 4,
(byte) type, 0, 4, 1, 2, 3, 4,
};
Parser parser = newParser(data);
parser.getAssist().setHeaderSize(data.length);
parser.readTLVs(new Header());
}
@Test
public void testReadTLVs_mismatchingType() throws IOException {
TestTlvAdapter a = new TestTlvAdapter();
a.bytesToRead = 2;
int type2 = 22;
thrown.expect(IllegalStateException.class);
thrown.expectMessage(toHex(type2));
thrown.expectMessage(toHex(a.getType()));
byte[] data = new byte[] {
(byte) type2, 0, (byte) a.bytesToRead, 1, 2};
Parser parser = newParser(data);
parser.getAssist().setHeaderSize(data.length);
parser.getAdapters().put(type2, a);
parser.readTLVs(new Header());
}
@Test
public void testReadTlvValueToHeader_happyPath() throws IOException {
TestTlvAdapter adapter = new TestTlvAdapter();
adapter.bytesToRead = 2;
newParser(new byte[] {1,2,3}).readTlvValue(adapter, 2);
}
@Test
public void testReadTlvValueToHeader_wrongReadLen() throws IOException {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("1");
thrown.expectMessage("2");
TestTlvAdapter adapter = new TestTlvAdapter();
adapter.bytesToRead = 2;
newParser(new byte[] {1,2,3}).readTlvValue(adapter, 1);
}
@Test
public void testReadAddressFamilyAndTransportProtocol() throws IOException {
Header header = new Header();
header.setCommand(Command.PROXY);
assertEquals(AddressFamily.AF_UNSPEC, header.getAddressFamily());
assertEquals(TransportProtocol.UNSPEC, header.getTransportProtocol());
AddressFamily af = AddressFamily.AF_INET6;
TransportProtocol tp = TransportProtocol.STREAM;
Parser parser = newParser(new byte[] {(byte) ProxyProtocolSpec.pack(af, tp)});
parser.readAddressFamilyAndTransportProtocol(header);
assertEquals(af, header.getAddressFamily());
assertEquals(tp, header.getTransportProtocol());
}
@Test
public void testMaybeValidateChecksum_happyPath() throws IOException {
byte[] data = new byte[] {
(byte) ProxyProtocolSpec.PP2_TYPE_CRC32C, 0, 4,
(byte) 0xE3, (byte) 0x7E, (byte) 0xA1, (byte) 0x85};
Parser parser = newParser(data);
parser.getAssist().setHeaderSize(data.length);
parser.readTLVs(new Header());
parser.maybeValidateChecksum();
}
@Test
public void testMaybeValidateChecksum_doesNotMatch() throws IOException {
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("Invalid ");
thrown.expectMessage("0x0");
byte[] data = new byte[] {
(byte) ProxyProtocolSpec.PP2_TYPE_CRC32C, 0, 4, 0, 0, 0, 0};
Parser parser = newParser(data);
parser.getAssist().setHeaderSize(data.length);
parser.readTLVs(new Header());
parser.maybeValidateChecksum();
}
@Test
public void testMaybeValidateChecksum_notEnforceChecksum() {
Parser parser = newParser(new byte[0]);
parser.setEnforceChecksum(false);
parser.maybeValidateChecksum();
}
@Test
public void testMaybeValidateChecksum_checksumNotFound() {
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("not found");
Parser parser = newParser(new byte[0]);
parser.maybeValidateChecksum();
}
@Test
public void testReadAlpn() throws IOException {
byte[] data = new byte[] {1, 2, 3, 4};
Header header = new Header();
assertFalse(header.getAlpn().isPresent());
newParser(data).readAlpn(header, data.length);
assertArrayEquals(data, header.getAlpn().get());
}
@Test
public void testReadAuthority() throws IOException {
byte[] data = new byte[] {'a', 'b', 'c'};
Header header = new Header();
assertFalse(header.getAuthority().isPresent());
newParser(data).readAuthority(header, data.length);
assertEquals("abc", header.getAuthority().get());
}
@Test
public void testReadSslFlags_allSet() throws IOException {
byte[] data = new byte[] {7, 0, 0, 0, 0};
Header header = new Header();
assertFalse(header.getSslFlags().isPresent());
newParser(data).readSslFlags(header, data.length);
SslFlags flags = header.getSslFlags().get();
assertTrue(flags.isClientConnectedWithSsl());
assertTrue(flags.isClientProvidedCertDuringConnection());
assertTrue(flags.isClientProvidedCertDuringSession());
assertTrue(flags.isClientVerifiedCert());
}
@Test
public void testReadSslFlags_allClear() throws IOException {
byte[] data = new byte[] {0, 0, 0, 0, 1};
Header header = new Header();
assertFalse(header.getSslFlags().isPresent());
newParser(data).readSslFlags(header, data.length);
SslFlags flags = header.getSslFlags().get();
assertFalse(flags.isClientConnectedWithSsl());
assertFalse(flags.isClientProvidedCertDuringConnection());
assertFalse(flags.isClientProvidedCertDuringSession());
assertFalse(flags.isClientVerifiedCert());
}
@Test
public void testReadCRC32c() throws IOException {
byte[] data = Ints.toByteArray(12345);
newParser(data).readCRC32c(data.length);
}
@Test
public void testReadSslVersion() throws IOException {
byte[] data = new byte[] {'a', 'b', 'c'};
Header header = new Header();
header.setSslFlags(SSL_FLAGS);
assertFalse(header.getSslVersion().isPresent());
newParser(data).readSslVersion(header, data.length);
assertEquals("abc", header.getSslVersion().get());
}
@Test
public void testReadSslCommonName() throws IOException {
byte[] data = new byte[] {'a', 'b', 'c'};
Header header = new Header();
header.setSslFlags(SSL_FLAGS);
assertFalse(header.getSslCommonName().isPresent());
newParser(data).readSslCommonName(header, data.length);
assertEquals("abc", header.getSslCommonName().get());
}
@Test
public void testReadSslCipher() throws IOException {
byte[] data = new byte[] {'a', 'b', 'c'};
Header header = new Header();
header.setSslFlags(SSL_FLAGS);
assertFalse(header.getSslCipher().isPresent());
newParser(data).readSslCipher(header, data.length);
assertEquals("abc", header.getSslCipher().get());
}
@Test
public void testReadSslSigAlg() throws IOException {
byte[] data = new byte[] {'a', 'b', 'c'};
Header header = new Header();
header.setSslFlags(SSL_FLAGS);
assertFalse(header.getSslSigAlg().isPresent());
newParser(data).readSslSigAlg(header, data.length);
assertEquals("abc", header.getSslSigAlg().get());
}
@Test
public void testReadSslKeyAlg() throws IOException {
byte[] data = new byte[] {'a', 'b', 'c'};
Header header = new Header();
header.setSslFlags(SSL_FLAGS);
assertFalse(header.getSslKeyAlg().isPresent());
newParser(data).readSslKeyAlg(header, data.length);
assertEquals("abc", header.getSslKeyAlg().get());
}
@Test
public void testReadNetNS() throws IOException {
byte[] data = new byte[] {'a', 'b', 'c'};
Header header = new Header();
header.setSslFlags(SSL_FLAGS);
assertFalse(header.getNetNS().isPresent());
newParser(data).readNetNS(header, data.length);
assertEquals("abc", header.getNetNS().get());
}
@Test
public void testAddressRemovalWithLocalCommand() throws IOException {
byte stream[] = {
0x0d, 0x0a, 0x0d, 0x0a, /* Start of Sig */
0x00, 0x0d, 0x0a, 0x51,
0x55, 0x49, 0x54, 0x0a, /* End of Sig */
0x20, 0x11, 0x00, 0x0c, /* ver_cmd, fam and len */
(byte) 0xac, 0x1f, 0x07, 0x71, /* Caller src ip */
(byte) 0xac, 0x1f, 0x0a, 0x1f, /* Endpoint dst ip */
(byte) 0xc8, (byte) 0xf2, 0x00, 0x50 /* Proxy src port & dst port */
};
Parser parser = new Parser();
parser.setEnforceChecksum(false);
Header header = new Header();
byte[] defaultAddress = header.getSrcAddress();
header = parser.read(new ByteArrayInputStream(stream));
assertEquals(Command.LOCAL, header.getCommand());
assertEquals(defaultAddress, header.getSrcAddress());
assertEquals(defaultAddress, header.getDstAddress());
assertEquals(0, header.getSrcPort());
assertEquals(0, header.getDstPort());
assertEquals(AddressFamily.AF_UNSPEC, header.getAddressFamily());
assertEquals(TransportProtocol.UNSPEC, header.getTransportProtocol());
}
private Parser newParser(int b) {
return newParser(new byte[] {(byte) b});
}
private Parser newParser(byte[] data) {
final Parser parser = new Parser();
parser.init(new ByteArrayInputStream(data));
return parser;
}
private final class TestTlvAdapter implements TlvAdapter<TlvRaw> {
public int bytesToRead;
@Override
public void writeValue(Tlv value, DataOutputStream out) {}
@Override
public TlvRaw read(InputAssist inputAssist, int length) throws IOException {
TlvRaw tlv = new TlvRaw();
tlv.setType(getType());
tlv.setValue(new byte[bytesToRead]);
inputAssist.getDataInputStream().read(tlv.getValue());
return tlv;
}
@Override
public int getType() {
return 0xF0;
}
}
}
| 9,026 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/CRC32COutputStreamTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Test;
import com.google.common.primitives.Ints;
public class CRC32COutputStreamTest {
@Test
public void testCRC32CSamples() throws IOException {
// samples from https://tools.ietf.org/html/rfc7143 ending in byte[] {0, 0, 0, 0}
// the checksum is known for the zero checksum value
assertCRC32C(0x8A9136AA,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00);
assertCRC32C(0xD9963A56,
(byte) 0x01, (byte) 0xC0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x14, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x14, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x18,
(byte) 0x28, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00);
}
private void assertCRC32C(int crc, byte... data) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
CRC32COutputStream out = new CRC32COutputStream(bout, true);
int dataLength = data.length - Integer.BYTES;
out.write(data, 0, dataLength);
out.writeChecksum();
byte[] buf = bout.toByteArray();
assertEquals(data.length, buf.length);
assertArrayEquals(Ints.toByteArray(crc), Arrays.copyOfRange(buf, dataLength, data.length));
// code coverage, keep static code analysis happy
out.flush();
out.close();
}
}
| 9,027 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/TlvRawAdapterTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.junit.Assert.assertArrayEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.junit.Test;
public class TlvRawAdapterTest {
final TlvRawAdapter adapter = new TlvRawAdapter(8);
@Test
public void testRead() throws IOException {
DataInputStream in = new DataInputStream(new ByteArrayInputStream(
new byte[] {1, 2, 3, 4}));
TlvRaw tlv = adapter.read(new InputAssist(in, false), 3);
assertArrayEquals(new byte[] {1, 2, 3}, tlv.getValue());
}
@Test
public void testWriteValue() throws IOException {
TlvRaw tlv = new TlvRaw();
byte[] value = new byte[] {1, 2, 3, 4};
tlv.setValue(value);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
adapter.writeValue(tlv, out);
assertArrayEquals(value, buf.toByteArray());
}
@Test
public void testReadEmptyArray() throws IOException {
byte[] expected = new byte[]{};
DataInputStream in = new DataInputStream(new ByteArrayInputStream(expected));
TlvRaw tlv = adapter.read(new InputAssist(in, false), 0);
assertArrayEquals(new byte[] {}, tlv.getValue());
}
@Test
public void testWriteWithNoValue() throws IOException {
TlvRaw tlv = new TlvRaw();
tlv.setType(1);
tlv.setValue(new byte[]{});
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
adapter.writeValue(tlv, out);
assertArrayEquals(new byte[]{}, buf.toByteArray());
}
}
| 9,028 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/InputAssistTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class InputAssistTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testValidateHeaderSizeBeforeRead_happyPath() throws IOException {
int headerSize = 5;
InputAssist assist = newAssist(new byte[] {0, (byte) headerSize});
assist.readHeaderSize();
int read = 2;
assist.validateHeaderSizeBeforeRead(
ProxyProtocolSpec.ADD_TO_HEADER_SIZE - read + headerSize);
}
@Test
public void testValidateHeaderSizeBeforeRead_overHeaderSize() throws IOException {
int headerSize = 5;
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage(Integer.toString(ProxyProtocolSpec.ADD_TO_HEADER_SIZE + headerSize));
InputAssist assist = newAssist(new byte[] {0, (byte) headerSize});
assist.readHeaderSize();
int read = 2;
assist.validateHeaderSizeBeforeRead(
ProxyProtocolSpec.ADD_TO_HEADER_SIZE - read + headerSize + 1);
}
@Test
public void testReadShort_happyPath() throws IOException {
InputAssist assist = newAssist(new byte[] {-1, -1});
assertEquals(0xFFFF, assist.readShort());
}
@Test
public void testReadShort_truncated() throws IOException {
thrown.expect(InvalidHeaderException.class);
newAssist(new byte[] {-1}).readShort();
}
@Test
public void testReadShort_empty() throws IOException {
thrown.expect(InvalidHeaderException.class);
newAssist(new byte[0]).readShort();
}
@Test
public void testReadBytes_empty() throws IOException {
newAssist(new byte[0]).readBytes(0, "label");
}
private InputAssist newAssist(byte[] data) {
return new InputAssist(new ByteArrayInputStream(data), false);
}
}
| 9,029 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/Compatibility_AwsNetworkLoadBalancerTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import org.junit.Test;
import com.amazonaws.proprot.ProxyProtocolSpec.AddressFamily;
import com.amazonaws.proprot.ProxyProtocolSpec.Command;
import com.amazonaws.proprot.ProxyProtocolSpec.TransportProtocol;
import com.google.common.collect.Iterables;
/**
* The header generated by AWS Network Load Balancer,
* see http://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#proxy-protocol .
*/
public class Compatibility_AwsNetworkLoadBalancerTest {
/**
* A connection done through Private Link/Interface VPC endpoint.
*/
@Test
public void test_PrivateLink() throws IOException {
byte expected_content[] = {
0x0d, 0x0a, 0x0d, 0x0a, /* Start of Sig */
0x00, 0x0d, 0x0a, 0x51,
0x55, 0x49, 0x54, 0x0a, /* End of Sig */
0x21, 0x11, 0x00, 0x54, /* ver_cmd, fam and len */
(byte) 0xac, 0x1f, 0x07, 0x71, /* Caller src ip */
(byte) 0xac, 0x1f, 0x0a, 0x1f, /* Endpoint dst ip */
(byte) 0xc8, (byte) 0xf2, 0x00, 0x50, /* Proxy src port & dst port */
0x03, 0x00, 0x04, (byte) 0xe8, /* CRC TLV start */
(byte) 0xd6, (byte) 0x89, 0x2d, (byte) 0xea, /* CRC TLV cont, VPCE id TLV start */
0x00, 0x17, 0x01, 0x76,
0x70, 0x63, 0x65, 0x2d,
0x30, 0x38, 0x64, 0x32,
0x62, 0x66, 0x31, 0x35,
0x66, 0x61, 0x63, 0x35,
0x30, 0x30, 0x31, 0x63,
0x39, 0x04, 0x00, 0x24, /* VPCE id TLV end, NOOP TLV start*/
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, /* NOOP TLV end */
};
ProxyProtocol protocol = new ProxyProtocol();
ByteArrayInputStream in = new ByteArrayInputStream(expected_content);
Header header = protocol.read(in);
assertEquals(AddressFamily.AF_INET, header.getAddressFamily());
assertEquals(TransportProtocol.STREAM, header.getTransportProtocol());
assertEquals(Command.PROXY, header.getCommand());
assertEquals("172.31.7.113", getAddressAsStr(header.getSrcAddress()));
assertEquals("172.31.10.31", getAddressAsStr(header.getDstAddress()));
assertEquals(0xC8F2, header.getSrcPort());
assertEquals(80, header.getDstPort());
TlvRaw vpceIdTlv = (TlvRaw) Iterables.getOnlyElement(header.getTlvs());
// PP2_TYPE_AWS (0xEA)
assertEquals(0xEA, vpceIdTlv.getType());
byte[] tlvValue = vpceIdTlv.getValue();
// PP2_SUBTYPE_AWS_VPCE_ID (0x01)
assertEquals(1, tlvValue[0]);
byte[] vpceIdValue = Arrays.copyOfRange(tlvValue, 1, tlvValue.length);
assertArrayEquals("vpce-08d2bf15fac5001c9".getBytes(), vpceIdValue);
}
private String getAddressAsStr(byte[] address) throws UnknownHostException {
return InetAddress.getByAddress(address).getHostAddress();
}
}
| 9,030 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/GeneratorTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class GeneratorTest {
private static final int TLV_TYPE = 0xF0;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testGetAdapter_found() {
Tlv tlv = new TestTlv(TLV_TYPE);
Generator generator = new Generator();
TestTlvAdapter adapter = new TestTlvAdapter();
generator.getAdapters().put(tlv.getType(), adapter);
assertSame(adapter, generator.getAdapter(tlv));
}
@Test
public void testGetAdapter_raw() {
TlvRaw tlv = new TlvRaw();
tlv.setType(0xF0);
tlv.setValue(new byte[] {1, 2, 3});
assertThat(new Generator().getAdapter(tlv), instanceOf(TlvRawAdapter.class));
}
@Test
public void testGetAdapter_noAdapter() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("0xf0");
Tlv tlv = new TestTlv(0xF0);
new Generator().getAdapter(tlv);
}
@Test
public void testMaybePadHeader_notPadded() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
new Generator().maybePadHeader(2000, out);
assertEquals(0, out.size());
}
@Test
public void testMaybePadHeader_exactSize() throws IOException {
callPadHeader(0);
}
@Test
public void testMaybePadHeader_exceedsEnforcedSize() throws IOException {
thrown.expect(InvalidHeaderException.class);
callPadHeader(-1);
}
/**
* Special value - can't pad 1 byte.
*/
@Test
public void testMaybePadHeader_lessThanEnforcedSizeBy1() throws IOException {
thrown.expect(InvalidHeaderException.class);
callPadHeader(1);
}
/**
* Special value - can't pad 2 bytes.
*/
@Test
public void testMaybePadHeader_lessThenEnforcedSizeBy2() throws IOException {
thrown.expect(InvalidHeaderException.class);
callPadHeader(2);
}
@Test
public void testMaybePadHeader_lessThenEnforcedSize() throws IOException {
callPadHeader(3);
callPadHeader(4);
callPadHeader(10000);
}
private void callPadHeader(int enforcedSizeChange) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Generator generator = new Generator();
generator.setEnforcedSize(Optional.of(2000 + enforcedSizeChange));
generator.maybePadHeader(2000, out);
assertEquals(enforcedSizeChange, out.size());
}
private class TestTlv implements Tlv {
private final int type;
public TestTlv(int type) {
this.type = type;
}
@Override
public int getType() {
return type;
}
}
private class TestTlvAdapter implements TlvAdapter<TestTlv> {
@Override
public int getType() {
return TLV_TYPE;
}
@Override
public TestTlv read(InputAssist inputAssist, int length) {
return null;
}
@Override
public void writeValue(Tlv tlv, DataOutputStream out) {}
}
}
| 9,031 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/NullHasherTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.google.common.hash.Hasher;
public class NullHasherTest {
@Test
public void testBasics() {
Hasher hasher = NullHasher.INSTANCE;
assertEquals(0, hasher.hash().asInt());
hasher.putBoolean(false);
hasher.putByte((byte) 3);
hasher.putBytes(new byte[0]);
hasher.putBytes(null, 3, 3);
hasher.putChar('c');
hasher.putDouble(3.3);
hasher.putFloat(3.4f);
hasher.putInt(7);
hasher.putLong(3);
hasher.putObject(null, null);
hasher.putShort((short) 7);
hasher.putString(null, null);
hasher.putUnencodedChars(null);
}
}
| 9,032 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/ProxyProtocolSpecTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static java.lang.Integer.toHexString;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.amazonaws.proprot.ProxyProtocolSpec.Code;
import com.amazonaws.proprot.ProxyProtocolSpec.Command;
public class ProxyProtocolSpecTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testValueOf_happyPath() {
assertEquals(Command.PROXY, Command.valueOf(Command.PROXY.getCode(), 37));
}
@Test
public void testValidatePrefix_valueOf() {
thrown.expect(InvalidHeaderException.class);
int pos = 37;
thrown.expectMessage(Integer.toString(pos));
int code = 89;
thrown.expectMessage("0x" + toHexString(code));
thrown.expectMessage(Command.class.getSimpleName());
Command.valueOf(code, pos);
}
@Test
public void testInitCodeEnum_happyPath() {
Map<Integer, Command> valuesByCode = new HashMap<>();
ProxyProtocolSpec.initCodeEnum(Command.values(), valuesByCode);
assertEquals(Command.values().length, valuesByCode.size());
}
@Test
public void testInitCodeEnum_duplicatedCode() {
thrown.expect(InvalidHeaderException.class);
thrown.expectMessage("0x" + toHexString(TestCode.DUP_1.getCode()));
thrown.expectMessage(TestCode.DUP_1.name());
thrown.expectMessage(TestCode.DUP_2.name());
ProxyProtocolSpec.initCodeEnum(TestCode.values(), new HashMap<>());
}
@Test
public void testToString() {
assertEquals("PROXY(1)", Command.PROXY.toString());
}
private enum TestCode implements Code {
CODE0(0x0), CODE1(0x1), DUP_1(22), DUP_2(22);
private final int code;
private TestCode(int code) {
this.code = code;
}
@Override
public int getCode() {
return code;
}
}
}
| 9,033 |
0 | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/tst/com/amazonaws/proprot/CRC32CInputStreamTest.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import org.junit.Test;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
public class CRC32CInputStreamTest {
/**
* Make sure our CRC32C algorithm works as expected.
*/
@Test
public void testCRC32CSamples() throws IOException {
assertCRC32C(0xC1D04330, (byte) 'a');
assertCRC32C(0x364B3FB7, (byte) 'a', (byte) 'b', (byte) 'c');
assertCRC32C(0xc1d04330, (byte) 0x61);
// samples from https://tools.ietf.org/html/rfc3720#appendix-B.4 ,
// reverted because it seems they had wrong endianness according to the
// Guava and JDK9 implementations of CRC32C
assertCRC32C(0x8A9136AA,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00);
assertCRC32C(0x62A8AB43,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF);
assertCRC32C(0x46DD794E,
(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
(byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B, (byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F,
(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17,
(byte) 0x18, (byte) 0x19, (byte) 0x1A, (byte) 0x1B, (byte) 0x1C, (byte) 0x1D, (byte) 0x1E, (byte) 0x1F);
assertCRC32C(0x113FDB5C,
(byte) 0x1F, (byte) 0x1E, (byte) 0x1D, (byte) 0x1C, (byte) 0x1B, (byte) 0x1A, (byte) 0x19, (byte) 0x18,
(byte) 0x17, (byte) 0x16, (byte) 0x15, (byte) 0x14, (byte) 0x13, (byte) 0x12, (byte) 0x11, (byte) 0x10,
(byte) 0x0F, (byte) 0x0E, (byte) 0x0D, (byte) 0x0C, (byte) 0x0B, (byte) 0x0A, (byte) 0x09, (byte) 0x08,
(byte) 0x07, (byte) 0x06, (byte) 0x05, (byte) 0x04, (byte) 0x03, (byte) 0x02, (byte) 0x01, (byte) 0x00);
assertCRC32C(0xD9963A56,
(byte) 0x01, (byte) 0xC0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x14, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x14, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x18,
(byte) 0x28, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00);
}
@Test
public void testReadChecksum() throws Exception {
byte[] data = new byte[] {0, 0, 0, 1};
CRC32CInputStream in1 = new CRC32CInputStream(new ByteArrayInputStream(data), true);
CRC32CInputStream in2 = new CRC32CInputStream(new ByteArrayInputStream(data), true);
DataInputStream din2 = new DataInputStream(in2);
assertEquals(in1.readChecksum(), din2.readInt());
CRC32CInputStream in0 = new CRC32CInputStream(new ByteArrayInputStream(
new byte[] {0, 0, 0, 0}), true);
in0.read(new byte[4]);
assertEquals(in0.getChecksum(), in1.getChecksum());
in1.close();
in2.close();
din2.close();
in0.close();
}
private void assertCRC32C(int crc, byte... data) throws IOException {
byte[] buf = new byte[100];
assertThat(buf.length, greaterThanOrEqualTo(data.length));
CRC32CInputStream in = new CRC32CInputStream(new ByteArrayInputStream(data), true);
assertEquals(data.length, in.read(buf));
int checksum = in.getChecksum();
in.close();
assertEquals("Expected " + Util.toHex(crc)
+ ", calculated " + Util.toHex(checksum), crc, checksum);
// make sure we calculate the same value as the hasher:
{
Hasher hasher = Hashing.crc32c().newHasher();
hasher.putBytes(data);
assertEquals("Expected " + Util.toHex(crc)
+ ", calculated " + Util.toHex(hasher.hash().asInt()), crc, hasher.hash().asInt());
}
}
}
| 9,034 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/Parser.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static com.amazonaws.proprot.Util.toHex;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import com.amazonaws.proprot.Header.SslFlags;
import com.amazonaws.proprot.ProxyProtocolSpec.AddressFamily;
import com.amazonaws.proprot.ProxyProtocolSpec.Command;
import com.amazonaws.proprot.ProxyProtocolSpec.TransportProtocol;
/**
* Parses Proxy Protocol v2.
* Is not thread-safe. Reusable.
* @see ProxyProtocol#read(java.io.InputStream)
*/
class Parser {
private final Map<Integer, TlvAdapter<?>> adapters = new HashMap<>();
private boolean readUnknownTLVs = true;
private InputAssist assist;
private boolean enforceChecksum = true;
private boolean foundChecksum;
private int expectedChecksum;
public Header read(InputStream inputStream) throws IOException, InvalidHeaderException {
init(inputStream);
readPrefix();
assert assist.getReadCount() == 12;
Header header = new Header();
header.setCommand(readCommand());
assert assist.getReadCount() == 13;
readAddressFamilyAndTransportProtocol(header);
assert assist.getReadCount() == 14;
assist.readHeaderSize();
assert assist.getReadCount() == ProxyProtocolSpec.ADD_TO_HEADER_SIZE;
readAddresses(header);
header.correctAddressesForLocalCommand();
// the remainder of the header are TLVs
readTLVs(header);
maybeValidateChecksum();
header.validate();
return header;
}
/**
* Initializes resources for parsing.
* Is exposed to be called by tests, so the tests can call low-level methods.
*/
void init(InputStream inputStream) {
foundChecksum = false;
assist = new InputAssist(inputStream, enforceChecksum);
}
void readPrefix() throws IOException {
int length = ProxyProtocolSpec.PREFIX.length;
byte[] buf = assist.readBytes(length, "Proxy Protocol prefix");
if (!Arrays.equals(buf, ProxyProtocolSpec.PREFIX)) {
throw new InvalidHeaderException(
"Invalid Proxy Protocol prefix " + toString(buf) + ". "
+ "Expected " + toString(ProxyProtocolSpec.PREFIX));
}
}
Command readCommand() throws IOException {
int versionAndCommand = assist.readByte();
// higher 4 bits - version
int version = (versionAndCommand >>> 4) & 0xF;
validateProtocolVersion(version);
// lower 4 bits - command
int commandCode = versionAndCommand & 0xF;
return Command.valueOf(commandCode, assist.getReadPos());
}
private void validateProtocolVersion(int version) {
if (version != ProxyProtocolSpec.PROTOCOL_V2) {
throw new InvalidHeaderException(
"Expected version value 0x2 but got " + toHex(version)
+ " at the byte " + assist.getReadPos());
}
}
void readAddressFamilyAndTransportProtocol(Header header) throws IOException {
int transportProtocolAddAddressFamily = assist.readByte();
header.setAddressFamily(getAddressFamily(transportProtocolAddAddressFamily));
header.setTransportProtocol(getTransportProtocol(transportProtocolAddAddressFamily));
}
AddressFamily getAddressFamily(
int transportProtocolAddAddressFamily) {
int code = (transportProtocolAddAddressFamily >>> 4) & 0xF;
return AddressFamily.valueOf(code, assist.getReadPos());
}
TransportProtocol getTransportProtocol(
int transportProtocolAddAddressFamily) {
int code = transportProtocolAddAddressFamily & 0xF;
return TransportProtocol.valueOf(code, assist.getReadPos());
}
void readAddresses(Header header) throws IOException {
final AddressFamily af = header.getAddressFamily();
if (af.equals(AddressFamily.AF_INET) ||
af.equals(AddressFamily.AF_INET6)) {
header.setSrcAddress(
readAddress(header.getAddressFamily(), "src"));
header.setDstAddress(
readAddress(header.getAddressFamily(), "dst"));
header.setSrcPort(assist.readShort());
header.setDstPort(assist.readShort());
} else if (af.equals(AddressFamily.AF_UNIX)) {
header.setSrcAddress(readUnixAddress("src unix"));
header.setDstAddress(readUnixAddress("dst unix"));
} else {
assert af.equals(AddressFamily.AF_UNSPEC);
// do nothing
}
}
/**
* Note that some TLVs are not returned as TLV objects.
* Instead the data is stored in the {@link Header} fields,
* or is used without storing (e.g. checksum).
*/
void readTLVs(Header header) throws IOException {
while (assist.getReadCount() < assist.getHeaderSize()) {
readTlv(header);
}
}
private void readTlv(Header header) throws IOException {
int type = assist.readByte();
int length = assist.readShort();
if (ProxyProtocolSpec.STANDARD_TLV_TYPES.contains(type)) {
readTlvValueToHeader(header, type, length);
} else if (adapters.containsKey(type)) {
TlvAdapter<?> adapter = getAdapter(type);
Tlv result = readTlvValue(adapter, length);
header.addTlv(result);
} else {
Tlv result = readTlvValue(new TlvRawAdapter(type), length);
if (readUnknownTLVs) {
header.addTlv(result);
} else {
// discard the read TLV
}
}
}
private void readTlvValueToHeader(Header header, int type, int length) throws IOException {
// The SSL TLV contains other TLVs, we don't care about this and "flatten" the SSL TLV
// structure by reading the nested TLVs as the top-level TLVs.
// This will prevent the read length validation check from failing.
int correctedLength = type == ProxyProtocolSpec.PP2_TYPE_SSL
? Byte.BYTES + Integer.BYTES
: length;
long countBeforeRead = assist.getReadCount();
doReadTlvValueToHeader(header, type, correctedLength);
checkReadExpected(correctedLength, countBeforeRead, type);
}
// CHECKSTYLE:OFF
private void doReadTlvValueToHeader(Header header, int type, int length) throws IOException {
// CHECKSTYLE:ON
// optimization using switch statement
// it took a lot of time to initialize the map from types to the reading lambdas
switch (type) {
case ProxyProtocolSpec.PP2_TYPE_ALPN:
readAlpn(header, length);
break;
case ProxyProtocolSpec.PP2_TYPE_AUTHORITY:
readAuthority(header, length);
break;
case ProxyProtocolSpec.PP2_TYPE_CRC32C:
readCRC32c(length);
break;
case ProxyProtocolSpec.PP2_TYPE_NOOP:
assist.readBytes(length, "noop");
break;
case ProxyProtocolSpec.PP2_TYPE_SSL:
readSslFlags(header, length);
break;
case ProxyProtocolSpec.PP2_SUBTYPE_SSL_VERSION:
readSslVersion(header, length);
break;
case ProxyProtocolSpec.PP2_SUBTYPE_SSL_CN:
readSslCommonName(header, length);
break;
case ProxyProtocolSpec.PP2_SUBTYPE_SSL_CIPHER:
readSslCipher(header, length);
break;
case ProxyProtocolSpec.PP2_SUBTYPE_SSL_SIG_ALG:
readSslSigAlg(header, length);
break;
case ProxyProtocolSpec.PP2_SUBTYPE_SSL_KEY_ALG:
readSslKeyAlg(header, length);
break;
case ProxyProtocolSpec.PP2_TYPE_NETNS:
readNetNS(header, length);
break;
default:
throw new IllegalStateException("Unrecognized TLV type " + toHex(type));
}
}
Tlv readTlvValue(TlvAdapter<?> adapter, int length) throws IOException {
long countBeforeRead = assist.getReadCount();
Tlv result = adapter.read(assist, length);
checkReadExpected(length, countBeforeRead, adapter.getType());
return result;
}
private void checkReadExpected(int lengthToRead, long countBeforeRead, int type) {
long readCount = assist.getReadCount() - countBeforeRead;
if (readCount != lengthToRead) {
throw new IllegalStateException(
"TLV read for the type " + toHex(type)
+ " was expected to read " + lengthToRead + " bytes but read " + readCount);
}
}
void maybeValidateChecksum() {
if (enforceChecksum) {
if (foundChecksum) {
if (expectedChecksum != assist.getChecksum()) {
throw new InvalidHeaderException(
"Invalid checksum. Parsed " + toHex(expectedChecksum)
+ " but calculated " + toHex(assist.getChecksum()));
}
} else {
throw new InvalidHeaderException("Checksum was not found in the header");
}
}
}
private byte[] readAddress(AddressFamily addressFamily, String label) throws IOException {
return assist.readBytes(addressFamily.getAddressSize(), label);
}
byte[] readUnixAddress(String label) throws IOException {
byte[] b = assist.readBytes(AddressFamily.AF_UNIX.getAddressSize(), label);
int lastIdx = b.length - 1;
while (lastIdx >= 0 && b[lastIdx] == 0) {
lastIdx--;
}
return Arrays.copyOf(b, lastIdx + 1);
}
void readAlpn(Header header, int length) throws IOException {
header.setAlpn(Optional.of(assist.readBytes(length, "alpn")));
}
void readAuthority(Header header, int length) throws IOException {
header.setAuthority(Optional.of(assist.readString(length, "authority")));
}
void readCRC32c(int length) throws IOException {
assert length == 4;
foundChecksum = true;
expectedChecksum = assist.readChecksum();
}
void readSslFlags(Header header, int length) throws IOException {
assert length == Byte.BYTES + Integer.BYTES;
int client = assist.readByte();
int clientVerifiedCert = assist.readInt();
header.setSslFlags(SslFlags.getOptional(client, clientVerifiedCert == 0));
}
void readSslVersion(Header header, int length) throws IOException {
header.setSslVersion(Optional.of(assist.readString(length, "ssl version")));
}
void readSslCommonName(Header header, int length) throws IOException {
header.setSslCommonName(Optional.of(assist.readString(length, "ssl common name")));
}
void readSslCipher(Header header, int length) throws IOException {
header.setSslCipher(Optional.of(assist.readString(length, "ssl cipher")));
}
void readSslSigAlg(Header header, int length) throws IOException {
header.setSslSigAlg(Optional.of(assist.readString(length, "signature algorithm")));
}
void readSslKeyAlg(Header header, int length) throws IOException {
header.setSslKeyAlg(Optional.of(assist.readString(length, "key algorithm")));
}
void readNetNS(Header header, int length) throws IOException {
header.setNetNS(Optional.of(assist.readString(length, "net NS")));
}
/**
* Returns a string representation of the array printing numbers in hexadecimal.
*/
String toString(byte[] a) {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int i = 0; i < a.length; i++) {
sb.append(toHex(Byte.toUnsignedInt(a[i])));
if (i < a.length - 1) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString();
}
public Map<Integer, TlvAdapter<?>> getAdapters() {
return adapters;
}
public void setAdapters(Map<Integer, TlvAdapter<?>> adapters) {
this.adapters.clear();
this.adapters.putAll(adapters);
}
private TlvAdapter<?> getAdapter(int type) {
TlvAdapter<?> adapter = adapters.get(type);
if (type != adapter.getType()) {
throw new IllegalStateException("Adapter " + adapter + " has TLV type "
+ toHex(adapter.getType()) + " however it is registered "
+ "to handle type " + toHex(type));
}
return adapter;
}
public void setReadUnknownTLVs(boolean readUnknownTLVs) {
this.readUnknownTLVs = readUnknownTLVs;
}
public void setEnforceChecksum(boolean enforceChecksum) {
this.enforceChecksum = enforceChecksum;
}
InputAssist getAssist() {
return assist;
}
}
| 9,035 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/Util.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
class Util {
public final static byte[] INT0 = new byte[] {0, 0, 0, 0};
public final static byte[] INT1 = new byte[] {0, 0, 0, 1};
public static String toHex(int b) {
return "0x" + Integer.toHexString(b);
}
/**
* When we do not want to create {@link DataOutputStream} to write out the data.
*/
public static void writeShort(int v, OutputStream out) throws IOException {
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
}
}
| 9,036 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/TlvRaw.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
/**
* Uninterpreted TLV, represents the TLV contents as a byte array.
*/
public class TlvRaw implements Tlv {
private int type;
private byte[] value;
@Override
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public byte[] getValue() {
return value;
}
public void setValue(byte[] value) {
this.value = value;
}
}
| 9,037 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/TlvRawAdapter.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.io.DataOutputStream;
import java.io.IOException;
public class TlvRawAdapter implements TlvAdapter<TlvRaw> {
private final int type;
public TlvRawAdapter(int type) {
this.type = type;
}
@Override
public int getType() {
return type;
}
@Override
public TlvRaw read(InputAssist inputAssist, int length) throws IOException {
TlvRaw tlv = new TlvRaw();
tlv.setType(type);
tlv.setValue(inputAssist.readBytes(length, "TLV " + type));
return tlv;
}
@Override
public void writeValue(Tlv tlv, DataOutputStream out) throws IOException {
out.write(((TlvRaw) tlv).getValue());
}
}
| 9,038 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/NullHasher.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import com.google.common.hash.Funnel;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hasher;
class NullHasher implements Hasher {
private static final HashCode HASH_CODE = HashCode.fromInt(0);
public static final Hasher INSTANCE = new NullHasher();
@Override
public Hasher putByte(byte b) {
return null;
}
@Override
public Hasher putBytes(byte[] bytes) {
return null;
}
public Hasher putBytes(ByteBuffer bytes) {
return null;
}
@Override
public Hasher putBytes(byte[] bytes, int off, int len) {
return null;
}
@Override
public Hasher putShort(short s) {
return null;
}
@Override
public Hasher putInt(int i) {
return null;
}
@Override
public Hasher putLong(long l) {
return null;
}
@Override
public Hasher putFloat(float f) {
return null;
}
@Override
public Hasher putDouble(double d) {
return null;
}
@Override
public Hasher putBoolean(boolean b) {
return null;
}
@Override
public Hasher putChar(char c) {
return null;
}
@Override
public Hasher putUnencodedChars(CharSequence charSequence) {
return null;
}
@Override
public Hasher putString(CharSequence charSequence, Charset charset) {
return null;
}
@Override
public <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
return null;
}
@Override
public HashCode hash() {
return HASH_CODE;
}
} | 9,039 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/ProxyProtocolSpec.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static com.amazonaws.proprot.Util.toHex;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
/**
* The constants describing the Proxy Protocol.
* Whenever possible the names here correspond to the protocol specification.
* See the protocol specification for more information.
*/
public final class ProxyProtocolSpec {
public static final byte[] PREFIX = {0xD, 0xA, 0xD, 0xA, 0x0, 0xD, 0xA, 0x51, 0x55, 0x49, 0x54, 0x0A};
// 13th byte
public static final int PROTOCOL_V2 = 0x2;
public interface Code {
int getCode();
}
public enum Command implements Code {
LOCAL(0x0), PROXY(0x1);
private static Map<Integer, Command> valuesByCode = new HashMap<>();
private final int code;
static {
initCodeEnum(values(), valuesByCode);
}
private Command(int code) {
this.code = code;
}
public static Command valueOf(Integer code, long pos) {
return valueByCode(code, valuesByCode, pos);
}
@Override
public String toString() {
return codeEnumToString(this);
}
@Override
public int getCode() {
return code;
}
}
// 14th byte
public enum AddressFamily implements Code {
AF_UNSPEC(0x0, 0), AF_INET(0x1, 4), AF_INET6(0x2, 16), AF_UNIX(0x3, 108);
private static Map<Integer, AddressFamily> valuesByCode = new HashMap<>();
private final int code;
private final int addressSize;
static {
initCodeEnum(values(), valuesByCode);
}
private AddressFamily(int code, int addressSize) {
this.code = code;
this.addressSize = addressSize;
}
public static AddressFamily valueOf(Integer code, long pos) {
return valueByCode(code, valuesByCode, pos);
}
@Override
public String toString() {
return codeEnumToString(this);
}
@Override
public int getCode() {
return code;
}
/**
* The number of bytes reserved for address of the family.
*/
public int getAddressSize() {
return addressSize;
}
}
public enum TransportProtocol implements Code {
UNSPEC(0x0), STREAM(0x1), DGRAM(0x2);
private static Map<Integer, TransportProtocol> valuesByCode = new HashMap<>();
private final int code;
static {
initCodeEnum(values(), valuesByCode);
}
private TransportProtocol(int code) {
this.code = code;
}
public static TransportProtocol valueOf(Integer code, long pos) {
return valueByCode(code, valuesByCode, pos);
}
@Override
public String toString() {
return codeEnumToString(this);
}
@Override
public int getCode() {
return code;
}
}
/**
* Valid AF/TP combinations.
*/
public static final Set<Integer> VALID_AF_TP_VALUES = ImmutableSet.of(
// UNSPEC
0x00,
// TCP over IPv4
0x11,
// UDP over IPv4
0x12,
// TCP over IPv6
0x21,
// UDP over IPv6
0x22,
// UNIX stream
0x31,
// UNIX datagram
0x32);
// 15th & 16th bytes - address length in bytes
/**
* The number of bytes to add to the value stored in the header size field to calculate the total size of a header.
*/
public static final int ADD_TO_HEADER_SIZE = 16;
// Value Types
public static final int PP2_TYPE_ALPN = 0x1;
public static final int PP2_TYPE_AUTHORITY = 0x2;
public static final int PP2_TYPE_CRC32C = 0x3;
public static final int PP2_TYPE_NOOP = 0x4;
public static final int PP2_TYPE_SSL = 0x20;
public static final int PP2_SUBTYPE_SSL_VERSION = 0x21;
public static final int PP2_SUBTYPE_SSL_CN = 0x22;
public static final int PP2_SUBTYPE_SSL_CIPHER = 0x23;
public static final int PP2_SUBTYPE_SSL_SIG_ALG = 0x24;
public static final int PP2_SUBTYPE_SSL_KEY_ALG = 0x25;
public static final int PP2_TYPE_NETNS = 0x30;
public static final int PP2_CLIENT_SSL = 0x01;
public static final int PP2_CLIENT_CERT_CONN = 0x02;
public static final int PP2_CLIENT_CERT_SESS = 0x04;
public static final Set<Integer> STANDARD_TLV_TYPES = ImmutableSet.of(
ProxyProtocolSpec.PP2_TYPE_ALPN,
ProxyProtocolSpec.PP2_TYPE_AUTHORITY,
ProxyProtocolSpec.PP2_TYPE_CRC32C,
ProxyProtocolSpec.PP2_TYPE_NOOP,
ProxyProtocolSpec.PP2_TYPE_SSL,
ProxyProtocolSpec.PP2_SUBTYPE_SSL_VERSION,
ProxyProtocolSpec.PP2_SUBTYPE_SSL_CN,
ProxyProtocolSpec.PP2_SUBTYPE_SSL_CIPHER,
ProxyProtocolSpec.PP2_SUBTYPE_SSL_SIG_ALG,
ProxyProtocolSpec.PP2_SUBTYPE_SSL_KEY_ALG,
ProxyProtocolSpec.PP2_TYPE_NETNS);
/**
* Packs address family and transport protocol into a single byte as described by the spec.
*/
public static int pack(AddressFamily addressFamily, TransportProtocol transportProtocol) {
return (addressFamily.getCode() << 4) | transportProtocol.getCode();
}
private static <E extends Enum<?> & Code> E valueByCode(
Integer code, Map<Integer, E> valuesByCode, long pos) {
E value = valuesByCode.get(code);
if (value == null) {
Class<?> enumClass = getEnumClass(valuesByCode);
throw new InvalidHeaderException("Unexpected code " + toHex(code) + " for "
+ enumClass.getSimpleName()
+ " at byte " + pos);
} else {
return value;
}
}
/**
* Should be called by the {@link Code} enumerations.
* @param valuesByCode is populated by the method.
*/
static <E extends Enum<?> & Code> void initCodeEnum(
E[] values, Map<Integer, E> valuesByCode) {
assert valuesByCode.isEmpty();
for (E value : values) {
int code = value.getCode();
E oldValue = valuesByCode.put(code, value);
if (oldValue != null) {
Class<?> enumClass = getEnumClass(valuesByCode);
throw new InvalidHeaderException(enumClass.getSimpleName()
+ " has multiple constants with the same code " + toHex(code) + " - "
+ value.toString() + " and " + oldValue.toString());
}
}
}
private static <E extends Enum<?> & Code> String codeEnumToString(E value) {
return value.name() + "(" + value.getCode() + ")";
}
/**
* Class of the map values.
*/
private static <E extends Enum<?> & Code> Class<?> getEnumClass(Map<Integer, E> valuesByCode) {
return valuesByCode.values().iterator().next().getDeclaringClass();
}
}
| 9,040 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/Tlv.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
/**
* The protocol Type-Length-Value record.
* Length is not returned because it describes the length of the original encoded data and is not
* interesting.
*/
public interface Tlv {
int getType();
}
| 9,041 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/TlvSubTypeRawAdapter.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class TlvSubTypeRawAdapter implements TlvAdapter<TlvSubTypeRaw> {
private final int type;
public TlvSubTypeRawAdapter(int type) {
this.type = type;
}
@Override
public int getType() {
return type;
}
@Override
public TlvSubTypeRaw read(InputAssist inputAssist, int length) throws IOException {
if (length < 1) {
throw new InvalidHeaderException("Unexpected length " + length + " of the TLV " + type + ". Should be at least 1.");
}
TlvSubTypeRaw tlv = new TlvSubTypeRaw();
tlv.setType(type);
tlv.setSubType(inputAssist.readByte());
tlv.setValue(inputAssist.readBytes(length - 1, "TLV " + type));
return tlv;
}
@Override
public void writeValue(Tlv tlv, DataOutputStream out) throws IOException {
TlvSubTypeRaw subTypeTlv = (TlvSubTypeRaw) tlv;
out.writeByte(subTypeTlv.getSubType());
out.write(subTypeTlv.getValue());
}
}
| 9,042 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/TlvSubTypeRaw.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
/**
* TlvSubTypeRaw implements a pattern of extending Proxy Protocol with a TLV having a byte-sized subtype.
*/
public class TlvSubTypeRaw implements Tlv {
private int type;
private int subType;
private byte[] value;
@Override
public int getType() {
return type;
}
public int getSubType() {
return subType;
}
public void setType(int type) {
this.type = type;
}
public void setSubType(int subType) {
this.subType = subType;
}
public byte[] getValue() {
return value;
}
public void setValue(byte[] value) {
this.value = value;
}
}
| 9,043 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/CRC32COutputStream.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.primitives.Ints;
/**
* Calculation of the CRC32c checksum is implemented as output stream, so it can be used
* with {@link ByteArrayOutputStream#writeTo(OutputStream)}.
* Assumes the checksum value comes right after the data being checksummed and includes
* the zero value checksum into the checksum calculation.
*/
class CRC32COutputStream extends OutputStream {
private final OutputStream out;
private final Hasher hasher;
public CRC32COutputStream(OutputStream out, boolean calculateChecksum) {
this.hasher = calculateChecksum ? Hashing.crc32c().newHasher() : NullHasher.INSTANCE;
this.out = out;
}
@Override
public void write(int b) throws IOException {
hasher.putByte((byte) b);
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
hasher.putBytes(b, off, len);
out.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
hasher.putBytes(b);
out.write(b);
}
/**
* Writes the checksum calculated on the data so far plus zero checksum value to the
* wrapped output stream.
*/
public void writeChecksum() throws IOException {
hasher.putBytes(Util.INT0);
out.write(Ints.toByteArray(hasher.hash().asInt()));
}
@Override
public void close() throws IOException {
out.close();
}
@Override
public void flush() throws IOException {
out.flush();
}
}
| 9,044 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/ProxyProtocol.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static com.amazonaws.proprot.Util.toHex;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import com.google.common.base.Preconditions;
/**
* Marshalls and unmarshalls the Proxy Protocol header.
* The facade of the library. Is thread-safe once configured.
*/
public class ProxyProtocol {
private boolean readUnknownTLVs = true;
private boolean enforceChecksum = true;
private Optional<Integer> enforcedSize = Optional.empty();
private final Map<Integer, TlvAdapter<?>> adapters = new HashMap<>();
/**
* Reads the protocol header.
* On successful completion the input stream is positioned on the first byte after
* the Proxy Protocol header data. That's the first byte of the original connection.
*/
public Header read(InputStream in) throws IOException, InvalidHeaderException {
Parser parser = new Parser();
parser.setReadUnknownTLVs(isReadUnknownTLVs());
parser.setEnforceChecksum(isEnforceChecksum());
parser.getAdapters().putAll(getAdapters());
return parser.read(in);
}
/**
* Writes the protocol header.
*/
public void write(Header header, OutputStream out) throws IOException, InvalidHeaderException {
Generator generator = new Generator();
generator.setEnforceChecksum(isEnforceChecksum());
generator.setEnforcedSize(getEnforcedSize());
generator.getAdapters().putAll(getAdapters());
generator.write(header, out);
}
/**
* <p>Indicates whether {@link #read(InputStream)} returns the TLVs this object does not have
* adapters for. If <code>true</code> the unrecognized TLVs are returned as {@link TlvRaw}s.
* </p>
* <p>By default returns <code>true</code>.</p>
*/
public boolean isReadUnknownTLVs() {
return readUnknownTLVs;
}
/**
* @see #isReadUnknownTLVs()
*/
public void setReadUnknownTLVs(boolean readUnknownTLVs) {
this.readUnknownTLVs = readUnknownTLVs;
}
/**
* <p>If <code>true</code>, enforce the checksum when reading and writing the protocol header.
* When reading, calculate the checksum and throw {@link InvalidHeaderException} if
* the checksum does not match the checksum specified in the header or the header does not
* include the checksum. Generate the checksum when writing.</p>
*
* <p>If <code>false</code>, the checksum is ignored when reading and is not generated when
* writing.
* </p>
*
* <p>The checksum is not exposed as a TLV object even though according to the protocol
* specification it is stored as a TLV.
* </p>
*
* <p>By default returns <code>true</code>.</p>
*
* <p>Checksum processing approximately doubles processing time of a header.</p>
*
*/
public boolean isEnforceChecksum() {
return enforceChecksum;
}
public void setEnforceChecksum(boolean enforceChecksum) {
this.enforceChecksum = enforceChecksum;
}
/**
* If specified, the class generates Proxy Protocol headers of the specified size if necessary
* padding the header with the {@link ProxyProtocolSpec#PP2_TYPE_NOOP} TLV.
* {@link #write(Header, OutputStream)} throws {@link InvalidHeaderException} if the size of
* the generated header is greater than the specified size. Due to the restriction of the Proxy
* Protocol the exception is also thrown when the generated header is smaller than the
* specified size by 1 or 2 bytes.
* @return by default returns {@link Optional#empty()}
*/
public Optional<Integer> getEnforcedSize() {
return enforcedSize;
}
/**
* @see #getEnforcedSize()
*/
public void setEnforcedSize(Optional<Integer> enforcedSize) {
this.enforcedSize = enforcedSize;
}
/**
* A map of adapter type to adapter.
*/
public Map<Integer, TlvAdapter<?>> getAdapters() {
validateAdapters();
return adapters;
}
public void setAdapters(Collection<TlvAdapter<?>> adapterColl) {
Preconditions.checkNotNull(adapters);
adapters.clear();
for (TlvAdapter<?> adapter : adapterColl) {
TlvAdapter<?> oldAdapter = adapters.put(adapter.getType(), adapter);
if (oldAdapter != null) {
throw new IllegalArgumentException("Found two adapters for the same TLV type "
+ toHex(adapter.getType()) + ": " + oldAdapter + " and " + adapter);
}
}
validateAdapters();
}
private void validateAdapters() {
for (Integer adapterType: adapters.keySet()) {
if (ProxyProtocolSpec.STANDARD_TLV_TYPES.contains(adapterType)) {
throw new IllegalArgumentException(
"The TLV type " + toHex(adapterType) + " is handled by the library "
+ "and can not be processed by the external adapter " + adapters.get(adapterType));
}
}
}
}
| 9,045 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/TlvAdapter.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* Writes and reads a TLV. The implementations must be thread-safe.
*/
public interface TlvAdapter<T extends Tlv> {
/**
* Returns the TLV type handled by the adapter.
*/
int getType();
/**
* The implementors don't need to validate whether all the available data was read.
* The caller will throw an exception when the number of bytes read from the input
* stream does not equal to the "length" parameter.
*
* @param inputAssist contains the input data stream to read the TLV value from and
* the parsing tools.
* @param length the number of bytes belonging to the TLV in the provided input stream.
*/
T read(InputAssist inputAssist, int length) throws IOException, InvalidHeaderException;
/**
* Serializes the value of the provided TLV to the output stream.
*/
void writeValue(Tlv tlv, DataOutputStream out) throws IOException, InvalidHeaderException;
}
| 9,046 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/InputAssist.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import com.google.common.io.CountingInputStream;
/**
* Provides tools helping the ProProt parser and the external TLV adapters to parse Proxy Protocol Header.
* The provided methods reading from the input data stream validate that stream is not read beyond the
* header and that stream does not reach a premature end.
*
* @see ProxyProtocolSpec
*/
public class InputAssist {
private final CountingInputStream cin;
private final CRC32CInputStream in;
private int headerSize;
public InputAssist(InputStream inputStream, boolean enforceChecksum) {
// use MAX_VALUE before we know the actual header size
headerSize = Integer.MAX_VALUE;
cin = new CountingInputStream(inputStream);
in = new CRC32CInputStream(cin, enforceChecksum);
}
/**
* Reads the specified number of bytes to a UTF8 string.
*/
public String readString(int length, String label) throws IOException {
byte[] buf = readBytes(length, label);
return new String(buf, StandardCharsets.UTF_8);
}
public int readByte() throws IOException {
validateHeaderSizeBeforeRead(1);
int readByte = in.read();
checkEOF(readByte);
return readByte;
}
public int readShort() throws IOException {
validateHeaderSizeBeforeRead(2);
int b1 = in.read();
int b2 = in.read();
checkEOF(b1 | b2);
return (b1 << 8) + b2;
}
public int readInt() throws IOException {
validateHeaderSizeBeforeRead(4);
int b1 = in.read();
int b2 = in.read();
int b3 = in.read();
int b4 = in.read();
checkEOF(b1 | b2 | b3 | b4);
return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
}
/**
* Same as {@link #readBytesIntoBuf(int, String)} but reads the data into a newly created array
* which is returned.
*/
public byte[] readBytes(int length, String label) throws IOException, InvalidHeaderException {
// to handle zero-length reads, InputStream.read with zero length does not return 0
if (length == 0) {
return new byte[0];
}
// Experimented with reusing a buffer instead of creating a new one every time,
// but that did not make much difference.
// There was no difference for a header without TLVs and about 13% smaller memory usage
// for the headers with all the known TLVs. That does not seem to be worth the added code
// complexity since this is not a very realistic case.
validateHeaderSizeBeforeRead(length);
byte[] b = new byte[length];
int readCount = in.read(b);
checkEOF(readCount);
if (readCount < length) {
throw new InvalidHeaderException("Premature end of the Proxy Protocol prefix data stream "
+ "when reading " + label + ". "
+ "Read " + readCount + " bytes instead of expected " + length + ".");
}
return b;
}
/**
* Reads the protocol header size from the input stream.
*/
void readHeaderSize() throws IOException {
headerSize = readShort() + ProxyProtocolSpec.ADD_TO_HEADER_SIZE;
}
/**
* Throws the EOF exception if the read result is -1.
*/
private void checkEOF(int readResult) {
if (readResult == -1) {
throw throwEOF(cin.getCount());
}
}
private InvalidHeaderException throwEOF(long readCount) {
throw new InvalidHeaderException(
"Premature end of the Proxy Protocol prefix data stream after "
+ readCount + " bytes");
}
void validateHeaderSizeBeforeRead(int readSize) {
long countBeforeRead = getReadCount();
if (countBeforeRead + readSize > headerSize) {
throw new InvalidHeaderException(
"Proxy Protocol header is longer than its declared size " + headerSize + ".");
}
}
/**
* The number of bytes read from the provided stream so far.
*/
public long getReadCount() {
return cin.getCount();
}
/**
* The position in the stream, 1 less than {@link #getReadCount()}.
*/
public long getReadPos() {
return getReadCount() - 1;
}
int readChecksum() throws IOException {
return in.readChecksum();
}
int getChecksum() {
return in.getChecksum();
}
public InputStream getDataInputStream() {
return in;
}
void setHeaderSize(int headerSize) {
this.headerSize = headerSize;
}
int getHeaderSize() {
return headerSize;
}
}
| 9,047 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/CRC32CInputStream.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.primitives.Ints;
/**
* Calculates the stream checksum while allowing to read the expected checksum value from
* the stream interpreting it as zero for the purposes of checksum calculation.
*/
class CRC32CInputStream extends InputStream {
// XXX with the move to Java9 switch to http://download.java.net/java/jdk9/docs/api/java/util/zip/CRC32C.html?
private final Hasher hasher;
private final InputStream in;
public CRC32CInputStream(InputStream in, boolean calculateChecksum) {
this.in = in;
this.hasher = calculateChecksum ? Hashing.crc32c().newHasher() : NullHasher.INSTANCE;
}
@Override
public int read() throws IOException {
int b = in.read();
if (b != -1) {
hasher.putByte((byte) b);
}
return b;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int result = in.read(b, off, len);
if (result != -1) {
hasher.putBytes(b, off, result);
}
return result;
}
public int readChecksum() throws IOException {
int b1 = in.read();
int b2 = in.read();
int b3 = in.read();
int b4 = in.read();
if ((b1 | b2 | b3 | b4) < 0) {
throw new EOFException();
}
hasher.putBytes(Util.INT0);
return Ints.fromBytes((byte) b1, (byte) b2, (byte) b3, (byte) b4);
}
public int getChecksum() {
return hasher.hash().asInt();
}
}
| 9,048 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/InvalidHeaderException.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
/**
* Indicates a problem with parsing or generating the Proxy Protocol header.
*/
public class InvalidHeaderException extends RuntimeException {
public InvalidHeaderException(String message) {
super(message);
}
}
| 9,049 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/Header.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static com.amazonaws.proprot.Util.toHex;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import com.amazonaws.proprot.ProxyProtocolSpec.AddressFamily;
import com.amazonaws.proprot.ProxyProtocolSpec.Command;
import com.amazonaws.proprot.ProxyProtocolSpec.TransportProtocol;
import com.google.common.io.BaseEncoding;
/**
* The Proxy Protocol header.
*/
public class Header {
private final static byte[] BYTE_A_0 = new byte[0];
private Command command = Command.LOCAL;
private AddressFamily addressFamily = AddressFamily.AF_UNSPEC;
private TransportProtocol transportProtocol = TransportProtocol.UNSPEC;
private byte[] srcAddress = BYTE_A_0;
private byte[] dstAddress = BYTE_A_0;
private int srcPort;
private int dstPort;
// data of the predefined TLVs
private Optional<byte[]> alpn = Optional.empty();
private Optional<String> authority = Optional.empty();
private Optional<SslFlags> sslFlags = Optional.empty();
private Optional<String> sslVersion = Optional.empty();
private Optional<String> sslCommonName = Optional.empty();
private Optional<String> sslCipher = Optional.empty();
private Optional<String> sslSigAlg = Optional.empty();
private Optional<String> sslKeyAlg = Optional.empty();
private Optional<String> netNS = Optional.empty();
private List<Tlv> tlvs = Collections.emptyList();
/**
* Checks the header consistency.
* This method is called after parsing header and before writing the header information to the output stream.
* @throws InvalidHeaderException if inconsistencies are found.
*/
public void validate() throws InvalidHeaderException {
verifyAddressFamilyTransportProtocolCombination();
verifyAddressSize(srcAddress);
verifyAddressSize(dstAddress);
if (!getSslFlags().isPresent()) {
assertNoSslContainedTlv(sslVersion, "SSL version");
assertNoSslContainedTlv(sslCommonName, "SSL Common Name (CN)");
assertNoSslContainedTlv(sslCipher, "SSL Cipher");
assertNoSslContainedTlv(sslSigAlg, "SSL Certificate Signature Algorithm");
assertNoSslContainedTlv(sslKeyAlg, "SSL Certificate Key Algorithm");
}
}
private void verifyAddressFamilyTransportProtocolCombination() {
int value = ProxyProtocolSpec.pack(addressFamily, transportProtocol);
if (!ProxyProtocolSpec.VALID_AF_TP_VALUES.contains(value)) {
throw new InvalidHeaderException("Unexpected address family/transport protocol value "
+ toHex(value) + " (" + addressFamily + "/" + transportProtocol + ")");
}
}
// CHECKSTYLE:OFF
private void verifyAddressSize(byte[] address) {
// CHECKSTYLE:ON
int addressLength = address.length;
switch (addressFamily) {
case AF_UNSPEC:
case AF_INET:
case AF_INET6:
if (addressLength != addressFamily.getAddressSize()) {
throw new InvalidHeaderException("For the address family " + addressFamily +
" expected address size " + addressFamily.getAddressSize() + " but got "
+ addressLength + " for the address "
+ BaseEncoding.base16().lowerCase().encode(address));
}
break;
case AF_UNIX:
// Unix address can be smaller than the reserved space
if (addressLength > addressFamily.getAddressSize()
|| addressLength == 0) {
throw new InvalidHeaderException("Invalid size " + addressLength +
" of the Unix address "
+ BaseEncoding.base16().lowerCase().encode(address));
}
break;
}
}
private void assertNoSslContainedTlv(Optional<?> value, String label) {
if (value.isPresent()) {
throw new InvalidHeaderException(
label + " TLV must be part of the container SSL TLV");
}
}
/**
* @return Never <code>null</code>. By default {@link Command#PROXY}.
*/
public Command getCommand() {
return command;
}
public void setCommand(Command command) {
this.command = command;
}
public AddressFamily getAddressFamily() {
return addressFamily;
}
public void setAddressFamily(AddressFamily addressFamily) {
this.addressFamily = addressFamily;
}
public TransportProtocol getTransportProtocol() {
return transportProtocol;
}
public void setTransportProtocol(TransportProtocol transportProtocol) {
this.transportProtocol = transportProtocol;
}
/**
* Source address represented as a byte array. Default value is
* <code>byte[0]</code>The actual format depends on the value of the
* {@link #getAddressFamily()} field. Address is not specified and is equal to the default
* value for {@link AddressFamily#AF_UNSPEC}.
* For {@link AddressFamily#AF_INET} and {@link AddressFamily#AF_INET6} addresses you can
* use {@link InetAddress#getByAddress(byte[])}.
* {@link AddressFamily#AF_UNIX} address is a sequence of bytes with the trailing zero bytes
* truncated. Willy Tarreau, the author of the Proxy Protocol v2:
* <blockquote>
* UNIX addresses should be seen as byte streams, they are usually
* 108 bytes and stop at the first zero <i>if there is one</i>.
* On Linux we also support abstract namespace sockets which basically are
* Unix socket addresses starting with a zero, and the remaining 107 bytes
* become an internal address. This way there's no need for FS access. And
* thanks to this they're also supported by default without doing anything.
* </blockquote>
*
*/
public byte[] getSrcAddress() {
return srcAddress;
}
public void setSrcAddress(byte[] srcAddress) {
this.srcAddress = srcAddress;
}
/**
* @see #getSrcAddress()
*/
public byte[] getDstAddress() {
return dstAddress;
}
public void setDstAddress(byte[] dstAddress) {
this.dstAddress = dstAddress;
}
/**
* Is specified when {@link #getTransportProtocol()} is {@link TransportProtocol#STREAM}
* or {@link TransportProtocol#DGRAM}.
* Default value is zero.
*/
public int getSrcPort() {
return srcPort;
}
public void setSrcPort(int srcPort) {
this.srcPort = srcPort;
}
/**
* Is specified when {@link #getTransportProtocol()} is {@link TransportProtocol#STREAM}
* or {@link TransportProtocol#DGRAM}.
* Default value is zero.
*/
public int getDstPort() {
return dstPort;
}
public void setDstPort(int dstPort) {
this.dstPort = dstPort;
}
/**
* When {@link #getCommand()} is {@link Command#LOCAL}, the specification requires parser to process
* address information and then ignore it. In that case, reset {@link #getSrcAddress()}, {@link #getDstAddress()},
* {@link #getSrcPort()}, {@link #getDstPort()}, {@link #getAddressFamily()}, and {@link #getTransportProtocol()}.
* This method is called after parsing header for address information.
*/
void correctAddressesForLocalCommand() {
if (command.equals(Command.LOCAL)) {
this.setSrcAddress(BYTE_A_0);
this.setDstAddress(BYTE_A_0);
this.setSrcPort(0);
this.setDstPort(0);
this.setAddressFamily(AddressFamily.AF_UNSPEC);
this.setTransportProtocol(TransportProtocol.UNSPEC);
}
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_TYPE_ALPN} TLV.
*/
public Optional<byte[]> getAlpn() {
return alpn;
}
public void setAlpn(Optional<byte[]> alpn) {
this.alpn = alpn;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_TYPE_AUTHORITY} TLV.
*/
public Optional<String> getAuthority() {
return authority;
}
public void setAuthority(Optional<String> authority) {
this.authority = authority;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_TYPE_SSL} TLV without the nested TLVs.
*/
public Optional<SslFlags> getSslFlags() {
return sslFlags;
}
public void setSslFlags(Optional<SslFlags> sslFlags) {
this.sslFlags = sslFlags;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_SUBTYPE_SSL_VERSION} TLV.
*/
public Optional<String> getSslVersion() {
return sslVersion;
}
public void setSslVersion(Optional<String> sslVersion) {
this.sslVersion = sslVersion;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_SUBTYPE_SSL_CN} TLV.
*/
public Optional<String> getSslCommonName() {
return sslCommonName;
}
public void setSslCommonName(Optional<String> sslCommonName) {
this.sslCommonName = sslCommonName;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_SUBTYPE_SSL_CIPHER} TLV.
*/
public Optional<String> getSslCipher() {
return sslCipher;
}
public void setSslCipher(Optional<String> sslCipher) {
this.sslCipher = sslCipher;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_SUBTYPE_SSL_SIG_ALG} TLV.
*/
public Optional<String> getSslSigAlg() {
return sslSigAlg;
}
public void setSslSigAlg(Optional<String> sslSigAlg) {
this.sslSigAlg = sslSigAlg;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_SUBTYPE_SSL_KEY_ALG} TLV.
*/
public Optional<String> getSslKeyAlg() {
return sslKeyAlg;
}
public void setSslKeyAlg(Optional<String> sslKeyAlg) {
this.sslKeyAlg = sslKeyAlg;
}
/**
* The contents of the {@link ProxyProtocolSpec#PP2_TYPE_NETNS} TLV.
*/
public Optional<String> getNetNS() {
return netNS;
}
public void setNetNS(Optional<String> netNS) {
this.netNS = netNS;
}
/**
* The TLVs of the types not known to the library.
* Immutable.
*/
public List<Tlv> getTlvs() {
return tlvs;
}
public void addTlv(Tlv tlv) {
int tlvType = tlv.getType();
if (ProxyProtocolSpec.STANDARD_TLV_TYPES.contains(tlvType)) {
throw new InvalidHeaderException(
"The TLV type " + toHex(tlvType) + " defined in the Proxy Protocol "
+ "specification should not be exposed as a TLV. "
+ "Use Header class fields instead");
}
if (tlvs.isEmpty()) {
// assume the number of the custom TLVs is small
tlvs = new ArrayList<>(4);
}
tlvs.add(tlv);
}
/**
* Implements the Flightweight pattern.
*/
public static class SslFlags {
/**
* The number of bits used in the flag field.
*/
private static final int BIT_COUNT = 3;
private static final int BIT_MASK = (1 << BIT_COUNT) - 1;
private static final int VERIFIED_FLAG = 1 << BIT_COUNT;
/**
* The count of all the flags tracked by the objects of this class.
*/
private static final int FLAG_COUNT = BIT_COUNT + 1;
private final boolean clientConnectedWithSsl;
private final boolean clientProvidedCertDuringConnection;
private final boolean clientProvidedCertDuringSession;
private final boolean clientVerifiedCert;
private final int client;
private SslFlags(boolean clientConnectedWithSsl, boolean clientProvidedCertDuringConnection,
boolean clientProvidedCertDuringSession, boolean clientVerifiedCert) {
this.clientConnectedWithSsl = clientConnectedWithSsl;
this.clientProvidedCertDuringConnection = clientProvidedCertDuringConnection;
this.clientProvidedCertDuringSession = clientProvidedCertDuringSession;
this.client = calculateClient(clientConnectedWithSsl,
clientProvidedCertDuringConnection, clientProvidedCertDuringSession);
this.clientVerifiedCert = clientVerifiedCert;
}
/**
* The value for the "client" field.
*/
public int getClient() {
return client;
}
public boolean isClientConnectedWithSsl() {
return clientConnectedWithSsl;
}
public boolean isClientProvidedCertDuringConnection() {
return clientProvidedCertDuringConnection;
}
public boolean isClientProvidedCertDuringSession() {
return clientProvidedCertDuringSession;
}
public boolean isClientVerifiedCert() {
return clientVerifiedCert;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof SslFlags) {
SslFlags other = (SslFlags) o;
return client == other.client
&& clientVerifiedCert == other.clientVerifiedCert;
} else {
return false;
}
}
@Override
public int hashCode() {
return getValueIdx(client, clientVerifiedCert);
}
public static Optional<SslFlags> getOptional(int client, boolean clientVerifiedCert) {
return Container.VALUES[getValueIdx(client, clientVerifiedCert)];
}
public static Optional<SslFlags> getOptional(boolean clientConnectedWithSsl,
boolean clientProvidedCertDuringConnection, boolean clientProvidedCertDuringSession,
boolean clientVerifiedCert) {
int client = calculateClient(clientConnectedWithSsl, clientProvidedCertDuringConnection,
clientProvidedCertDuringSession);
return getOptional(client, clientVerifiedCert);
}
private static int getValueIdx(int client, boolean clientVerifiedCert) {
return (client & BIT_MASK) | (clientVerifiedCert ? VERIFIED_FLAG : 0);
}
private static int calculateClient(boolean clientConnectedWithSsl,
boolean clientProvidedCertDuringConnection, boolean clientProvidedCertDuringSession) {
int value = 0;
if (clientConnectedWithSsl) {
value |= ProxyProtocolSpec.PP2_CLIENT_SSL;
}
if (clientProvidedCertDuringConnection) {
value |= ProxyProtocolSpec.PP2_CLIENT_CERT_CONN;
}
if (clientProvidedCertDuringSession) {
value |= ProxyProtocolSpec.PP2_CLIENT_CERT_SESS;
}
return value;
}
/**
* Lazy load, otherwise SslFlags creation causes infinite loop.
*/
private static class Container {
/**
* All the class values, is used to optimize memory allocation when parsing.
*/
@SuppressWarnings("unchecked")
private static final Optional<SslFlags>[] VALUES = new Optional[1 << FLAG_COUNT];
static {
final boolean[] bools = new boolean[] {false, true};
int i = 0;
for (boolean f1 : bools) {
for (boolean f2 : bools) {
for (boolean f3 : bools) {
for (boolean f4 : bools) {
VALUES[i] = Optional.of(new SslFlags(f1, f2, f3, f4));
i++;
}
}
}
}
assert i == VALUES.length;
SslFlags lastValue = VALUES[VALUES.length - 1].get();
assert lastValue.isClientConnectedWithSsl();
assert lastValue.isClientProvidedCertDuringConnection();
assert lastValue.isClientProvidedCertDuringSession();
assert lastValue.isClientVerifiedCert();
assert lastValue == getOptional(0xFF, true).get();
}
}
}
}
| 9,050 |
0 | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws | Create_ds/elastic-load-balancing-tools/proprot/src/com/amazonaws/proprot/Generator.java | /* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under the License.
*/
package com.amazonaws.proprot;
import static com.amazonaws.proprot.Util.toHex;
import static com.amazonaws.proprot.Util.writeShort;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import com.amazonaws.proprot.Header.SslFlags;
import com.amazonaws.proprot.ProxyProtocolSpec.AddressFamily;
/**
* Generates Proxy Protocol v2 header.
* Is not thread-safe.
* @see ProxyProtocol#read(java.io.InputStream)
*/
class Generator {
private static final int SIZE_OF_HEADER_SIZE_FIELD = Short.BYTES;
private final Map<Integer, TlvAdapter<? extends Tlv>> adapters = new HashMap<>();
/**
* Is used to convert a value to byte[] before writing it out in order to calculate
* its length because length is written before the value.
*/
private final ByteArrayOutputStream valueBuf = new ByteArrayOutputStream(30);
private final DataOutputStream valueOut = new DataOutputStream(valueBuf);
private Header header;
private boolean enforceChecksum;
private Optional<Integer> enforcedSize = Optional.empty();
public void write(Header header, OutputStream outputStream) throws IOException {
this.header = header;
header.validate();
// code is ugly because we need to conditionally calculate the checksum,
// backtrack to include the size of the header and the size of the PP2_TYPE_SSL TLV
CRC32COutputStream out = new CRC32COutputStream(outputStream, enforceChecksum);
ByteArrayOutputStream mainBuf = new ByteArrayOutputStream(
header.getAddressFamily().getAddressSize() * 2 + 100);
// the fixed-size part of the header before the header size field
writeFixedHeader(mainBuf);
int writtenSize = mainBuf.size();
mainBuf.writeTo(out);
mainBuf.reset();
// the size field should go after the fixed size part
// generate the rest of the header in memory, so we can calculate the size
writeAddresses(mainBuf);
writeTlvs(mainBuf);
maybeWriteSsl(header, mainBuf);
writtenSize += mainBuf.size();
maybePadHeader(writtenSize + SIZE_OF_HEADER_SIZE_FIELD + getCrcTlvSize(), mainBuf);
if (enforceChecksum) {
writeTlvStart(ProxyProtocolSpec.PP2_TYPE_CRC32C, getCrcValueSize(), mainBuf);
}
// flush the size field
int headerSize = getHeaderSize(mainBuf);
writeShort(headerSize, out);
// flush mainBuf
mainBuf.writeTo(out);
// generate and write the checksum
if (enforceChecksum) {
out.writeChecksum();
}
// keep static code analysis happy
out.close();
mainBuf.close();
}
/**
* Writes the fixed part of the header up to but not including the header size field.
*/
private void writeFixedHeader(ByteArrayOutputStream out) throws IOException {
out.write(ProxyProtocolSpec.PREFIX);
assert out.size() == 12;
writeCommand(out);
assert out.size() == 13;
writeAddressFamilyAndTransportProtocol(out);
assert out.size() == 14;
}
private void writeCommand(OutputStream out) throws IOException {
out.write(0x20 | header.getCommand().getCode());
}
private void writeAddresses(OutputStream out) throws IOException {
AddressFamily af = header.getAddressFamily();
if (af.equals(AddressFamily.AF_INET) ||
af.equals(AddressFamily.AF_INET6)) {
out.write(header.getSrcAddress());
out.write(header.getDstAddress());
writeShort(header.getSrcPort(), out);
writeShort(header.getDstPort(), out);
} else if (af.equals(AddressFamily.AF_UNIX)) {
int addressSize = AddressFamily.AF_UNIX.getAddressSize();
out.write(Arrays.copyOf(header.getSrcAddress(), addressSize));
out.write(Arrays.copyOf(header.getDstAddress(), addressSize));
} else {
assert af.equals(AddressFamily.AF_UNSPEC);
}
}
private void writeTlvs(OutputStream out) throws IOException {
maybeWriteByteTVL(ProxyProtocolSpec.PP2_TYPE_ALPN, header.getAlpn(), out);
maybeWriteStrTVL(ProxyProtocolSpec.PP2_TYPE_AUTHORITY, header.getAuthority(), out);
maybeWriteStrTVL(ProxyProtocolSpec.PP2_TYPE_NETNS, header.getNetNS(), out);
for (Tlv tlv : header.getTlvs()) {
assert valueBuf.size() == 0;
TlvAdapter<? extends Tlv> adapter = getAdapter(tlv);
adapter.writeValue(tlv, valueOut);
writeTLVFromValueBuf(tlv.getType(), out);
}
}
private void maybeWriteSsl(Header header, OutputStream out) throws IOException {
if (header.getSslFlags().isPresent()) {
SslFlags flags = header.getSslFlags().get();
ByteArrayOutputStream sslBuf = writeSslTlvs();
// length
int size = sslBuf.size() + Byte.BYTES + Integer.BYTES;
writeTlvStart(ProxyProtocolSpec.PP2_TYPE_SSL, size, out);
// client
out.write(flags.getClient());
// verify
out.write(flags.isClientVerifiedCert() ? Util.INT0 : Util.INT1);
sslBuf.writeTo(out);
// to keep static code analysis happy
sslBuf.close();
}
}
private ByteArrayOutputStream writeSslTlvs() throws IOException {
ByteArrayOutputStream sslBuf = new ByteArrayOutputStream(20);
maybeWriteStrTVL(ProxyProtocolSpec.PP2_SUBTYPE_SSL_VERSION, header.getSslVersion(), sslBuf);
maybeWriteStrTVL(ProxyProtocolSpec.PP2_SUBTYPE_SSL_CN, header.getSslCommonName(), sslBuf);
maybeWriteStrTVL(ProxyProtocolSpec.PP2_SUBTYPE_SSL_CIPHER, header.getSslCipher(), sslBuf);
maybeWriteStrTVL(ProxyProtocolSpec.PP2_SUBTYPE_SSL_SIG_ALG, header.getSslSigAlg(), sslBuf);
maybeWriteStrTVL(ProxyProtocolSpec.PP2_SUBTYPE_SSL_KEY_ALG, header.getSslKeyAlg(), sslBuf);
return sslBuf;
}
/**
* Should be called last or before last checksum TLV.
*/
void maybePadHeader(int knownSize, OutputStream out) throws IOException {
if (!enforcedSize.isPresent()) {
return;
}
int targetSize = enforcedSize.get();
if (knownSize == targetSize) {
// nothing to do
return;
}
if (knownSize > targetSize) {
throw new InvalidHeaderException("Header size " + knownSize
+ " can not be larger than the specified limit " + targetSize);
}
int remainingSize = targetSize - knownSize;
if (remainingSize == 1 || remainingSize == 2) {
throw new InvalidHeaderException("Due to Proxy Protocol limitation can not pad header "
+ "of size " + knownSize + " by 1 or 2 bytes to the specified limit "
+ targetSize);
} else {
int padSize = remainingSize - getTlvStartSize();
padHeader(padSize, out);
}
}
private void padHeader(int padSize, OutputStream out) throws IOException {
for (int i = 0; i < padSize; i++) {
valueBuf.write(0);
}
writeTLVFromValueBuf(ProxyProtocolSpec.PP2_TYPE_NOOP, out);
}
private void maybeWriteStrTVL(int type, Optional<String> data, OutputStream out)
throws IOException {
if (data.isPresent()) {
assert valueBuf.size() == 0;
valueBuf.write(data.get().getBytes(StandardCharsets.UTF_8));
writeTLVFromValueBuf(type, out);
}
}
private void maybeWriteByteTVL(int type, Optional<byte[]> data, OutputStream out)
throws IOException {
if (data.isPresent()) {
assert valueBuf.size() == 0;
valueBuf.write(data.get());
writeTLVFromValueBuf(type, out);
}
}
private void writeTLVFromValueBuf(int type, OutputStream out) throws IOException {
writeTlvStart(type, valueBuf.size(), out);
valueBuf.writeTo(out);
valueBuf.reset();
}
private void writeTlvStart(int type, int size, OutputStream out) throws IOException {
out.write(type);
writeShort(size, out);
}
TlvAdapter<? extends Tlv> getAdapter(Tlv tlv) {
int type = tlv.getType();
if (tlv instanceof TlvRaw) {
return new TlvRawAdapter(type);
} else if (adapters.containsKey(type)) {
return adapters.get(type);
} else {
throw new IllegalStateException(
"Unable to find adapter for " + tlv + " of type " + toHex(type));
}
}
private void writeAddressFamilyAndTransportProtocol(OutputStream out) throws IOException {
out.write(ProxyProtocolSpec.pack(
header.getAddressFamily(), header.getTransportProtocol()));
}
private int getHeaderSize(ByteArrayOutputStream mainBuf) {
if (enforceChecksum) {
// only CRC value is left not in mainBuf
return mainBuf.size() + getCrcValueSize();
} else {
return mainBuf.size();
}
}
private int getCrcValueSize() {
return Integer.BYTES;
}
private int getCrcTlvSize() {
if (enforceChecksum) {
return getTlvStartSize() + getCrcValueSize();
} else {
return 0;
}
}
private int getTlvStartSize() {
return Byte.BYTES + Short.BYTES;
}
public Map<Integer, TlvAdapter<? extends Tlv>> getAdapters() {
return adapters;
}
public void setEnforceChecksum(boolean enforceChecksum) {
this.enforceChecksum = enforceChecksum;
}
public void setEnforcedSize(Optional<Integer> enforcedSize) {
this.enforcedSize = enforcedSize;
}
}
| 9,051 |
0 | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control/controllers/PIDControllerTest.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import com.google.common.util.concurrent.AtomicDouble;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PIDControllerTest {
@Test
public void shouldComputeSignal() {
PIDController controller = new PIDController(1.0, 1.0, 1.0, 1.0, new AtomicDouble(1.0), 0.9);
double signal = controller.processStep(10.0);
assertEquals(30, signal, 1e-10);
signal = controller.processStep(10.0);
// p: 10, i: 19, d: 0
assertEquals(29, signal, 1e-10);
signal = controller.processStep(20.0);
// p: 20, i: 27.1, d: 10
assertEquals(67.1, signal, 1e-10);
}
}
| 9,052 |
0 | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control/controllers/IntegratorTest.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IntegratorTest {
@Test
public void shouldIntegrateInputs() {
Integrator integrator = new Integrator(10, -100, 100, 1.0);
double output = integrator.processStep(10.0);
assertEquals(20.0, output, 1e-10);
output = integrator.processStep(20.0);
assertEquals(40.0, output, 1e-10);
integrator.setSum(-10.0);
output = integrator.processStep(-10.0);
assertEquals(-20.0, output, 1e-10);
}
@Test
public void shouldSupportDecay() {
Integrator integrator = new Integrator(10, -100, 100, 0.9);
double output = integrator.processStep(10.0);
assertEquals(20.0, output, 1e-10);
output = integrator.processStep(20.0);
assertEquals(38.0, output, 1e-10);
output = integrator.processStep(30.0);
assertEquals(64.2, output, 1e-10);
}
@Test
public void shouldSupportMinMax() {
Integrator integrator = new Integrator(10, -100, 100, 1.0);
double output = integrator.processStep(200.0);
assertEquals(100.0, output, 1e-10);
output = integrator.processStep(-400.0);
assertEquals(-100.0, output, 1e-10);
}
}
| 9,053 |
0 | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control/clutch/ExperimentalControlLoopTest.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.control.IActuator;
import io.vavr.Tuple;
import org.junit.Test;
import rx.Observable;
import rx.subjects.PublishSubject;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
public class ExperimentalControlLoopTest {
@Test
public void shouldCallActuator() throws Exception {
ClutchConfiguration config = ClutchConfiguration.builder()
.metric(Clutch.Metric.RPS)
.setPoint(100.0)
.kp(1.0)
.ki(0)
.kd(0)
.minSize(1)
.maxSize(1000)
.rope(Tuple.of(0.0, 0.0))
.cooldownInterval(0)
.cooldownUnits(TimeUnit.SECONDS)
.build();
TestActuator actuator = new TestActuator();
CountDownLatch latch = actuator.createLatch();
ExperimentalControlLoop controlLoop = new ExperimentalControlLoop(config, actuator, new AtomicLong(100),
new AtomicDouble(1.0), Observable.timer(10, TimeUnit.MINUTES), Observable.just(100),
new ExperimentalControlLoop.DefaultRpsMetricComputer(),
new ExperimentalControlLoop.DefaultScaleComputer());
PublishSubject<Event> publisher = PublishSubject.create();
controlLoop.call(publisher).subscribe();
publisher.onNext(new Event(Clutch.Metric.RPS, 110));
latch.await();
assertEquals(110, actuator.lastValue, 1e-10);
latch = actuator.createLatch();
publisher.onNext(new Event(Clutch.Metric.RPS, 120));
latch.await();
assertEquals(130, actuator.lastValue, 1e-10);
latch = actuator.createLatch();
publisher.onNext(new Event(Clutch.Metric.RPS, 90));
latch.await();
assertEquals(120, actuator.lastValue, 1e-10);
latch = actuator.createLatch();
publisher.onNext(new Event(Clutch.Metric.RPS, 0));
latch.await();
assertEquals(20, actuator.lastValue, 1e-10);
latch = actuator.createLatch();
publisher.onNext(new Event(Clutch.Metric.RPS, 0));
latch.await();
assertEquals(1, actuator.lastValue, 1e-10);
latch = actuator.createLatch();
publisher.onNext(new Event(Clutch.Metric.RPS, 2000));
latch.await();
assertEquals(1000, actuator.lastValue, 1e-10);
}
@Test
public void testLagDerivativeInMetricComputer() throws Exception {
ClutchConfiguration config = ClutchConfiguration.builder()
.metric(Clutch.Metric.RPS)
.setPoint(100.0)
.kp(1.0)
.ki(0)
.kd(0)
.minSize(1)
.maxSize(1000)
.rope(Tuple.of(0.0, 0.0))
.cooldownInterval(0)
.cooldownUnits(TimeUnit.SECONDS)
.build();
TestActuator actuator = new TestActuator();
CountDownLatch latch = actuator.createLatch();
ExperimentalControlLoop controlLoop = new ExperimentalControlLoop(config, actuator, new AtomicLong(100),
new AtomicDouble(1.0), Observable.timer(10, TimeUnit.MINUTES), Observable.just(100),
new ExperimentalControlLoop.DefaultRpsMetricComputer(),
new ExperimentalControlLoop.DefaultScaleComputer());
PublishSubject<Event> publisher = PublishSubject.create();
controlLoop.call(publisher).subscribe();
publisher.onNext(new Event(Clutch.Metric.RPS, 110));
latch.await();
assertEquals(110, actuator.lastValue, 1e-10);
latch = actuator.createLatch();
publisher.onNext(new Event(Clutch.Metric.LAG, 20));
publisher.onNext(new Event(Clutch.Metric.RPS, 110));
latch.await();
assertEquals(140, actuator.lastValue, 1e-10);
latch = actuator.createLatch();
publisher.onNext(new Event(Clutch.Metric.LAG, 10));
publisher.onNext(new Event(Clutch.Metric.RPS, 100));
latch.await();
assertEquals(130, actuator.lastValue, 1e-10);
}
@Test
public void shouldIntegrateErrorDuringCoolDown() throws Exception {
ClutchConfiguration config = ClutchConfiguration.builder()
.metric(Clutch.Metric.RPS)
.setPoint(100.0)
.kp(1.0)
.ki(0)
.kd(0)
.minSize(1)
.maxSize(1000)
.rope(Tuple.of(0.0, 0.0))
.cooldownInterval(10)
.cooldownUnits(TimeUnit.MINUTES)
.build();
TestActuator actuator = new TestActuator();
CountDownLatch latch = actuator.createLatch();
ExperimentalControlLoop controlLoop = new ExperimentalControlLoop(config, actuator, new AtomicLong(100),
new AtomicDouble(1.0), Observable.timer(10, TimeUnit.MINUTES), Observable.just(100),
new ExperimentalControlLoop.DefaultRpsMetricComputer(),
new ExperimentalControlLoop.DefaultScaleComputer());
PublishSubject<Event> publisher = PublishSubject.create();
controlLoop.call(publisher).subscribe();
publisher.onNext(new Event(Clutch.Metric.RPS, 110));
assertEquals(1, latch.getCount());
publisher.onNext(new Event(Clutch.Metric.RPS, 120));
assertEquals(1, latch.getCount());
controlLoop.setCooldownMillis(0);
publisher.onNext(new Event(Clutch.Metric.RPS, 90));
latch.await();
assertEquals(120, actuator.lastValue, 1e-10);
}
@Test
public void shouldIntegrateErrorWithDecay() throws Exception {
ClutchConfiguration config = ClutchConfiguration.builder()
.metric(Clutch.Metric.RPS)
.setPoint(100.0)
.kp(1.0)
.ki(0)
.kd(0)
.integralDecay(0.9)
.minSize(1)
.maxSize(1000)
.rope(Tuple.of(0.0, 0.0))
.cooldownInterval(10)
.cooldownUnits(TimeUnit.MINUTES)
.build();
TestActuator actuator = new TestActuator();
CountDownLatch latch = actuator.createLatch();
ExperimentalControlLoop controlLoop = new ExperimentalControlLoop(config, actuator, new AtomicLong(100),
new AtomicDouble(1.0), Observable.timer(10, TimeUnit.MINUTES), Observable.just(100),
new ExperimentalControlLoop.DefaultRpsMetricComputer(),
new ExperimentalControlLoop.DefaultScaleComputer());
PublishSubject<Event> publisher = PublishSubject.create();
controlLoop.call(publisher).subscribe();
publisher.onNext(new Event(Clutch.Metric.RPS, 110));
assertEquals(1, latch.getCount());
publisher.onNext(new Event(Clutch.Metric.RPS, 120));
assertEquals(1, latch.getCount());
controlLoop.setCooldownMillis(0);
publisher.onNext(new Event(Clutch.Metric.RPS, 90));
latch.await();
assertEquals(116.1, actuator.lastValue, 1e-10);
}
public static class TestActuator extends IActuator {
private double lastValue;
private CountDownLatch latch;
public CountDownLatch createLatch() {
this.latch = new CountDownLatch(1);
return this.latch;
}
@Override
protected Double processStep(Double value) {
this.lastValue = value;
latch.countDown();
return value;
}
}
}
| 9,054 |
0 | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control/clutch/ClutchConfiguratorTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.netflix.control.clutch.metrics.IClutchMetricsRegistry;
import com.yahoo.sketches.quantiles.UpdateDoublesSketch;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.assertj.core.data.Offset;
import org.junit.Test;
import rx.Observable;
import rx.observers.TestSubscriber;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ClutchConfiguratorTest {
@Test public void shouldCorrectlyBoundValues() {
assertThat(ClutchConfigurator.bound(0, 10, 50)).isEqualTo(10, Offset.offset(0.001));
assertThat(ClutchConfigurator.bound(0, 10, -10.0)).isEqualTo(0, Offset.offset(0.001));
assertThat(ClutchConfigurator.bound(0, 10, 5.2)).isEqualTo(5.2, Offset.offset(0.001));
}
@Test public void shouldProduceValeusInSaneRange() {
ThreadLocalRandom random = ThreadLocalRandom.current();
UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().build(1024);
for (int i = 0; i < 21; ++i) {
sketch.update(random.nextDouble(8.3, 75.0));
}
assertThat(sketch.getQuantile(0.99)).isLessThan(76.0);
}
@Test public void shouldGetConfigWithoutException() {
ClutchConfigurator configurator = new ClutchConfigurator(new IClutchMetricsRegistry() {}, 1, 2, Observable.interval(1, TimeUnit.DAYS));
configurator.getSketch(Clutch.Metric.CPU).update(70.0);
assertNotNull(configurator.getConfig());
}
@Test
public void testPercentileCalculation() {
DescriptiveStatistics stats = new DescriptiveStatistics(100);
UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().build(1024);
for (int i = 0; i < 200; ++i) {
sketch.update(i);
stats.addValue(i);
}
assertEquals(sketch.getQuantile(0.8), 160, 0);
assertEquals(stats.getPercentile(80), 180, 1);
}
// TODO: What guarantees do I want to make about the configurator?
}
| 9,055 |
0 | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control/clutch/ClutchConfigurationTest.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ClutchConfigurationTest {
@Test
public void shouldCreateClutchConfiguration() {
ClutchConfiguration config = ClutchConfiguration.builder().kd(1.0).build();
assertEquals(1.0, config.kd, 1e-10);
assertEquals(1.0, config.integralDecay, 1e-10);
config = ClutchConfiguration.builder().kd(1.0).integralDecay(0.9).build();
assertEquals(1.0, config.kd, 1e-10);
assertEquals(0.9, config.integralDecay, 1e-10);
}
}
| 9,056 |
0 | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control/clutch/ControlLoopTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.control.IActuator;
import com.netflix.control.controllers.ControlLoop;
import io.vavr.Tuple;
import org.junit.Test;
import rx.Observable;
import rx.observers.TestSubscriber;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class ControlLoopTest {
@Test public void shouldRemainInSteadyState() {
ClutchConfiguration config = ClutchConfiguration.builder()
.cooldownInterval(10L)
.cooldownUnits(TimeUnit.MILLISECONDS)
.metric(Clutch.Metric.CPU)
.kd(0.01)
.kp(0.01)
.kd(0.01)
.maxSize(10)
.minSize(3)
.rope(Tuple.of(0.25, 0.0))
.setPoint(0.6)
.build();
TestSubscriber<Double> subscriber = new TestSubscriber<>();
Observable.range(0, 1000)
.map(__ -> new Event(Clutch.Metric.CPU, 0.5))
.compose(new ControlLoop(config, IActuator.of(x -> x), new AtomicLong(8)))
.toBlocking()
.subscribe(subscriber);
subscriber.assertNoErrors();
subscriber.assertCompleted();
assertThat(subscriber.getOnNextEvents()).allSatisfy(x -> assertThat(x).isEqualTo(8.0));
}
@Test public void shouldBeUnperturbedByOtherMetrics() {
ClutchConfiguration config = ClutchConfiguration.builder()
.cooldownInterval(10L)
.cooldownUnits(TimeUnit.MILLISECONDS)
.metric(Clutch.Metric.CPU)
.kd(0.01)
.kp(0.01)
.kd(0.01)
.maxSize(10)
.minSize(3)
.rope(Tuple.of(0.25, 0.0))
.setPoint(0.6)
.build();
TestSubscriber<Double> subscriber = new TestSubscriber<>();
Observable<Event> cpu = Observable.range(0, 1000)
.map(__ -> new Event(Clutch.Metric.CPU, 0.5));
Observable<Event> network = Observable.range(0, 1000)
.map(__ -> new Event(Clutch.Metric.NETWORK, 0.1));
cpu.mergeWith(network)
.compose(new ControlLoop(config, IActuator.of(x -> x), new AtomicLong(8)))
.toBlocking()
.subscribe(subscriber);
subscriber.assertNoErrors();
subscriber.assertCompleted();
assertThat(subscriber.getOnNextEvents()).allSatisfy(x -> assertThat(x).isEqualTo(8.0));
}
@Test public void shouldScaleUp() {
ClutchConfiguration config = ClutchConfiguration.builder()
.cooldownInterval(10L)
.cooldownUnits(TimeUnit.MILLISECONDS)
.metric(Clutch.Metric.CPU)
.kd(0.01)
.kp(0.01)
.kd(0.01)
.maxSize(10)
.minSize(3)
.rope(Tuple.of(0.25, 0.0))
.setPoint(0.6)
.build();
TestSubscriber<Double> subscriber = new TestSubscriber<>();
Observable.range(0, 1000)
.map(__ -> new Event(Clutch.Metric.CPU, 0.7))
.compose(new ControlLoop(config, IActuator.of(Math::ceil), new AtomicLong(8)))
.toBlocking()
.subscribe(subscriber);
subscriber.assertNoErrors();
subscriber.assertCompleted();
assertThat(subscriber.getOnNextEvents()).allSatisfy(x -> assertThat(x).isEqualTo(9.0));
}
@Test public void shouldScaleDown() {
ClutchConfiguration config = ClutchConfiguration.builder()
.cooldownInterval(10L)
.cooldownUnits(TimeUnit.MILLISECONDS)
.metric(Clutch.Metric.CPU)
.kd(0.01)
.kp(0.01)
.kd(0.01)
.maxSize(10)
.minSize(3)
.rope(Tuple.of(0.25, 0.0))
.setPoint(0.6)
.build();
TestSubscriber<Double> subscriber = new TestSubscriber<>();
Observable.range(0, 1000)
.map(__ -> new Event(Clutch.Metric.CPU, 0.2))
.compose(new ControlLoop(config, IActuator.of(Math::ceil), new AtomicLong(8)))
.toBlocking()
.subscribe(subscriber);
subscriber.assertNoErrors();
subscriber.assertCompleted();
assertThat(subscriber.getOnNextEvents()).allSatisfy(x -> assertThat(x).isLessThan(8.0));
}
@Test public void shouldScaleUpAndDown() {
ClutchConfiguration config = ClutchConfiguration.builder()
.cooldownInterval(0L)
.cooldownUnits(TimeUnit.MILLISECONDS)
.metric(Clutch.Metric.CPU)
.kd(0.1)
.kp(0.5)
.kd(0.1)
.maxSize(10)
.minSize(3)
.rope(Tuple.of(0.0, 0.0))
.setPoint(0.6)
.build();
TestSubscriber<Double> subscriber = new TestSubscriber<>();
Observable.range(0, 1000)
.map(tick -> new Event(Clutch.Metric.CPU, ((tick % 60.0) + 30.0) / 100.0))
.compose(new ControlLoop(config, IActuator.of(Math::ceil), new AtomicLong(5)))
.toBlocking()
.subscribe(subscriber);
subscriber.assertNoErrors();
subscriber.assertCompleted();
assertThat(subscriber.getOnNextEvents()).anySatisfy(x -> assertThat(x).isLessThan(5.0));
assertThat(subscriber.getOnNextEvents()).anySatisfy(x -> assertThat(x).isGreaterThan(5.0));
}
@Test public void shouldScaleUpAndDownWithValuesInDifferentRange() {
ClutchConfiguration config = ClutchConfiguration.builder()
.cooldownInterval(0L)
.cooldownUnits(TimeUnit.MILLISECONDS)
.metric(Clutch.Metric.CPU)
.kd(0.01)
.kp(0.05)
.kd(0.01)
.maxSize(10)
.minSize(3)
.rope(Tuple.of(0.0, 0.0))
.setPoint(60.0)
.build();
TestSubscriber<Double> subscriber = new TestSubscriber<>();
Observable.range(0, 1000)
.map(tick -> new Event(Clutch.Metric.CPU, (tick % 60.0) + 30.0))
.compose(new ControlLoop(config, IActuator.of(Math::ceil), new AtomicLong(5)))
.toBlocking()
.subscribe(subscriber);
subscriber.assertNoErrors();
subscriber.assertCompleted();
assertThat(subscriber.getOnNextEvents()).anySatisfy(x -> assertThat(x).isLessThan(5.0));
assertThat(subscriber.getOnNextEvents()).anySatisfy(x -> assertThat(x).isGreaterThan(5.0));
}
}
| 9,057 |
0 | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/test/java/com/netflix/control/clutch/ClutchExperimentalTest.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ClutchExperimentalTest {
}
| 9,058 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/IActuator.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control;
import rx.functions.Func1;
/**
* Same interface as IController but separated so that actuators can be identified.
*
* The job of the actuator is to receive a size and alter the size of the target
* to be autoscaled. This might for example be a Mantis Job, a Flink Router or even
* an AWS Autoscaling Group.
*/
public abstract class IActuator extends IController {
/**
* Static factory method for constructing an instance of IAcuator.
*
* @param fn A function which presumably side-effects for actuation. Should return its input.
* @return An IActuator which calls fn with the value.
*/
public static IActuator of(Func1<Double, Double> fn) {
return new IActuator() {
@Override
protected Double processStep(Double value) {
return fn.call(value);
}
};
}
}
| 9,059 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/IController.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control;
import rx.Observable;
import rx.Subscriber;
/**
* The Feedback Principle: Constantly compare the actual output to the
* setpoint; then apply a corrective action in the proper direction and
* approximately of the correct size.
*
* Iteratively applying changes in the correct direction allows this
* system to converge onto the correct value over time.
*
*/
public abstract class IController implements Observable.Operator<Double, Double> {
private final IController parent = this;
/**
* Implementation method for Controller components. Surrounding RxJava machinery will call this method.
*
* @param value Input from previous stage of control loop processing.
* @return Output intended for next stage of control loop processing.
*/
protected abstract Double processStep(Double value);
@Override
public Subscriber<? super Double> call(final Subscriber<? super Double> s) {
return new Subscriber<Double>(s) {
@Override
public void onCompleted() {
if (!s.isUnsubscribed()) {
s.onCompleted();
}
}
@Override
public void onError(Throwable t) {
if (!s.isUnsubscribed()) {
s.onError(t);
}
}
@Override
public void onNext(Double error) {
Double controlAction = parent.processStep(error);
if (!s.isUnsubscribed()) {
s.onNext(controlAction);
}
}
};
}
}
| 9,060 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/utils/OperatorToTransformer.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.utils;
import rx.Observable;
/*
Wraps an rx Operator into an rx Transformer
*/
public class OperatorToTransformer<T, R> implements Observable.Transformer<T, R> {
private final Observable.Operator<R, T> op;
public OperatorToTransformer(Observable.Operator<R, T> op) {
this.op = op;
}
@Override
public Observable<R> call(Observable<T> tObservable) {
return tObservable.lift(op);
}
}
| 9,061 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/examples/ExampleAutoScaler.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.examples;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.control.actuators.MantisJobActuator;
import com.netflix.control.controllers.PIDController;
import com.netflix.control.controllers.ErrorComputer;
import com.netflix.control.controllers.Integrator;
import rx.Observable;
/**
* Simple example controller shows how one can create a PID which can auto-scale
* a process on a single metric.
*/
public class ExampleAutoScaler implements Observable.Transformer<Double, Double> {
private Double setPoint = 65.0;
private Double rope = 5.0;
private double kp = 0.01;
private double ki = 0.01;
private double kd = 0.01;
private double min = 1.0;
private double max = 10.0;
@Override
public Observable<Double> call(Observable<Double> cpuMeasurements) {
return cpuMeasurements
/*
The error computer here is going to take our stream of CPU
readings and compute an error value for our controller.
In this case we're targeting 65.0% CPU usage, and the problem
is inverted (scaling up causes CPU to decrease). Finally we
use a region of practical equivalence (ROPE) sometimes referred
to as a dead zone around our target of 65.0. The reason for this
is that it is difficult to hit 65% CPU usage exactly. This treats
the interval [60.0, 70.0] as the setPoint.
*/
.lift(new ErrorComputer(this.setPoint, true, rope))
/*
The controller takes the error measurements and attempts
to determine the correct scale to track the setPoint. Each of the
gain parameters can be thought of as a factor multiplied by that
particular component.
kp: Proportional gain, multiplied by the error.
ki: Integral gain, multiplied by the sum of all errors. (Recall
error can be negative!)
kd: Derivative gain, multiplied by the diference between error now
and at t-1.
*/
.lift(new PIDController(kp, ki, kd))
/*
The integrator's job is to sum up the output of the controller. The
reason we integrate is because our actuator expects whole size numbers. If
instead we were required to produce only the differences (+2 for scale up two
workers, -3 to scale down three then we would omit the integrator.
*/
.lift(new Integrator(1.0, min, max, 1.0))
/*
We now feed this to an actuator which hows how to actually perform
the scaling action against the target. This can be achieved by performing a
REST call or communicating with other in-process systems.
*/
.lift(new MantisJobActuator("myJob", 1, "prod", "us-east-1", "main"))
/*
Finally we perform some logging.
*/
.doOnNext(System.out::println);
}
}
| 9,062 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/actuators/MantisJobActuator.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.actuators;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.netflix.control.IActuator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Actuator which controls the number of instances for a particular job id and stage.
*/
public class MantisJobActuator extends IActuator {
private final String jobId;
private final Integer stageNumber;
private static Logger logger = LoggerFactory.getLogger(MantisJobActuator.class);
private Long lastValue = Long.MIN_VALUE;
private final String url;
public MantisJobActuator(String jobId, Integer stageNumber, String environ, String region, String stack) {
this.jobId = jobId;
this.stageNumber = stageNumber;
this.url = "staging".equals(stack.toLowerCase())
? "https://mantisapi.staging." + region + "." + environ + ".netflix.net"
: "https://mantisapi." + region + "." + environ + ".netflix.net";
logger.debug("Using scaling endpoint: " + url);
}
private final String scaleEndPoint = "/api/jobs/scaleStage";
@Override
protected Double processStep(Double input) {
Long numWorkers = ((Double) Math.ceil(input)).longValue();
if (numWorkers != lastValue) {
logger.info("Scaling " + this.jobId + " to " + numWorkers + " workers.");
String payload = "{\"JobId\":\"" + this.jobId + "\",\"StageNumber\":"
+ this.stageNumber + ",\"NumWorkers\":\"" + numWorkers + "\"}";
try {
HttpResponse<String> resp = Unirest.post(url + scaleEndPoint)
.header("accept", "application/json")
.body(payload)
.asString();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
lastValue = numWorkers;
}
return numWorkers * 1.0;
}
}
| 9,063 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/controllers/Derivative.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import com.netflix.control.IController;
public class Derivative extends IController {
private double last = 0;
private boolean initialized = false;
@Override
protected Double processStep(Double input) {
if (initialized) {
double output = input - last;
this.last = input;
return output;
} else {
return 0.0;
}
}
}
| 9,064 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/controllers/ControlLoop.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.control.IActuator;
import com.netflix.control.clutch.Clutch;
import com.netflix.control.clutch.ClutchConfiguration;
import com.netflix.control.clutch.Event;
import com.yahoo.sketches.quantiles.UpdateDoublesSketch;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.schedulers.Schedulers;
@Slf4j
public class ControlLoop implements Observable.Transformer<Event, Double> {
private final ClutchConfiguration config;
private final IActuator actuator;
private final AtomicDouble dampener;
private final AtomicLong currentScale;
private final long cooldownMillis;
private final AtomicLong cooldownTimestamp;
private final UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().setK(1024).build();
public ControlLoop(ClutchConfiguration config, IActuator actuator, AtomicLong initialSize) {
this(config, actuator, initialSize, new AtomicDouble(1.0));
}
public ControlLoop(ClutchConfiguration config, IActuator actuator, AtomicLong initialSize,
AtomicDouble dampener) {
this.config = config;
this.actuator = actuator;
this.currentScale = initialSize;
this.dampener = dampener;
this.cooldownMillis = config.getCooldownUnits().toMillis(config.cooldownInterval);
this.cooldownTimestamp = new AtomicLong(System.currentTimeMillis() + this.cooldownMillis);
}
@Override
public Observable<Double> call(Observable<Event> events) {
events = events.share();
// TODO: How do I get a zero if nothing came through?
Observable<Event> lag = events.filter(event -> event.getMetric() == Clutch.Metric.LAG);
Observable<Event> drops = events.filter(event -> event.getMetric() == Clutch.Metric.DROPS);
return events
.filter(e -> e.metric == config.metric)
.map(e -> e.value)
.doOnNext(sketch::update)
.lift(new ErrorComputer(config.setPoint, true, config.rope._1, config.rope._2))
.lift(new PIDController(config.kp, config.ki, config.kd, 1.0, new AtomicDouble(1.0), config.integralDecay))
.lift(new Integrator(currentScale.get(), config.minSize, config.maxSize, config.integralDecay))
.filter(__ -> this.cooldownMillis == 0 || cooldownTimestamp.get() <= System.currentTimeMillis() - this.cooldownMillis)
.filter(scale -> this.currentScale.get() != Math.round(Math.ceil(scale)))
.lift(actuator)
.doOnNext(scale -> this.currentScale.set(Math.round(Math.ceil(scale))))
.doOnNext(__ -> cooldownTimestamp.set(System.currentTimeMillis()));
}
}
| 9,065 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/controllers/Integrator.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import com.netflix.control.IController;
public class Integrator extends IController {
private double sum = 0;
private double min = Double.NEGATIVE_INFINITY;
private double max = Double.POSITIVE_INFINITY;
private double decayFactor = 1.0;
public Integrator() {
}
public Integrator(double init) {
this.sum = init;
}
public Integrator(double init, double min, double max) {
this(init, min, max, 1.0);
}
public Integrator(double init, double min, double max, double decayFactor) {
this.sum = init;
this.min = min;
this.max = max;
this.decayFactor = decayFactor;
}
/**
* A Clutch specific optimization, I don't like this one bit,
* and would like to clean it up before OSS probably tearing down the
* Rx pipeline and rewiring it instead.
* @param val The value to which this integrator will be set.
*/
public void setSum(double val) {
this.sum = val;
}
@Override
protected Double processStep(Double input) {
double newSum = this.sum + input;
newSum = (newSum > max) ? max : newSum;
newSum = (newSum < min) ? min : newSum;
this.sum = decayFactor * newSum;
return newSum;
}
}
| 9,066 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/controllers/PIDController.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.control.IController;
/**
* The Feedback Principle: Constantly compare the actual output to the
* setpoint; then apply a corrective action in the proper direction and
* approximately of the correct size.
*
* Iteratively applying changes in the correct direction allows this
* system to converge onto the correct value over time.
*
*/
public class PIDController extends IController {
private final Double kp; // Proportional Gain
private final Double ki; // Integral Gain
private final Double kd; // Derivative Gain
private Double previous = 0.0;
private final double deltaT;
private final AtomicDouble dampener;
private final double integralDecay;
private Double integral = 0.0;
private Double derivative = 0.0;
/**
* Implements a Proportional-Integral-Derivative (PID) three term control
* system.
*
* @param kp The gain for the proportional component of the controller.
* @param ki The gain for the integral component of the controller.
* @param kd The gain for the derivative component of the controller.
* @param deltaT The time delta. A useful default is 1.0.
* @param dampener A dampening signal which can be used for gain scheduling.
* @param integralDecay Factor [0.0, 1.0] to decay the integral component on each step.
*
* Setting the gain for an individual component disables said
* component. For example setting kd to 0.0 creates a PI (two term) control
* system.
*
* Gain scheduling is a method of manipulating the behavior of a PID
* controller at runtime. The concept is that different gain schedules might
* be appropriate at different times. Some examples;
*
* Oscillation: High gain can exacerbate and even cause oscillation.
* Chaos Kong: Increasing gain to accelerate scale ups.
*/
public PIDController(Double kp, Double ki, Double kd, Double deltaT, AtomicDouble dampener, double integralDecay) {
this.kp = kp;
this.ki = ki;
this.kd = kd;
this.deltaT = deltaT;
this.dampener = dampener;
this.integralDecay = integralDecay;
}
public PIDController(Double kp, Double ki, Double kd) {
this(kp, ki, kd, 1.0, new AtomicDouble(1.0), 1.0);
}
@Override
public Double processStep(Double error) {
double curIntegral = this.integral + this.deltaT * error;
this.derivative = (error - this.previous) / this.deltaT;
this.previous = error;
this.integral = this.integralDecay * curIntegral;
double d = this.dampener.get();
return this.kp * d * error
+ this.ki * d * curIntegral
+ this.kd * d * this.derivative;
}
/**
* @deprecated
* Use the public constructors
*/
@Deprecated
public static PIDController of(Double kp, Double ki, Double kd, AtomicDouble dampener) {
return new PIDController(kp, ki, kd, 1.0, dampener, 1.0);
}
/**
* @deprecated
* Use the public constructors
*/
@Deprecated
public static PIDController of(Double kp, Double ki, Double kd, Double deltaT) {
return new PIDController(kp, ki, kd, deltaT, new AtomicDouble(1.0), 1.0);
}
/**
* @deprecated
* Use the public constructors
*/
@Deprecated
public static PIDController of(Double kp, Double ki, Double kd) {
return new PIDController(kp, ki, kd, 1.0, new AtomicDouble(1.0), 1.0);
}
public AtomicDouble getDampener() {
return this.dampener;
}
public double getIntegralDecay() {
return this.integralDecay;
}
}
| 9,067 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/controllers/ErrorComputer.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import com.netflix.control.IController;
/**
* The loss computation is generally the first step in a control system.
* The responsibility of this component is to compute the loss function
* on the output of the system under control.
*
* Example:
* [ErrorComputer] -> PIDController -> Integrator -> Actuator
*
* The loss acts as input for the control system.
*/
public class ErrorComputer extends IController {
private final double setPoint;
private final boolean inverted;
private final double lowerRope;
private final double upperRope;
/**
*
* @param setPoint The target value for the metric being tracked.
* @param inverted A boolean indicating whether or not to invert output. Output is generally inverted if increasing
* the plant input will decrease the output. For example when autoscaling increasing the number
* of worker instances will decrease messages processed per instance. This is an inverted problem.
* @param lowerRope Region of practical equivalence (ROPE) -- a region surrounding the setpoint considered equal to the setpoint.
* @param upperRope Region of practical equivalence (ROPE) -- a region surrounding the setpoint considered equal to the setpoint.
*/
public ErrorComputer(double setPoint, boolean inverted, double lowerRope, double upperRope) {
this.setPoint = setPoint;
this.inverted = inverted;
this.lowerRope = lowerRope;
this.upperRope = upperRope;
}
public ErrorComputer(double setPoint, boolean inverted, double rope) {
this.setPoint = setPoint;
this.inverted = inverted;
this.lowerRope = rope;
this.upperRope = rope;
}
@Override
public Double processStep(Double input) {
return inverted ?
-1.0 * loss(setPoint, input, lowerRope, upperRope) :
loss(setPoint, input, lowerRope, upperRope);
}
/**
* Computes the correct loss value considering all values within [setPoint-rope, setPoint+rope] are considered
* to be equivalent. Error must grow linearly once the value is outside of the ROPE, without a calculation such as
* this the loss is a step function once crossing the threshold, with this function loss is zero and linearly
* increases as it deviates from the setpoint and ROPE.
*
* @param setPoint The configured setPoint.
* @param observed The observed metric to be compared to the setPoint.
* @param lowerRope The region of practical equivalence (ROPE) on the lower end.
* @param upperRope The region of practical equivalence (ROPE) on the upper end.
* @return Error adjusted for the ROPE.
*/
public static double loss(double setPoint, double observed, double lowerRope, double upperRope) {
if (observed > setPoint + upperRope) {
return (setPoint + upperRope) - observed;
} else if (observed < setPoint - lowerRope) {
return (setPoint - lowerRope) - observed;
}
return 0.0;
}
}
| 9,068 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/controllers/BoundToInterval.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import com.netflix.control.IController;
public class BoundToInterval extends IController {
private final double min;
private final double max;
public BoundToInterval(double min, double max) {
this.min = min;
this.max = max;
}
@Override
protected Double processStep(final Double input) {
double x = input;
return x > this.max ? this.max :
x < this.min ? this.min :
x;
}
public static BoundToInterval of(double min, double max) {
return new BoundToInterval(min, max);
}
}
| 9,069 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/controllers/BoostComputer.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.controllers;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.control.IController;
public class BoostComputer extends IController {
private final AtomicLong size;
public BoostComputer(final AtomicLong size) {
this.size = size;
}
@Override
protected Double processStep(final Double input) {
return (input + this.size.get()) / this.size.get();
}
}
| 9,070 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/IRpsMetricComputer.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import io.vavr.Function2;
import java.util.Map;
/**
* A function for computing the RPS metric to be compared against the setPoint and feed to the PID controller.
* Arguments:
* 1.) the clutch configuration for the current control loop
* 2.) a Map containing metrics for computation
* Return:
* the computed RPS metric
*/
@FunctionalInterface
public interface IRpsMetricComputer extends Function2<ClutchConfiguration, Map<Clutch.Metric, Double>, Double> {
}
| 9,071 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/ClutchExperimental.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.control.IActuator;
import com.netflix.control.clutch.metrics.IClutchMetricsRegistry;
import com.yahoo.sketches.quantiles.UpdateDoublesSketch;
import io.vavr.Function1;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import rx.Observable;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* Clutch experimental is taking a radically different approach to auto scaling, something akin to the first
* iteration of clutch but with lessons from the past year of auto scaling.
*/
public class ClutchExperimental implements Observable.Transformer<Event, Object> {
private final IActuator actuator;
private final AtomicLong currentSize;
private final Integer minSize;
private final Integer maxSize;
private final Observable<Long> timer;
private final Observable<Integer> sizeObs;
private final long initialConfigMillis;
private final Function1<Map<Clutch.Metric, UpdateDoublesSketch>, ClutchConfiguration> configurator;
private final IRpsMetricComputer rpsMetricComputer;
private final IScaleComputer scaleComputer;
/**
* Constructs a new Clutch instance for autoscaling.
* @param actuator A function of Double -> Double which causes the scaling to occur.
* @param initialSize The initial size of the cluster as it exists before scaling.
* @param minSize The minimum size to which the cluster can/should scale.
* @param maxSize The maximum size to which the cluster can/should scale.
* @param sizeObs An observable indicating the size of the cluster should external events resize it.
* @param timer An observable on which each tick signifies a new configuration should be emitted.
* @param initialConfigMillis The initial number of milliseconds before initial configuration.
* @param configurator Function to generate a ClutchConfiguration based on metric sketches.
* @param rpsMetricComputer Computes the RPS metric to be feed into the PID controller.
* @param scaleComputer Computes the new scale based on the current scale and PID controller output.
*
*/
public ClutchExperimental(IActuator actuator, Integer initialSize, Integer minSize, Integer maxSize,
Observable<Integer> sizeObs, Observable<Long> timer, long initialConfigMillis,
Function1<Map<Clutch.Metric, UpdateDoublesSketch>, ClutchConfiguration> configurator,
IRpsMetricComputer rpsMetricComputer,
IScaleComputer scaleComputer) {
this.actuator = actuator;
this.currentSize = new AtomicLong(initialSize);
this.minSize = minSize;
this.maxSize = maxSize;
this.sizeObs = sizeObs;
this.timer = timer;
this.initialConfigMillis = initialConfigMillis;
this.configurator = configurator;
this.rpsMetricComputer = rpsMetricComputer;
this.scaleComputer = scaleComputer;
}
public ClutchExperimental(IActuator actuator, Integer currentSize, Integer minSize, Integer maxSize,
Observable<Integer> sizeObs, Observable<Long> timer, long initialConfigMillis,
Function1<Map<Clutch.Metric, UpdateDoublesSketch>, ClutchConfiguration> configurator) {
this(actuator, currentSize, minSize, maxSize, sizeObs, timer, initialConfigMillis, configurator,
new ExperimentalControlLoop.DefaultRpsMetricComputer(), new ExperimentalControlLoop.DefaultScaleComputer());
}
public ClutchExperimental(IActuator actuator, Integer currentSize, Integer minSize, Integer maxSize,
Observable<Integer> sizeObs, Observable<Long> timer, long initialConfigMillis, long coolDownSeconds) {
this(actuator, currentSize, minSize, maxSize, sizeObs, timer, initialConfigMillis, (sketches) -> {
double setPoint = 0.6 * sketches.get(Clutch.Metric.RPS).getQuantile(0.99);
Tuple2<Double, Double> rope = Tuple.of(setPoint * 0.15, 0.0);
// TODO: Significant improvements to gain computation can likely be made.
double kp = (setPoint * 1e-9) / 5.0;
double ki = 0.0;
double kd = (setPoint * 1e-9) / 4.0;
return new ClutchConfiguration.ClutchConfigurationBuilder()
.metric(Clutch.Metric.RPS)
.setPoint(setPoint)
.kp(kp)
.ki(ki)
.kd(kd)
.minSize(minSize)
.maxSize(maxSize)
.rope(rope)
.cooldownInterval(coolDownSeconds)
.cooldownUnits(TimeUnit.SECONDS)
.build();
});
}
@Override
public Observable<Object> call(Observable<Event> eventObservable) {
final Observable<Event> events = eventObservable.share();
return events
.compose(new ExperimentalClutchConfigurator(new IClutchMetricsRegistry() { }, timer,
initialConfigMillis, configurator))
.switchMap(config -> events
.compose(new ExperimentalControlLoop(config, this.actuator,
this.currentSize, new AtomicDouble(1.0), timer, sizeObs,
this.rpsMetricComputer, this.scaleComputer)));
}
}
| 9,072 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/SymptomDetector.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.yahoo.sketches.quantiles.DoublesSketch;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.HashSet;
import io.vavr.collection.Set;
import java.util.List;
import java.util.function.Predicate;
/**
* TODO: This is completely experimental, not currently in use.
*/
public class SymptomDetector {
private final Set<Tuple2<String, Predicate<List<? extends DoublesSketch>>>> symptoms = HashSet.empty();
public void registerDector(String symptom, Predicate<List<? extends DoublesSketch>> pred) {
symptoms.add(Tuple.of(symptom, pred));
}
public Set<String> getSymptoms(List<? extends DoublesSketch> observations) {
return symptoms
.filter(tup -> tup._2.test(observations))
.map(tup -> tup._1);
}
}
| 9,073 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/ClutchConfigurator.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.control.clutch.metrics.IClutchMetricsRegistry;
import com.yahoo.sketches.quantiles.DoublesSketch;
import com.yahoo.sketches.quantiles.UpdateDoublesSketch;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.HashSet;
import io.vavr.collection.Set;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.schedulers.Schedulers;
/**
* The ClutchConfigurator's responsibility is to Observe the metrics stream for the workers
* in a single stage and recommend a configuration for the autoscaler.
*
* There are several responsibilities;
* - Determine the dominant metric and recommend scaling occur on this metric.
* - Determine the true maximum achievable value for a metric and instead scale on that.
*
* WHAT ELSE?
* - Determine if a job is overprovisioned / underprovisioned.
* - What can we do with lag and drops?
* - What can we do with oscillation?
* - What can we do if maxSize is too small?
*
*/
@Slf4j
public class ClutchConfigurator implements Observable.Transformer<Event, ClutchConfiguration> {
private static double DEFAULT_SETPOINT = 60.0;
private static Tuple2<Double, Double> DEFAULT_ROPE = Tuple.of(25.0, 0.00);
private static int DEFAULT_K = 1024;
private static double DEFAULT_QUANTILE = 0.99;
private IClutchMetricsRegistry metricsRegistry;
private final Integer minSize;
private final Integer maxSize;
private final Observable<Long> timer;
private Integer loggingIntervalMins = 60;
/** Metrics which represent a resources and are consequently usable for scaling. */
private static Set<Clutch.Metric> resourceMetrics = HashSet
.of(Clutch.Metric.CPU, Clutch.Metric.MEMORY, Clutch.Metric.NETWORK, Clutch.Metric.UserDefined);
private static ConcurrentHashMap<Clutch.Metric, UpdateDoublesSketch> sketches = new ConcurrentHashMap<>();
static {
sketches.put(Clutch.Metric.CPU, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.MEMORY, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.NETWORK, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.LAG, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.DROPS, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.UserDefined, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
}
public ClutchConfigurator(IClutchMetricsRegistry metricsRegistry, Integer minSize, Integer maxSize, Observable<Long> timer) {
this.metricsRegistry = metricsRegistry;
this.minSize = minSize;
this.maxSize = maxSize;
this.timer = timer;
}
public ClutchConfigurator(IClutchMetricsRegistry metricsRegistry, Integer minSize, Integer maxSize, Observable<Long> timer,
Integer loggingIntervalMins) {
this(metricsRegistry, minSize, maxSize, timer);
this.loggingIntervalMins = loggingIntervalMins;
}
//
// Metrics
//
/**
* Determines the dominant metric given a stream of Metric -> UpdateDoublesSketch.
* If a User Defined metric is present we will always use it.
* @param metrics
* @return A Clutch.Metric on which the job should scale.
*/
private static Clutch.Metric determineDominantMetric(List<Map.Entry<Clutch.Metric, UpdateDoublesSketch>> metrics) {
if (metrics.stream().filter(metric -> metric.getKey() == Clutch.Metric.UserDefined).count() > 0) {
return Clutch.Metric.UserDefined;
}
Clutch.Metric metric = metrics.stream()
.max(Comparator.comparingDouble(a -> a.getValue().getQuantile(DEFAULT_QUANTILE)))
.map(Map.Entry::getKey)
.get();
log.info("Determined dominant resource: {}", metric.toString());
return metric;
}
/**
* The objective is to determine a setpoint which takes into account the fact that
* the worker may not be able to use all of the provisioned resources.
*
* @param metric A DoublesSketch representing the metric in question.
* @return An appropriate setpoint for a controller to use for autoscaling.
*/
private static double determineSetpoint(DoublesSketch metric) {
double quantile = metric.getQuantile(DEFAULT_QUANTILE);
double setPoint = quantile * (DEFAULT_SETPOINT / 100.0);
setPoint = setPoint == Double.NaN ? DEFAULT_SETPOINT : setPoint;
double bounded = bound(1.0, DEFAULT_SETPOINT, setPoint);
log.info("Determined quantile {} and setPoint of {} bounding to {}.", quantile, setPoint, bounded);
return bounded;
}
//
// Configs
//
/**
* Generates a configuration based on Clutch's best understanding of the job at this time.
* @return A configuration suitable for autoscaling with Clutch.
*/
protected ClutchConfiguration getConfig() {
Clutch.Metric dominantResource = determineDominantMetric(sketches.entrySet().stream()
.filter(x -> isResourceMetric(x.getKey()))
.filter(x -> x.getValue().getN() > 0)
.collect(Collectors.toList()));
double setPoint = determineSetpoint(sketches.get(dominantResource));
return new ClutchConfiguration.ClutchConfigurationBuilder()
.metric(dominantResource)
.setPoint(setPoint)
.kp(0.01)
.ki(0.01)
.kd(0.01)
.minSize(this.minSize)
.maxSize(this.maxSize)
.rope(DEFAULT_ROPE)
.cooldownInterval(5)
.cooldownUnits(TimeUnit.MINUTES)
.build();
}
/**
* Generates a configuration whose purpose is to pin high.
* @return A config which simply pins the controller to the maximum value.
*/
private ClutchConfiguration getPinHighConfig() {
return new ClutchConfiguration.ClutchConfigurationBuilder()
.metric(Clutch.Metric.CPU)
.setPoint(DEFAULT_SETPOINT)
.kp(0.01)
.ki(0.01)
.kd(0.01)
.minSize(this.maxSize)
.maxSize(this.maxSize)
.rope(DEFAULT_ROPE)
.cooldownInterval(5)
.cooldownUnits(TimeUnit.MINUTES)
.build();
}
protected UpdateDoublesSketch getSketch(Clutch.Metric metric) {
return sketches.get(metric);
}
@Override
public Observable<ClutchConfiguration> call(Observable<Event> eventObservable) {
eventObservable = eventObservable.share();
Observable<Object> logs = Observable.interval(this.loggingIntervalMins, TimeUnit.MINUTES)
.observeOn(Schedulers.newThread())
.map(__ -> {
logSketchSummary("CPU", sketches.get(Clutch.Metric.CPU));
logSketchSummary("MEMORY", sketches.get(Clutch.Metric.MEMORY));
logSketchSummary("NETWORK", sketches.get(Clutch.Metric.NETWORK));
logSketchSummary("UserDefined", sketches.get(Clutch.Metric.UserDefined));
return null;
});
Observable<ClutchConfiguration> configs = timer
.map(__ -> getConfig());
return eventObservable
.filter(event -> event != null && event.metric != null)
.map(event -> {
UpdateDoublesSketch sketch = sketches.computeIfAbsent(event.metric, metric ->
UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketch.update(event.value);
return null;
}) // Encourages RxJava to actually consume events.
.mergeWith(logs) // Encourages RxJava to actually consume events.
.filter(Objects::nonNull)
.cast(ClutchConfiguration.class)
.mergeWith(Observable.just(getPinHighConfig())) // Initial config
.mergeWith(configs) // Stream of configs.
.doOnNext(config -> log.info(config.toString()));
}
//
// Utils
//
private void logSketchSummary(String name, UpdateDoublesSketch sketch) {
log.info("{} sketch ({}) min: {}, max: {}, median: {}, 99th: {}", name, sketch.getN(), sketch.getMinValue(), sketch.getMaxValue(), sketch.getQuantile(0.5), sketch.getQuantile(0.99));
}
private static boolean isResourceMetric(Clutch.Metric metric) {
return resourceMetrics.contains(metric);
}
@VisibleForTesting
static double bound(double min, double max, double value) {
return value < min
? min
: value > max
? max
: value;
}
}
| 9,074 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/OscillationDetector.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import com.netflix.control.IController;
/**
* The OscillationDetctor collects scaling events from the actuator and
* determines wether the event was a scale up / down. It then computes
* a gain factor (see `OscillationDetector#computeOscillationFactor`) and sets
* the dampener based on this factor.
**/
public class OscillationDetector extends IController {
private final Cache<Long, Double> history;
private Double previous = -1.0;
private final Consumer<Double> callback;
public OscillationDetector(int historyMinutes, Consumer<Double> callback) {
this.history = CacheBuilder.newBuilder()
.maximumSize(12)
.expireAfterWrite(historyMinutes, TimeUnit.MINUTES)
.build();
this.callback = callback;
}
@Override
protected Double processStep(Double scale) {
this.previous = this.previous == null ? scale : this.previous;
double delta = scale > previous ? 1.0 : -1.0;
this.previous = scale;
history.put(System.currentTimeMillis(), delta);
this.callback.accept(computeOscillationFactor(history));
return scale;
}
/**
* Computes the oscillation factor which is the percentage of scaling events
* which were in different directions.
* 0.5 <= oscillationFactor <= 1.0
*
* @param actionCache A cache of timestamp -> scale
* @return The computed oscillation factor.
*/
private double computeOscillationFactor(Cache<Long, Double> actionCache) {
long nUp = actionCache.asMap().values().stream().filter(x -> x > 0.0).count();
long nDown = actionCache.asMap().values().stream().filter(x -> x < 0.0).count();
long n = nUp + nDown;
return n == 0
? 1.0
: nUp > nDown
? (1.0 * nUp) / n
: (1.0 * nDown) / n;
}
}
| 9,075 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/ClutchConfiguration.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import java.util.concurrent.TimeUnit;
import io.vavr.Tuple2;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Value;
/**
* Represents the overall configuration of a Clutch control loop.
*/
@EqualsAndHashCode
public @Builder(access = AccessLevel.PUBLIC) @Value class ClutchConfiguration {
/** The Metric for which this configuration is intended. */
public final Clutch.Metric metric;
/** The setPoint will be the value for the metric tracked by the controller. */
public final double setPoint;
/** Proportional controller gain. */
public final double kp;
/** Integral controller gain. */
public final double ki;
/** Derivative controller gain. */
public final double kd;
/** Integral component decay factor. */
@Builder.Default
public final double integralDecay = 1.0;
/** Minimum size for autoscaling. */
public final int minSize;
/** Maximum size for autoscaling */
public final int maxSize;
/** Region of Practical Equivalence. Value below and above setPoint which is treated as equal to the setPoint. */
public final Tuple2<Double, Double> rope;
/** Cooldown interval for the autoscaler. */
public final long cooldownInterval;
/** Cooldown time units for the autoscaler. */
public final TimeUnit cooldownUnits;
}
| 9,076 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/Event.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
public class Event {
public final Clutch.Metric metric;
public final double value;
public Event(Clutch.Metric metric, double value) {
this.metric = metric;
this.value = value;
}
public Clutch.Metric getMetric() {
return metric;
}
public double getValue() {
return value;
}
}
| 9,077 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/ExperimentalClutchConfigurator.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.netflix.control.clutch.metrics.IClutchMetricsRegistry;
import com.yahoo.sketches.quantiles.DoublesSketch;
import com.yahoo.sketches.quantiles.UpdateDoublesSketch;
import io.vavr.Function1;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import rx.Observable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ExperimentalClutchConfigurator implements Observable.Transformer<Event, ClutchConfiguration> {
private static int DEFAULT_K = 1024;
private static int NUM_STATS_DATA_POINTS = (int) TimeUnit.DAYS.toMinutes(7) * 2;
private IClutchMetricsRegistry metricsRegistry;
private final Observable<Long> timer;
private final long initialConfigMilis;
private final Function1<Map<Clutch.Metric, UpdateDoublesSketch>, ClutchConfiguration> configurator;
private static ConcurrentHashMap<Clutch.Metric, UpdateDoublesSketch> sketches = new ConcurrentHashMap<>();
private static ConcurrentHashMap<Clutch.Metric, DescriptiveStatistics> stats = new ConcurrentHashMap<>();
static {
sketches.put(Clutch.Metric.CPU, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.MEMORY, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.NETWORK, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.LAG, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.DROPS, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.UserDefined, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.RPS, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketches.put(Clutch.Metric.SOURCEJOB_DROP, UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
stats.put(Clutch.Metric.CPU, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stats.put(Clutch.Metric.MEMORY, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stats.put(Clutch.Metric.NETWORK, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stats.put(Clutch.Metric.LAG, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stats.put(Clutch.Metric.DROPS, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stats.put(Clutch.Metric.UserDefined, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stats.put(Clutch.Metric.RPS, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stats.put(Clutch.Metric.SOURCEJOB_DROP, new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
}
public ExperimentalClutchConfigurator(IClutchMetricsRegistry metricsRegistry, Observable<Long> timer,
long initialConfigMillis,
Function1<Map<Clutch.Metric, UpdateDoublesSketch>, ClutchConfiguration> configurator) {
this.metricsRegistry = metricsRegistry;
this.timer = timer;
this.initialConfigMilis = initialConfigMillis;
this.configurator = configurator;
}
//
// Configs
//
/**
* Generates a configuration based on Clutch's best understanding of the job at this time.
* @return A configuration suitable for autoscaling with Clutch.
*/
private ClutchConfiguration getConfig() {
return this.configurator.apply(sketches);
}
@Override
public Observable<ClutchConfiguration> call(Observable<Event> eventObservable) {
Observable<ClutchConfiguration> configs = timer
.map(__ -> getConfig())
.doOnNext(config -> log.info("New Config: {}", config.toString()));
Observable<ClutchConfiguration> initialConfig = Observable
.interval(this.initialConfigMilis, TimeUnit.MILLISECONDS)
.take(1)
.map(__ -> getConfig())
.doOnNext(config -> log.info("Initial Config: {}", config.toString()));
eventObservable
.filter(event -> event != null && event.metric != null)
.map(event -> {
UpdateDoublesSketch sketch = sketches.computeIfAbsent(event.metric, metric ->
UpdateDoublesSketch.builder().setK(DEFAULT_K).build());
sketch.update(event.value);
DescriptiveStatistics stat = stats.computeIfAbsent(event.metric, metric ->
new DescriptiveStatistics(NUM_STATS_DATA_POINTS));
stat.addValue(event.value);
return null;
}).subscribe();
return initialConfig
.concatWith(configs)
.distinctUntilChanged()
.doOnNext(__ -> log.info("RPS Sketch State: {}", sketches.get(Clutch.Metric.RPS)))
.doOnNext(__ -> {
logSketchSummary(sketches.get(Clutch.Metric.RPS));
logStatsSummary(stats.get(Clutch.Metric.RPS), "Stats RPS metric: ");
logStatsSummary(stats.get(Clutch.Metric.CPU), "Stats CPU metric: ");
logStatsSummary(stats.get(Clutch.Metric.MEMORY), "Stats Memory metric: ");
logStatsSummary(stats.get(Clutch.Metric.NETWORK), "Stats Network metric: ");
})
.doOnNext(config -> log.info("Clutch switched to config: {}", config));
}
private static void logSketchSummary(DoublesSketch sketch) {
double[] quantiles = sketch.getQuantiles(new double[]{0.0, 0.25, 0.5, 0.75, 0.99, 1.0});
log.info("RPS Sketch Quantiles -- Min: {}, 25th: {}, 50th: {}, 75th: {}, 99th: {}, Max: {}",
quantiles[0],
quantiles[1],
quantiles[2],
quantiles[3],
quantiles[4],
quantiles[5]
);
}
private static void logStatsSummary(DescriptiveStatistics stat, String prefix) {
log.info("{} RPS Sketch Quantiles -- Min: {}, 25th: {}, 50th: {}, 75th: {}, 99th: {}, Max: {}",
prefix,
stat.getPercentile(0),
stat.getPercentile(25),
stat.getPercentile(50),
stat.getPercentile(75),
stat.getPercentile(99),
stat.getPercentile(100)
);
}
}
| 9,078 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/Clutch.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import com.google.common.util.concurrent.AtomicDouble;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import rx.Observable;
import com.netflix.control.IActuator;
import com.netflix.control.clutch.metrics.IClutchMetricsRegistry;
import com.netflix.control.controllers.ControlLoop;
/**
* Clutch is our domain specific autoscaler which adopts many elements from control theory but allows us to fully
* encapsulate our desired autoscaling behavior.
*
* - Multiple Metric handled automatically identifying the dominant metric.
* - Handles dampening to prevent oscillation.
* - Handles a resistance metric if users want to provide feedback to the scaler itself.
**/
public class Clutch implements Observable.Transformer<Event, Object> {
/** Specifies all the Metrics clutch is capable of dealing with. */
public enum Metric {
/** CPU Resource Metric. */
CPU,
/** Memory Resource Metric. */
MEMORY,
/** Network Resource Metric. */
NETWORK,
/** Messages left unpolled, typically Kafka lag. */
LAG,
/** Messages dropped. */
DROPS,
/** Hypothetical metric which causes the controller to slow down. Currently unused. */
RESISTANCE,
/** A user defined resource metric provided by the job under control. Receives priority. */
UserDefined,
/** A measure of requests per second handled by the target. */
RPS,
/** Messages dropped by by the source job when sending to current job. */
SOURCEJOB_DROP
}
private final IActuator actuator;
private final AtomicLong initialSize;
private final Integer minSize;
private final Integer maxSize;
private final AtomicDouble dampener;
private Integer loggingIntervalMins = 60;
private final Observable<Long> timer = Observable.interval(1, TimeUnit.DAYS).share();
/**
* Constructs a new Clutch instance for autoscaling.
* @param actuator A function of Double -> Double which causes the scaling to occur.
* @param initialSize The initial size of the cluster as it exists before scaling.
* @param minSize The minimum size to which the cluster can/should scale.
* @param maxSize The maximum size to which the cluster can/shoulds cale.
*/
public Clutch(IActuator actuator, Integer initialSize, Integer minSize, Integer maxSize) {
this.actuator = actuator;
this.initialSize = new AtomicLong(initialSize);
this.minSize = minSize;
this.maxSize = maxSize;
this.dampener = new AtomicDouble(1.0);
}
public Clutch(IActuator actuator, Integer initialSize,
Integer minSize, Integer maxSize, Integer loggingIntervalMins) {
this(actuator, initialSize, minSize, maxSize);
this.loggingIntervalMins = loggingIntervalMins;
}
@Override
public Observable<Object> call(Observable<Event> eventObservable) {
final Observable<Event> events = eventObservable.share();
return events
.compose(new ClutchConfigurator(new IClutchMetricsRegistry() { }, minSize,
maxSize, timer, this.loggingIntervalMins))
.flatMap(config -> events.compose(new ControlLoop(config, this.actuator,
this.initialSize, dampener))
.takeUntil(timer)) // takeUntil tears down this control loop when a new config is produced.
.lift(new OscillationDetector(60, x -> this.dampener.set(Math.pow(x, 3))));
}
}
| 9,079 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/IScaleComputer.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import io.vavr.Function3;
/**
* A function for computing the new scale based on the current scale and the PID controller output.
* Arguments:
* 1.) the clutch configuration for the current control loop
* 2.) the current scale
* 3.) the delta computed by the PID controller
* Return:
* the new scale, which will be acted on by the actuator
*/
@FunctionalInterface
public interface IScaleComputer extends Function3<ClutchConfiguration, Long, Double, Double> {
}
| 9,080 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/ExperimentalControlLoop.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.util.concurrent.AtomicDouble;
import com.netflix.control.IActuator;
import com.netflix.control.controllers.ErrorComputer;
import com.netflix.control.controllers.Integrator;
import com.netflix.control.controllers.PIDController;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.Subscription;
@Slf4j
public class ExperimentalControlLoop implements Observable.Transformer<Event, Double> {
private final ClutchConfiguration config;
private final IActuator actuator;
private final AtomicDouble dampener;
private final AtomicLong cooldownTimestamp;
private final AtomicLong currentSize;
private final AtomicDouble lastLag;
private final Observable<Integer> size;
private final IRpsMetricComputer rpsMetricComputer;
private final IScaleComputer scaleComputer;
private long cooldownMillis;
public ExperimentalControlLoop(ClutchConfiguration config, IActuator actuator, AtomicLong currentSize,
Observable<Long> timer, Observable<Integer> size) {
this(config, actuator, currentSize, new AtomicDouble(1.0), timer, size,
new DefaultRpsMetricComputer(), new DefaultScaleComputer());
}
public ExperimentalControlLoop(ClutchConfiguration config, IActuator actuator, AtomicLong currentSize,
AtomicDouble dampener, Observable<Long> timer, Observable<Integer> size,
IRpsMetricComputer rpsMetricComputer,
IScaleComputer scaleComputer) {
this.config = config;
this.actuator = actuator;
this.dampener = dampener;
this.cooldownMillis = config.getCooldownUnits().toMillis(config.cooldownInterval);
this.cooldownTimestamp = new AtomicLong(System.currentTimeMillis());
this.currentSize = currentSize;
this.lastLag = new AtomicDouble(0.0);
this.size = size;
this.rpsMetricComputer = rpsMetricComputer;
this.scaleComputer = scaleComputer;
}
@Override
public Observable<Double> call(Observable<Event> events) {
events = events.share();
Observable<Event> lag =
Observable.just(new Event(Clutch.Metric.LAG, 0.0))
.mergeWith(events.filter(event -> event.getMetric() == Clutch.Metric.LAG));
Observable<Event> drops =
Observable.just(new Event(Clutch.Metric.DROPS, 0.0))
.mergeWith(events.filter(event -> event.getMetric() == Clutch.Metric.DROPS));
Observable<Event> sourceJobDrops =
Observable.just(new Event(Clutch.Metric.SOURCEJOB_DROP, 0.0))
.mergeWith(events.filter(event -> event.getMetric() == Clutch.Metric.SOURCEJOB_DROP));
Observable<Event> rps = events.filter(event -> event.getMetric() == Clutch.Metric.RPS);
Integrator deltaIntegrator = new Integrator(0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, config.integralDecay);
Subscription sizeSub = size
.doOnNext(currentSize::set)
.doOnNext(__ -> cooldownTimestamp.set(System.currentTimeMillis()))
.doOnNext(n -> log.info("Clutch received new scheduling update with {} workers.", n))
.subscribe();
return rps
.withLatestFrom(lag, drops, sourceJobDrops, (rpsEvent, lagEvent, dropEvent, sourceDropEvent) -> {
Map<Clutch.Metric, Double> metrics = new HashMap<>();
metrics.put(rpsEvent.getMetric(), rpsEvent.getValue());
metrics.put(lagEvent.getMetric(), lagEvent.getValue());
metrics.put(dropEvent.getMetric(), dropEvent.getValue());
metrics.put(sourceDropEvent.getMetric(), sourceDropEvent.getValue());
return metrics;
})
.doOnNext(metrics -> log.info("Latest metrics: {}", metrics))
.map(metrics -> this.rpsMetricComputer.apply(config, metrics))
.lift(new ErrorComputer(config.setPoint, true, config.rope._1, config.rope._2))
.lift(new PIDController(config.kp, config.ki, config.kd, 1.0, new AtomicDouble(1.0), config.integralDecay))
.doOnNext(d -> log.info("PID controller output: {}", d))
.lift(deltaIntegrator)
.doOnNext(d -> log.info("Integral: {}", d))
.filter(__ -> this.cooldownMillis == 0 || cooldownTimestamp.get() <= System.currentTimeMillis() - this.cooldownMillis)
.map(delta -> this.scaleComputer.apply(config, this.currentSize.get(), delta))
.doOnNext(d -> log.info("New desired size: {}, existing size: {}", d, this.currentSize.get()))
.filter(scale -> this.currentSize.get() != Math.round(Math.ceil(scale)))
.lift(actuator)
.doOnNext(scale -> this.currentSize.set(Math.round(Math.ceil(scale))))
.doOnNext(__ -> deltaIntegrator.setSum(0))
.doOnNext(__ -> cooldownTimestamp.set(System.currentTimeMillis()))
.doOnUnsubscribe(() -> {
sizeSub.unsubscribe();
});
}
/* For testing to trigger actuator on next event */
protected void setCooldownMillis(long cooldownMillis) {
this.cooldownMillis = cooldownMillis;
}
public static class DefaultRpsMetricComputer implements IRpsMetricComputer {
private double lastLag = 0;
public Double apply(ClutchConfiguration config, Map<Clutch.Metric, Double> metrics) {
double rps = metrics.get(Clutch.Metric.RPS);
double lag = metrics.get(Clutch.Metric.LAG);
double sourceDrops = metrics.get(Clutch.Metric.SOURCEJOB_DROP);
double drops = metrics.get(Clutch.Metric.DROPS);
double lagDerivative = lag - lastLag;
lastLag = lag;
return rps + lagDerivative + sourceDrops + drops;
}
}
public static class DefaultScaleComputer implements IScaleComputer {
public Double apply(ClutchConfiguration config, Long currentScale, Double delta) {
return Math.min(config.maxSize, Math.max(config.minSize, currentScale + delta));
}
}
}
| 9,081 |
0 | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch | Create_ds/mantis-rxcontrol/src/main/java/com/netflix/control/clutch/metrics/IClutchMetricsRegistry.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.control.clutch.metrics;
public interface IClutchMetricsRegistry {
public default void reportOverProvisioned(String name) {}
public default void reportUnderProvisioned(String name) {}
}
| 9,082 |
0 | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs/auth/TestSigV4Config.java | package software.aws.mcs.auth;
/*-
* #%L
* AWS SigV4 Auth Java Driver 4.x Plugin
* %%
* Copyright (C) 2020-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.File;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.ArrayList;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
public class TestSigV4Config {
static String[] DEFAULT_CONTACT_POINTS = {"127.0.0.1:9042"};
public static void main(String[] args) throws Exception {
String[] contactPointsRaw = DEFAULT_CONTACT_POINTS;
if (args.length == 1) {
contactPointsRaw = args[0].split(",");
} else if (args.length > 1) {
System.out.println("Usage: TestSigV4 [<contact points, comma separated, 'IP:port' format>]");
System.exit(-1);
}
ArrayList<InetSocketAddress> contactPoints = new ArrayList<>(contactPointsRaw.length);
for (int i = 0; i < contactPointsRaw.length; i++) {
String[] parts = contactPointsRaw[i].split(":");
contactPoints.add(InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])));
}
System.out.println("Using endpoints: " + contactPoints);
//By default the reference.conf is loaded by the driver which contains all defaults.
//You can override this by providing reference.conf on the classpath
//to isolate test you can load conf with a custom name
URL url = TestSigV4Config.class.getClassLoader().getResource("keyspaces-reference.conf");
File file = new File(url.toURI());
// The CqlSession object is the main entry point of the driver.
// It holds the known state of the actual Cassandra cluster (notably the Metadata).
// This class is thread-safe, you should create a single instance (per target Cassandra cluster), and share
// it throughout your application.
try (CqlSession session = CqlSession.builder()
.withConfigLoader(DriverConfigLoader.fromFile(file))
.addContactPoints(contactPoints)
.withLocalDatacenter("us-west-2")
.build()) {
// We use execute to send a query to Cassandra. This returns a ResultSet, which is essentially a collection
// of Row objects.
ResultSet rs = session.execute("select release_version from system.local");
// Extract the first row (which is the only one in this case).
Row row = rs.one();
// Extract the value of the first (and only) column from the row.
String releaseVersion = row.getString("release_version");
System.out.printf("Cassandra version is: %s%n", releaseVersion);
}
}
}
| 9,083 |
0 | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs/auth/SigV4AuthProviderTest.java | package software.aws.mcs.auth;
/*-
* #%L
* AWS SigV4 Auth Java Driver 4.x Plugin
* %%
* Copyright (C) 2020-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class SigV4AuthProviderTest {
@Test
public void testNonceExtraction() {
final String TEST_NONCE = "1234abcd1234abcd1234abcd1234abcd";
// Valid nonce is 32 characters, so we test that here
assertEquals(ByteBuffer.wrap(TEST_NONCE.getBytes(StandardCharsets.UTF_8)),
ByteBuffer.wrap(SigV4AuthProvider.extractNonce(ByteBuffer.wrap(("nonce=" + TEST_NONCE)
.getBytes(StandardCharsets.UTF_8)))));
}
@Test
public void testShortNonceExtraction() {
assertThrows(IllegalArgumentException.class, () -> {
SigV4AuthProvider.extractNonce(ByteBuffer.wrap("nonce=too_short".getBytes(StandardCharsets.UTF_8)));
});
}
@Test
public void testNonceExtractionFailure() {
assertThrows(IllegalArgumentException.class, () -> {
SigV4AuthProvider.extractNonce(ByteBuffer.wrap("nothing to see here".getBytes(StandardCharsets.UTF_8)));
});
}
@Test
public void testSimpleIndexOf() {
byte[] target = {0, 1, 2, 42, 24, 4, 5};
byte[] pattern = {42, 24};
assertEquals(3, SigV4AuthProvider.indexOf(target, pattern));
}
@Test
public void testLeadingIndexOf() {
byte[] target = {42, 24, 1, 2, 3, 4, 5};
byte[] pattern = {42, 24};
assertEquals(0, SigV4AuthProvider.indexOf(target, pattern));
}
@Test
public void testTrailingIndexOf() {
byte[] target = {1, 2, 3, 4, 5, 42, 24};
byte[] pattern = {42, 24};
assertEquals(5, SigV4AuthProvider.indexOf(target, pattern));
}
@Test
public void testPartialIndexOf() {
byte[] target = {1, 2, 42, 24, 3, 4, 5};
byte[] pattern = {42, 24, 42};
assertEquals(-1, SigV4AuthProvider.indexOf(target, pattern));
}
@Test
public void testPartialTrailingIndexOf() {
byte[] target = {1, 2, 3, 4, 5, 42};
byte[] pattern = {42, 24, 42};
assertEquals(-1, SigV4AuthProvider.indexOf(target, pattern));
}
}
| 9,084 |
0 | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs/auth/TestSigV4AssumeRoleConfig.java | package software.aws.mcs.auth;
/*-
* #%L
* AWS SigV4 Auth Java Driver 4.x Plugin
* %%
* Copyright (C) 2020-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import org.junit.platform.commons.util.StringUtils;
import java.io.File;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
public class TestSigV4AssumeRoleConfig {
static String KEYSPACES_DEFAULT_CONF="keyspaces-reference-norole.conf";
/**
* Before executing this test, ensure that KeySpaces tables are created.
* Refer ddl.cql and dml.cql to create and populate tables.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String keySpacesConf=KEYSPACES_DEFAULT_CONF;
if(args.length>1){
keySpacesConf=args[0];
System.out.println("Using key spaces config file: "+keySpacesConf);
keySpacesConf=Optional.of(keySpacesConf).filter(StringUtils::isBlank).orElse(KEYSPACES_DEFAULT_CONF);
}
URL url = TestSigV4AssumeRoleConfig.class.getClassLoader().getResource(keySpacesConf);
File file = new File(url.toURI());
// The CqlSession object is the main entry point of the driver.
// It holds the known state of the actual Cassandra cluster (notably the Metadata).
// This class is thread-safe, you should create a single instance (per target Cassandra cluster), and share
// it throughout your application.
try (CqlSession session = CqlSession.builder()
.withConfigLoader(DriverConfigLoader.fromFile(file))
.build()) {
// We use execute to send a query to Cassandra. This returns a ResultSet, which is essentially a collection
// of Row objects.
ResultSet rs = session.execute("select * from testkeyspace.testconf");
// Extract the first row (which is the only one in this case).
Row row = rs.one();
// Extract the value of the first (and only) column from the row.
String releaseVersion = row.getString("category");
System.out.printf("Cassandra version is: %s%n", releaseVersion);
}
}
}
| 9,085 |
0 | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/test/java/software/aws/mcs/auth/TestSigV4.java | package software.aws.mcs.auth;
/*-
* #%L
* AWS SigV4 Auth Java Driver 4.x Plugin
* %%
* Copyright (C) 2020-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.net.InetSocketAddress;
import java.util.ArrayList;
import javax.net.ssl.SSLContext;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
public class TestSigV4 {
static String[] DEFAULT_CONTACT_POINTS = {"127.0.0.1:9042"};
public static void main(String[] args) throws Exception {
String[] contactPointsRaw = DEFAULT_CONTACT_POINTS;
if (args.length == 1) {
contactPointsRaw = args[0].split(",");
} else if (args.length > 1) {
System.out.println("Usage: TestSigV4 [<contact points, comma separated, 'IP:port' format>]");
System.exit(-1);
}
ArrayList<InetSocketAddress> contactPoints = new ArrayList<>(contactPointsRaw.length);
for (int i = 0; i < contactPointsRaw.length; i++) {
String[] parts = contactPointsRaw[i].split(":");
contactPoints.add(InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])));
}
System.out.println("Using endpoints: " + contactPoints);
// The CqlSession object is the main entry point of the driver.
// It holds the known state of the actual Cassandra cluster (notably the Metadata).
// This class is thread-safe, you should create a single instance (per target Cassandra cluster), and share
// it throughout your application.
try (CqlSession session = CqlSession.builder()
.addContactPoints(contactPoints)
.withAuthProvider(new SigV4AuthProvider())
.withSslContext(SSLContext.getDefault())
.withLocalDatacenter("us-west-2")
.build()) {
// We use execute to send a query to Cassandra. This returns a ResultSet, which is essentially a collection
// of Row objects.
ResultSet rs = session.execute("select release_version from system.local");
// Extract the first row (which is the only one in this case).
Row row = rs.one();
// Extract the value of the first (and only) column from the row.
String releaseVersion = row.getString("release_version");
System.out.printf("Cassandra version is: %s%n", releaseVersion);
}
}
} | 9,086 |
0 | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/main/java/software/aws/mcs | Create_ds/aws-sigv4-auth-cassandra-java-driver-plugin/src/main/java/software/aws/mcs/auth/SigV4AuthProvider.java | package software.aws.mcs.auth;
/*-
* #%L
* AWS SigV4 Auth Java Driver 4.x Plugin
* %%
* Copyright (C) 2020-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.constraints.NotNull;
import org.apache.commons.codec.binary.Hex;
import com.datastax.oss.driver.api.core.auth.AuthProvider;
import com.datastax.oss.driver.api.core.auth.AuthenticationException;
import com.datastax.oss.driver.api.core.auth.Authenticator;
import com.datastax.oss.driver.api.core.config.DriverOption;
import com.datastax.oss.driver.api.core.context.DriverContext;
import com.datastax.oss.driver.api.core.metadata.EndPoint;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.signer.internal.Aws4SignerUtils;
import software.amazon.awssdk.auth.signer.internal.SignerConstant;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.auth.StsAssumeRoleCredentialsProvider;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import static software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider.create;
/**
* This auth provider can be used with the Amazon MCS service to
* authenticate with SigV4. It uses the AWSCredentialsProvider
* interface provided by the official AWS Java SDK to provide
* credentials for signing.
*/
public class SigV4AuthProvider implements AuthProvider {
private static final byte[] SIGV4_INITIAL_RESPONSE_BYTES = "SigV4\0\0".getBytes(StandardCharsets.UTF_8);
private static final ByteBuffer SIGV4_INITIAL_RESPONSE;
static {
ByteBuffer initialResponse = ByteBuffer.allocate(SIGV4_INITIAL_RESPONSE_BYTES.length);
initialResponse.put(SIGV4_INITIAL_RESPONSE_BYTES);
initialResponse.flip();
// According to the driver docs, it's safe to reuse a
// read-only buffer, and in our case, the initial response has
// no sensitive information
SIGV4_INITIAL_RESPONSE = initialResponse.asReadOnlyBuffer();
}
private static final int AWS_FRACTIONAL_TIMESTAMP_DIGITS = 3; // SigV4 expects three digits of nanoseconds for timestamps
private static final DateTimeFormatter timestampFormatter =
(new DateTimeFormatterBuilder()).appendInstant(AWS_FRACTIONAL_TIMESTAMP_DIGITS).toFormatter();
private static final byte[] NONCE_KEY = "nonce=".getBytes(StandardCharsets.UTF_8);
private static final int EXPECTED_NONCE_LENGTH = 32;
// These are static values because we don't need HTTP, but SigV4 assumes some amount of HTTP metadata
private static final String CANONICAL_SERVICE = "cassandra";
private final AwsCredentialsProvider credentialsProvider;
private final String signingRegion;
/**
* Create a new Provider, using the
* DefaultAWSCredentialsProviderChain as its credentials provider.
* The signing region is taking from the AWS_DEFAULT_REGION
* environment variable or the "aws.region" system property.
*/
public SigV4AuthProvider() {
this(create(), null);
}
private final static DriverOption REGION_OPTION = () -> "advanced.auth-provider.aws-region";
private final static DriverOption ROLE_OPTION = () -> "advanced.auth-provider.aws-role-arn";
/**
* This constructor is provided so that the driver can create
* instances of this class based on configuration. For example:
*
* <pre>
* datastax-java-driver.advanced.auth-provider = {
* aws-region = us-east-2
* class = software.aws.mcs.auth.SigV4AuthProvider
* }
* </pre>
*
* The signing region is taken from the
* datastax-java-driver.advanced.auth-provider.aws-region
* property, from the "aws.region" system property, or the
* AWS_DEFAULT_REGION environment variable, in that order of
* preference.
*
* For programmatic construction, use {@link #SigV4AuthProvider()}
* or {@link #SigV4AuthProvider(AwsCredentialsProvider, String)}.
*
* @param driverContext the driver context for instance creation.
* Unused for this plugin.
*/
public SigV4AuthProvider(DriverContext driverContext) {
this(driverContext.getConfig().getDefaultProfile().getString(REGION_OPTION, getDefaultRegion()),
driverContext.getConfig().getDefaultProfile().getString(ROLE_OPTION, null));
}
/**
* Create a new Provider, using the specified region.
* @param region the region (e.g. us-east-1) to use for signing. A
* null value indicates to use the AWS_REGION environment
* variable, or the "aws.region" system property to configure it.
*/
public SigV4AuthProvider(final String region) {
this(create(), region);
}
/**
* Create a new Provider, using the specified region and IAM role to assume.
* @param region the region (e.g. us-east-1) to use for signing. A
* null value indicates to use the AWS_REGION environment
* variable, or the "aws.region" system property to configure it.
* @param roleArn The IAM Role ARN which the connecting client should assume before connecting with Amazon Keyspaces.
*/
public SigV4AuthProvider(final String region,final String roleArn) {
this(Optional.ofNullable(roleArn).map(r->(AwsCredentialsProvider)createSTSRoleCredentialProvider(r,region)).orElse(create()), region);
}
/**
* Create a new Provider, using the specified AWSCredentialsProvider and region.
* @param credentialsProvider the credentials provider used to obtain signature material
* @param region the region (e.g. us-east-1) to use for signing. A
* null value indicates to use the AWS_REGION environment
* variable, or the "aws.region" system property to configure it.
*/
public SigV4AuthProvider(@NotNull AwsCredentialsProvider credentialsProvider, final String region) {
this.credentialsProvider = credentialsProvider;
if (region == null) {
this.signingRegion = getDefaultRegion();
} else {
this.signingRegion = region.toLowerCase();
}
if (this.signingRegion == null) {
throw new IllegalStateException(
"A region must be specified by constructor, AWS_REGION env variable, or aws.region system property"
);
}
}
@Override
public Authenticator newAuthenticator(EndPoint endPoint, String authenticator)
throws AuthenticationException {
return new SigV4Authenticator();
}
@Override
public void onMissingChallenge(EndPoint endPoint) {
throw new AuthenticationException(endPoint, "SigV4 requires a challenge from the endpoint. None was sent");
}
@Override
public void close() {
// We do not open any resources, so this is a NOOP
}
/**
* This authenticator performs SigV4 MCS authentication.
*/
public class SigV4Authenticator implements Authenticator {
@Override
public CompletionStage<ByteBuffer> initialResponse() {
return CompletableFuture.completedFuture(SIGV4_INITIAL_RESPONSE);
}
@Override
public CompletionStage<ByteBuffer> evaluateChallenge(ByteBuffer challenge) {
try {
byte[] nonce = extractNonce(challenge);
Instant requestTimestamp = Instant.now();
AwsCredentials credentials = credentialsProvider.resolveCredentials();
String signature = generateSignature(nonce, requestTimestamp, credentials);
String response =
String.format("signature=%s,access_key=%s,amzdate=%s",
signature,
credentials.accessKeyId(),
timestampFormatter.format(requestTimestamp));
if (credentials instanceof AwsSessionCredentials) {
response = response + ",session_token=" + ((AwsSessionCredentials)credentials).sessionToken();
}
return CompletableFuture.completedFuture(ByteBuffer.wrap(response.getBytes(StandardCharsets.UTF_8)));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("This platform does not support the UTF-8encoding", e);
}
}
@Override
public CompletionStage<Void> onAuthenticationSuccess(ByteBuffer token) {
return CompletableFuture.completedFuture(null);
}
}
/**
* Extracts the nonce value from the challenge
*/
static byte[] extractNonce(ByteBuffer challengeBuffer) {
byte[] challenge = new byte[challengeBuffer.remaining()];
challengeBuffer.get(challenge);
int nonceStart = indexOf(challenge, NONCE_KEY);
if (nonceStart == -1) {
throw new IllegalArgumentException("Did not find nonce in SigV4 challenge: "
+ new String(challenge, StandardCharsets.UTF_8));
}
// We'll start extraction right after the nonce bytes
nonceStart += NONCE_KEY.length;
int nonceEnd = nonceStart;
// Advance until we find the comma or hit the end of input
while (nonceEnd < challenge.length && challenge[nonceEnd] != ',') {
nonceEnd++;
}
int nonceLength = nonceEnd - nonceStart;
if (nonceLength != EXPECTED_NONCE_LENGTH) {
throw new IllegalArgumentException("Expected a nonce of " + EXPECTED_NONCE_LENGTH
+ " bytes but received " + nonceLength);
}
return Arrays.copyOfRange(challenge, nonceStart, nonceEnd);
}
private String generateSignature(byte[] nonce, Instant requestTimestamp, AwsCredentials credentials) throws UnsupportedEncodingException {
String credentialScopeDate = Aws4SignerUtils.formatDateStamp(requestTimestamp.toEpochMilli());
String signingScope = String.format("%s/%s/%s/aws4_request", credentialScopeDate, signingRegion, CANONICAL_SERVICE);
String nonceHash = sha256Digest(nonce);
String canonicalRequest = canonicalizeRequest(credentials.accessKeyId(), signingScope, requestTimestamp, nonceHash);
String stringToSign = String.format("%s\n%s\n%s\n%s",
SignerConstant.AWS4_SIGNING_ALGORITHM,
timestampFormatter.format(requestTimestamp),
signingScope,
sha256Digest(canonicalRequest));
byte[] signingKey = getSignatureKey(credentials.secretAccessKey(),
credentialScopeDate,
signingRegion,
CANONICAL_SERVICE);
byte[] signature = hmacSHA256(stringToSign, signingKey);
return Hex.encodeHexString(signature, true);
}
private static final String AMZ_ALGO_HEADER = "X-Amz-Algorithm=" + SignerConstant.AWS4_SIGNING_ALGORITHM;
private static final String AMZ_EXPIRES_HEADER = "X-Amz-Expires=900";
private static String canonicalizeRequest(String accessKey,
String signingScope,
Instant requestTimestamp,
String payloadHash) throws UnsupportedEncodingException {
List<String> queryStringHeaders =
Arrays.asList(
AMZ_ALGO_HEADER,
String.format("X-Amz-Credential=%s%%2F%s",
accessKey,
URLEncoder.encode(signingScope, StandardCharsets.UTF_8.name())),
"X-Amz-Date=" + URLEncoder.encode(timestampFormatter.format(requestTimestamp), StandardCharsets.UTF_8.name()),
AMZ_EXPIRES_HEADER
);
// IMPORTANT: This list must maintain alphabetical order for canonicalization
Collections.sort(queryStringHeaders);
String queryString = String.join("&", queryStringHeaders);
return String.format("PUT\n/authenticate\n%s\nhost:%s\n\nhost\n%s",
queryString, CANONICAL_SERVICE, payloadHash);
}
static String sha256Digest(byte[] bytes) {
try {
final MessageDigest md = MessageDigest.getInstance("SHA-256");
return Hex.encodeHexString(md.digest(bytes), true);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("This platform does not support the SHA-256 digest algorithm", e);
}
}
static String sha256Digest(String input) {
return sha256Digest(input.getBytes(StandardCharsets.UTF_8));
}
// Taken from https://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-java
private static final String HMAC_ALGORITHM = "hmacSHA256";
static byte[] hmacSHA256(String data, byte[] key) {
try {
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException("Failure computing HMAC-SHA256", e);
}
}
static byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) {
byte[] kSecret = ("AWS4" + key).getBytes(StandardCharsets.UTF_8);
byte[] kDate = hmacSHA256(dateStamp, kSecret);
byte[] kRegion = hmacSHA256(regionName, kDate);
byte[] kService = hmacSHA256(serviceName, kRegion);
byte[] kSigning = hmacSHA256("aws4_request", kService);
return kSigning;
}
/*
* Java does not natively provide a method for locating one array
* within another, so we provide that here. While other libraries
* also provide this, we want to minimize the dependencies that
* this plugin brings in.
*/
static int indexOf(byte[] target, byte[] pattern) {
final int lastCheckIndex = target.length - pattern.length;
for (int i = 0; i <= lastCheckIndex; i++) {
if (pattern[0] == target[i]) {
int inner = 0;
int outer = i;
// A tight loop over target, comparing indices
for (; inner < pattern.length && pattern[inner] == target[outer];
inner++, outer++) {}
// If the inner loop reached the end of the pattern, then we have found the index
if (inner == pattern.length) {
return i;
}
}
}
// Loop exhaustion means we did not find it
return -1;
}
/**
* Creates a STS role credential provider
* @param roleArn The ARN of the role to assume
* @param stsRegion The region of the STS endpoint
* @return The STS role credential provider
*/
private static StsAssumeRoleCredentialsProvider createSTSRoleCredentialProvider(@NotNull String roleArn,
@NotNull String stsRegion) {
final String sessionName="keyspaces-session-"+System.currentTimeMillis();
StsClient stsClient = StsClient.builder()
.region(Region.of(stsRegion))
.build();
AssumeRoleRequest assumeRoleRequest=AssumeRoleRequest.builder()
.roleArn(roleArn)
.roleSessionName(sessionName)
.build();
return StsAssumeRoleCredentialsProvider.builder()
.stsClient(stsClient)
.refreshRequest(assumeRoleRequest)
.build();
}
/**
* Gets the default region for SigV4 if region is not provided.
* @return Default region
*/
private static String getDefaultRegion() {
DefaultAwsRegionProviderChain chain = new DefaultAwsRegionProviderChain();
return chain.getRegion().toString().toLowerCase();
}
}
| 9,087 |
0 | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-maven-sam-app/HelloWorldFunction/src/test/java | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-maven-sam-app/HelloWorldFunction/src/test/java/helloworld/AppTest.java | package helloworld;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AppTest {
@Test
public void successfulResponse() {
App app = new App();
APIGatewayProxyResponseEvent result = app.handleRequest(null, null);
assertEquals(result.getStatusCode().intValue(), 200);
assertEquals(result.getHeaders().get("Content-Type"), "application/json");
String content = result.getBody();
assertNotNull(content);
assertTrue(content.contains("\"message\""));
assertTrue(content.contains("\"hello world\""));
assertTrue(content.contains("\"location\""));
}
}
| 9,088 |
0 | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-maven-sam-app/HelloWorldFunction/src/main/java | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-maven-sam-app/HelloWorldFunction/src/main/java/helloworld/App.java | package helloworld;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
.withHeaders(headers);
try {
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
return response
.withStatusCode(200)
.withBody(output);
} catch (IOException e) {
return response
.withBody("{}")
.withStatusCode(500);
}
}
private String getPageContents(String address) throws IOException{
URL url = new URL(address);
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
| 9,089 |
0 | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-image-gradle-sam-app/HelloWorldFunction/src/test/java | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-image-gradle-sam-app/HelloWorldFunction/src/test/java/helloworld/AppTest.java | package helloworld;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AppTest {
@Test
public void successfulResponse() {
App app = new App();
APIGatewayProxyResponseEvent result = app.handleRequest(null, null);
assertEquals(result.getStatusCode().intValue(), 200);
assertEquals(result.getHeaders().get("Content-Type"), "application/json");
String content = result.getBody();
assertNotNull(content);
assertTrue(content.contains("\"message\""));
assertTrue(content.contains("\"hello world\""));
assertTrue(content.contains("\"location\""));
}
}
| 9,090 |
0 | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-image-gradle-sam-app/HelloWorldFunction/src/main/java | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-image-gradle-sam-app/HelloWorldFunction/src/main/java/helloworld/App.java | package helloworld;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
.withHeaders(headers);
try {
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
return response
.withStatusCode(200)
.withBody(output);
} catch (IOException e) {
return response
.withBody("{}")
.withStatusCode(500);
}
}
private String getPageContents(String address) throws IOException{
URL url = new URL(address);
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
| 9,091 |
0 | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-gradle-sam-app/HelloWorldFunction/src/test/java | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-gradle-sam-app/HelloWorldFunction/src/test/java/helloworld/AppTest.java | package helloworld;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AppTest {
@Test
public void successfulResponse() {
App app = new App();
APIGatewayProxyResponseEvent result = app.handleRequest(null, null);
assertEquals(result.getStatusCode().intValue(), 200);
assertEquals(result.getHeaders().get("Content-Type"), "application/json");
String content = result.getBody();
assertNotNull(content);
assertTrue(content.contains("\"message\""));
assertTrue(content.contains("\"hello world\""));
assertTrue(content.contains("\"location\""));
}
}
| 9,092 |
0 | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-gradle-sam-app/HelloWorldFunction/src/main/java | Create_ds/aws-toolkit-vscode/src/testFixtures/workspaceFolder/java11-plain-gradle-sam-app/HelloWorldFunction/src/main/java/helloworld/App.java | package helloworld;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
.withHeaders(headers);
try {
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
return response
.withStatusCode(200)
.withBody(output);
} catch (IOException e) {
return response
.withBody("{}")
.withStatusCode(500);
}
}
private String getPageContents(String address) throws IOException{
URL url = new URL(address);
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
| 9,093 |
0 | Create_ds/mavericks/mvrx-common/src/main/java/com/airbnb | Create_ds/mavericks/mvrx-common/src/main/java/com/airbnb/mvrx/MavericksTestOverrides.java | package com.airbnb.mvrx;
@InternalMavericksApi
public class MavericksTestOverrides {
/**
* This should only be set by the MavericksTestRule from the mavericks-testing artifact.
* <p>
* This can be used to force MavericksViewModels to disable lifecycle aware observer for unit testing.
* This is Java so it can be package private.
*/
public static Boolean FORCE_DISABLE_LIFECYCLE_AWARE_OBSERVER = false;
static boolean FORCE_SYNCHRONOUS_STATE_STORES = false;
}
| 9,094 |
0 | Create_ds/mavericks/mvrx-testing/src/main/kotlin/com/airbnb | Create_ds/mavericks/mvrx-testing/src/main/kotlin/com/airbnb/mvrx/MvRxTestOverridesProxy.java | package com.airbnb.mvrx;
/**
* Used as a proxy between {@link com.airbnb.mvrx.test.MavericksTestRule} and Mavericks.
* this is Java because the flag is package private.
*/
@InternalMavericksApi
public class MvRxTestOverridesProxy {
public static void forceDisableLifecycleAwareObserver(Boolean disableLifecycleAwareObserver) {
MavericksTestOverrides.FORCE_DISABLE_LIFECYCLE_AWARE_OBSERVER = disableLifecycleAwareObserver;
}
}
| 9,095 |
0 | Create_ds/mavericks/mvrx-mocking/src/test/kotlin/com/airbnb/mvrx | Create_ds/mavericks/mvrx-mocking/src/test/kotlin/com/airbnb/mvrx/mocking/AutoValueClass.java | package com.airbnb.mvrx.mocking;
import com.google.auto.value.AutoValue;
@AutoValue
abstract class AutoValueClass {
abstract String name();
abstract int numberOfLegs();
static Builder builder() {
return new AutoValue_AutoValueClass.Builder();
}
@AutoValue.Builder
abstract static class Builder {
abstract Builder setName(String value);
abstract Builder setNumberOfLegs(int value);
abstract AutoValueClass build();
}
}
| 9,096 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/OfferRejectionsTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.fenzo;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class OfferRejectionsTest {
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
private TaskScheduler getScheduler(
long offerExpirySecs, final long leaseReOfferDelaySecs,
int maxOffersToReject,
final BlockingQueue<VirtualMachineLease> offersQ,
final Func1<String, VirtualMachineLease> offerGenerator
) {
return new TaskScheduler.Builder()
.withLeaseRejectAction(
new Action1<VirtualMachineLease>() {
@Override
public void call(final VirtualMachineLease virtualMachineLease) {
executorService.schedule(
new Runnable() {
@Override
public void run() {
offersQ.offer(offerGenerator.call(virtualMachineLease.hostname()));
}
},
leaseReOfferDelaySecs, TimeUnit.SECONDS);
}
}
)
.withLeaseOfferExpirySecs(offerExpirySecs)
.withMaxOffersToReject(maxOffersToReject)
.build();
}
// Test that offers are being rejected by scheduler based on configured offer expiry
@Test
public void testOffersAreRejected() throws Exception {
final BlockingQueue<VirtualMachineLease> offers = new LinkedBlockingQueue<>();
long offerExpirySecs=2;
long leaseReOfferDelaySecs=1;
final AtomicInteger offersGenerated = new AtomicInteger(0);
final TaskScheduler scheduler = getScheduler(
offerExpirySecs, leaseReOfferDelaySecs, 4, offers,
new Func1<String, VirtualMachineLease>() {
@Override
public VirtualMachineLease call(String s) {
offersGenerated.incrementAndGet();
return LeaseProvider.getLeaseOffer(s, 4, 4000, 1, 10);
}
}
);
for(int i=0; i<3; i++)
offers.offer(LeaseProvider.getLeaseOffer("host" + i, 4, 4000, 1, 10));
for(int i=0; i<offerExpirySecs+leaseReOfferDelaySecs+2; i++) {
List<VirtualMachineLease> newOffers = new ArrayList<>();
offers.drainTo(newOffers);
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), newOffers);
Thread.sleep(1000);
}
Assert.assertTrue("No offer rejections occured", offersGenerated.get()>0);
}
// test that not more than configured number of offers are rejected per configured offer expiry time interval
@Test
public void testOffersRejectLimit() throws Exception {
final BlockingQueue<VirtualMachineLease> offers = new LinkedBlockingQueue<>();
long offerExpirySecs=3;
long leaseReOfferDelaySecs=2;
int maxOffersToReject=2;
int numHosts=10;
final AtomicInteger offersGenerated = new AtomicInteger(0);
final TaskScheduler scheduler = getScheduler(
offerExpirySecs, leaseReOfferDelaySecs, maxOffersToReject, offers,
new Func1<String, VirtualMachineLease>() {
@Override
public VirtualMachineLease call(String s) {
offersGenerated.incrementAndGet();
return LeaseProvider.getLeaseOffer(s, 4, 4000, 1, 10);
}
}
);
for(int i=0; i<numHosts; i++)
offers.offer(LeaseProvider.getLeaseOffer("host" + i, 4, 4000, 1, 10));
for(int i=0; i<2*(offerExpirySecs+leaseReOfferDelaySecs+2); i++) {
List<VirtualMachineLease> newOffers = new ArrayList<>();
offers.drainTo(newOffers);
final SchedulingResult result = scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), newOffers);
int minIdleHosts = numHosts-maxOffersToReject;
Assert.assertTrue("Idle #hosts should be >= " + minIdleHosts + ", but is " + result.getIdleVMsCount(),
result.getIdleVMsCount() >= minIdleHosts);
Thread.sleep(500);
}
Assert.assertTrue("Never rejected any offers", offersGenerated.get()>0);
}
// Test that an offer that is on a host that has another task running form before is considered for expiring.
@Test
public void testPartialOfferReject() throws Exception {
long offerExpirySecs=3;
long leaseReOfferDelaySecs=2;
int maxOffersToReject=3;
int numHosts=3;
final ConcurrentMap<String, String> hostsRejectedFrom = new ConcurrentHashMap<>();
final TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseRejectAction(
new Action1<VirtualMachineLease>() {
@Override
public void call(final VirtualMachineLease virtualMachineLease) {
hostsRejectedFrom.putIfAbsent(virtualMachineLease.hostname(), virtualMachineLease.hostname());
}
}
)
.withLeaseOfferExpirySecs(offerExpirySecs)
.withMaxOffersToReject(maxOffersToReject)
.build();
final SchedulingResult result = scheduler.scheduleOnce(
Collections.singletonList(TaskRequestProvider.getTaskRequest(1, 1000, 1)),
Collections.singletonList(LeaseProvider.getLeaseOffer("host0", 4, 4000, 1, 10))
);
final Map<String, VMAssignmentResult> resultMap = result.getResultMap();
Assert.assertEquals(1, resultMap.size());
final TaskRequest taskRequest = resultMap.values().iterator().next().getTasksAssigned().iterator().next().getRequest();
scheduler.getTaskAssigner().call(taskRequest, "host0");
final String assignedHost = result.getResultMap().keySet().iterator().next();
final VirtualMachineLease consumedLease = LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next());
List<VirtualMachineLease> leases = new ArrayList<>();
// add back offer with remaining resources on first host
leases.add(consumedLease);
// add new offers from rest of the hosts
for(int i=1; i<numHosts; i++)
leases.add(LeaseProvider.getLeaseOffer("host" + i, 4, 4000, 1, 10));
for(int i=0; i<(offerExpirySecs+leaseReOfferDelaySecs); i++) {
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), leases);
leases.clear();
Thread.sleep(1000L);
}
System.out.println("assigned hosts: " + assignedHost + ", rejectedFrom: " + hostsRejectedFrom);
Assert.assertTrue(hostsRejectedFrom.containsKey(assignedHost));
}
// test that an expired lease doesn't get used for allocation to a task
@Test
public void testExpiryOfLease() throws Exception {
final AtomicInteger expireCount = new AtomicInteger();
final TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
expireCount.incrementAndGet();
}
})
.withLeaseOfferExpirySecs(1000000)
.build();
final VirtualMachineLease lease1 = LeaseProvider.getLeaseOffer("host1", 2, 2000, 1, 10);
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), Collections.singletonList(lease1));
Thread.sleep(100);
scheduler.expireLease(lease1.getId());
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(2, 1000, 1));
final SchedulingResult result = scheduler.scheduleOnce(tasks, Collections.<VirtualMachineLease>emptyList());
Assert.assertEquals(0, result.getResultMap().size());
}
// test that offers are rejected based on time irrespective of how many offers are outstanding.
@Test
public void testTimedOfferRejects() throws Exception {
final AtomicInteger expireCount = new AtomicInteger();
final int leaseExpirySecs=2;
final TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
expireCount.incrementAndGet();
}
})
.withLeaseOfferExpirySecs(leaseExpirySecs)
.withRejectAllExpiredOffers()
.build();
final int nLeases=100;
List<VirtualMachineLease> leases = LeaseProvider.getLeases(nLeases, 4, 4000, 1, 10);
for(int i=0; i<leaseExpirySecs; i++) {
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), leases);
leases.clear();
Thread.sleep(1000);
}
leases = LeaseProvider.getLeases(nLeases, nLeases, 4, 4000, 1, 10);
for(int i=0; i<leaseExpirySecs-1; i++) {
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), leases);
leases.clear();
Thread.sleep(1000);
}
Assert.assertEquals(nLeases, expireCount.get());
for(int i=0; i<2; i++) {
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), leases);
leases.clear();
Thread.sleep(1000);
}
Assert.assertEquals(nLeases*2, expireCount.get());
}
// test that all offers of a VM are rejected when one of them expires
@Test
public void testRejectAllOffersOfVm() throws Exception {
final AtomicInteger expireCount = new AtomicInteger();
final int leaseExpirySecs=2;
final Set<String> hostsRejectedFrom = new HashSet<>();
final AtomicBoolean gotReject = new AtomicBoolean();
final TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseRejectAction(virtualMachineLease -> {
expireCount.incrementAndGet();
hostsRejectedFrom.add(virtualMachineLease.hostname());
gotReject.set(true);
})
.withLeaseOfferExpirySecs(leaseExpirySecs)
.withMaxOffersToReject(1)
.build();
final int nhosts = 2;
List<VirtualMachineLease> leases = LeaseProvider.getLeases(nhosts, 4, 4000, 1, 10);
// add the same leases with same hostnames twice again, so there are 3 offers for each of the nHosts.
leases.addAll(LeaseProvider.getLeases(nhosts, 4, 4000, 1, 10));
leases.addAll(LeaseProvider.getLeases(nhosts, 4, 4000, 1, 10));
for (int i=0; i<leaseExpirySecs+2 && !gotReject.get(); i++) {
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), leases);
leases.clear();
Thread.sleep(1000);
}
Assert.assertEquals(3, expireCount.get());
Assert.assertEquals(1, hostsRejectedFrom.size());
}
}
| 9,097 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/VMCollectionTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.fenzo;
import com.netflix.fenzo.functions.Action1;
import org.apache.mesos.Protos;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.junit.Assert.*;
public class VMCollectionTest {
private final Map<String, Protos.Attribute> attributes1 = new HashMap<>();
private final Map<String, Protos.Attribute> activeVmAttribute1 = new HashMap<>();
private final Map<String, Protos.Attribute> activeVmAttribute2 = new HashMap<>();
private final List<VirtualMachineLease.Range> ports = new ArrayList<>();
private final String attributeVal1 = "4cores";
private final String vmAttrVal1 = "val1";
private final String vmAttrVal2 = "val2";
private final String activeAttr = "Asg";
@Before
public void setUp() throws Exception {
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(activeAttr)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(attributeVal1)).build();
attributes1.put(AutoScalerTest.hostAttrName, attribute);
Protos.Attribute vmAttr1 = Protos.Attribute.newBuilder().setName(activeAttr)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(vmAttrVal1)).build();
activeVmAttribute1.put(activeAttr, vmAttr1);
activeVmAttribute1.put(AutoScalerTest.hostAttrName, attribute);
Protos.Attribute vmAttr2 = Protos.Attribute.newBuilder().setName(activeAttr)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(vmAttrVal2)).build();
activeVmAttribute2.put(activeAttr, vmAttr2);
activeVmAttribute2.put(AutoScalerTest.hostAttrName, attribute);
ports.add(new VirtualMachineLease.Range(1, 100));
}
@Test
public void clonePseudoVMsForGroups() throws Exception {
AutoScaleRule rule = getAutoScaleRule(attributeVal1, 4);
Action1<VirtualMachineLease> leaseRejectAction = l -> {};
final ConcurrentMap<String, String> vmIdTohostNames = new ConcurrentHashMap<>();
final ConcurrentMap<String, String> leasesToHostnames = new ConcurrentHashMap<>();
final Map<String, AssignableVirtualMachine> avms = new HashMap<>();
final TaskTracker taskTracker = new TaskTracker();
VMCollection vms = createVmCollection(vmIdTohostNames, leasesToHostnames, taskTracker, avms);
for (int i=0; i < rule.getMaxSize()-1; i++) {
vms.addLease(LeaseProvider.getLeaseOffer("host"+i, 4, 4000,
0, 0, ports, attributes1, Collections.singletonMap("GPU", 1.0)));
}
for (AssignableVirtualMachine avm: avms.values())
avm.updateCurrTotalLease();
final Map<String, List<String>> map = vms.clonePseudoVMsForGroups(
Collections.singletonMap(rule.getRuleName(), 6), s -> rule,
lease -> true
);
Assert.assertNotNull(map);
Assert.assertEquals(1, map.size());
Assert.assertEquals(rule.getRuleName(), map.keySet().iterator().next());
Assert.assertEquals(1, map.values().iterator().next().size());
}
@Test
public void testWithInactiveAgents() throws Exception {
AutoScaleRule rule = getAutoScaleRule(attributeVal1, 4);
final ConcurrentMap<String, String> vmIdTohostNames = new ConcurrentHashMap<>();
final ConcurrentMap<String, String> leasesToHostnames = new ConcurrentHashMap<>();
final Map<String, AssignableVirtualMachine> avms = new HashMap<>();
TaskTracker taskTracker = new TaskTracker();
VMCollection vms = createVmCollection(vmIdTohostNames, leasesToHostnames, taskTracker, avms);
// create leases for ruleMax-2 VMs for each of vmAttrVal1 and vmAttrVal2
for (int i=0; i<rule.getMaxSize()-2; i++) {
vms.addLease(LeaseProvider.getLeaseOffer("host-a1-"+i, 4, 4000, 0, 0,
ports, activeVmAttribute1, Collections.singletonMap("GPU", 1.0)));
vms.addLease(LeaseProvider.getLeaseOffer("host-a2-"+i, 4, 4000, 0, 0,
ports, activeVmAttribute2, Collections.singletonMap("GPU", 1.0)));
}
for (AssignableVirtualMachine avm: avms.values())
avm.updateCurrTotalLease();
final Map<String, List<String>> map = vms.clonePseudoVMsForGroups(
Collections.singletonMap(rule.getRuleName(), 7), s -> rule,
lease -> {
System.out.println("Comparing " + vmAttrVal2 + " with " + lease.getAttributeMap().get(activeAttr).getText().getValue());
return vmAttrVal2.equals(lease.getAttributeMap().get(activeAttr).getText().getValue());
}
);
Assert.assertNotNull(map);
Assert.assertEquals(1, map.size());
Assert.assertEquals(2, map.values().iterator().next().size());
for (String h: map.values().iterator().next()) {
final AssignableVirtualMachine avm = avms.get(h);
Assert.assertNotNull(avm);
avm.updateCurrTotalLease();
final String attrValue = avm.getAttrValue(activeAttr);
Assert.assertTrue("Invalid to get host " + h + " with attrVal " + attrValue,
vmAttrVal2.equals(attrValue));
}
}
private VMCollection createVmCollection(ConcurrentMap<String, String> vmIdTohostNames,
ConcurrentMap<String, String> leasesToHostnames, TaskTracker taskTracker,
Map<String, AssignableVirtualMachine> avms) {
Action1<VirtualMachineLease> leaseRejectAction = l -> {};
return new VMCollection(s -> {
AssignableVirtualMachine avm = new AssignableVirtualMachine(
DefaultPreferentialNamedConsumableResourceEvaluator.INSTANCE,
vmIdTohostNames,
leasesToHostnames,
s,
leaseRejectAction,
2,
taskTracker,
false
);
avms.put(s, avm);
return avm;
}, AutoScalerTest.hostAttrName);
}
private AutoScaleRule getAutoScaleRule(final String name, final int maxSize) {
return new AutoScaleRule() {
@Override
public String getRuleName() {
return name;
}
@Override
public int getMinIdleHostsToKeep() {
return 0;
}
@Override
public int getMaxIdleHostsToKeep() {
return 0;
}
@Override
public int getMaxSize() {
return maxSize;
}
@Override
public long getCoolDownSecs() {
return 1;
}
@Override
public boolean idleMachineTooSmall(VirtualMachineLease lease) {
return false;
}
};
}
} | 9,098 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/TestLotsOfTasks.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.fenzo;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* A crude sample that tests Fenzo assignment speed with lots of mocked hosts and lots of tasks that are iteratively
* assigned in batches, like how a real world system may get tasks submitted routinely. Quantities that can be varied
* in the code include number of hosts, number of CPUs per host, number of tasks to assign per iteration, and Fenzo's
* "fitness good enough" value. The main() method creates the hosts' offers (mocked) and enough tasks to fill all of
* the hosts. It creates tasks of three different kinds - 1, single cpu task, tasks asking for half the number of total
* CPUs per host, and tasks asking for 0.75 times the number of CPUs per host. Then, it iteratively assigns resources
* to "batch" number of tasks until all tasks have been tried for assignment. At the end, it prints the average time
* taken for each batch's assignment in Fenzo. It "primes" the assignment routine by not including the time taken for
* the first few iterations. Also, it prints how many tasks were not assigned any resources and the
* total fill/utilization of the resources. Because of the way tasks may get assigned resources and the fitness strategy
* used, the utilization may not be 100%.
*/
public class TestLotsOfTasks {
private int numHosts;
private int numCores;
private double memory;
private List<TaskRequest> getTasks() {
// Add some single-core, some half machine sized, and some three-quarters machine sized tasks
List<TaskRequest> requests = new ArrayList<>();
double fractionSingleCore=0.2;
double fractionHalfSized=0.4;
double fractionThreeQuarterSized = 1.0 - fractionHalfSized - fractionSingleCore;
int numCoresUsed=0;
for(int t=0; t<numHosts*numCores*fractionSingleCore; t++, numCoresUsed++)
requests.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
System.out.println("numCoresRequested=" + numCoresUsed);
for(int t=0; t<(numCores*numHosts*fractionHalfSized/(numCores/2)); t++) {
requests.add(TaskRequestProvider.getTaskRequest(numCores/2, numCores*1000/2, 1));
numCoresUsed += numCores/2;
}
System.out.println("numCoresRequested=" + numCoresUsed);
for(int t=0; t<(numCores*numHosts*fractionThreeQuarterSized/(numCores*0.75)); t++) {
requests.add(TaskRequestProvider.getTaskRequest(numCores*0.75, numCores*1000*0.75, 1));
numCoresUsed += numCores*0.75;
}
// fill remaining cores with single-core tasks to get 100% potential utilization
System.out.println("#Tasks=" + requests.size() + ", numCoresRequested=" + numCoresUsed + " of possible " + (numCores*numHosts));
for(int t=0; t<(numCores*numHosts-numCoresUsed); t++)
requests.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
List<TaskRequest> result = new ArrayList<>();
// randomly add into result from requests
for(int i=0; i<20; i++) {
Iterator<TaskRequest> iterator = requests.iterator();
while(iterator.hasNext()) {
if((int)(Math.random()*10) % 2 == 0) {
result.add(iterator.next());
iterator.remove();
}
else
iterator.next();
}
}
// add all remaining tasks
result.addAll(requests);
return result;
}
private List<VirtualMachineLease> getLeases() {
return LeaseProvider.getLeases(numHosts, numCores, memory, 1, 10);
}
private static final double GOOD_ENOUGH_FITNESS=0.5;
// Results looks like this;
//
// ------------------------------------------------------------------------------------
// | Fitness | #Hosts | #CPUs | #tasks to assign | Avg mSecs | Utilization % |
// | Good Enough | | per host | per scheduling run | per run | |
// ------------------------------------------------------------------------------------
// | 0.01 | 10,000 | 8 | 200 | 58 | 97.14 |
// | 0.1 | 10,000 | 8 | 200 | 56 | 97.19 |
// | 0.5 | 10,000 | 8 | 200 | 145 | 97.24 |
// | 1.0 | 10,000 | 8 | 200 | 246 | 97.11 |
// ------------------------------------------------------------------------------------
// | 0.01 | 2,000 | 8 | 200 | 31 | 97.09 |
// | 0.1 | 2,000 | 8 | 200 | 30 | 97.45 |
// | 0.5 | 2,000 | 8 | 200 | 35 | 97.00 |
// | 1.0 | 2,000 | 8 | 200 | 54 | 97.23 |
// ------------------------------------------------------------------------------------
// | 0.01 | 200 | 8 | 200 | 59 | 97.13 |
// | 0.1 | 200 | 8 | 200 | 57 | 97.00 |
// | 0.5 | 200 | 8 | 200 | 45 | 97.00 |
// | 1.0 | 200 | 8 | 200 | 58 | 96.50 |
// ------------------------------------------------------------------------------------
//
public static void main(String[] args) {
TaskScheduler scheduler = getTaskScheduler();
TestLotsOfTasks tester = new TestLotsOfTasks();
tester.numHosts=2000;
tester.numCores=16;
tester.memory=1000*tester.numCores;
List<TaskRequest> tasks = tester.getTasks();
List<VirtualMachineLease> leases = tester.getLeases();
test2(tester, scheduler, tasks, leases);
scheduler.shutdown();
System.out.println("ALL DONE");
}
private static void addToAsgmtMap(Map<String, List<TaskRequest>> theMap, String hostname, TaskRequest request) {
if(theMap.get(hostname)==null)
theMap.put(hostname, new ArrayList<TaskRequest>());
theMap.get(hostname).add(request);
}
private static void test2(TestLotsOfTasks tester, TaskScheduler scheduler, List<TaskRequest> tasks,
List<VirtualMachineLease> leases) {
// schedule 1 task first
int n=0;
double totalAssignedCpus=0.0;
Map<String, TaskRequest> jobIds = new HashMap<>();
Map<String, List<TaskRequest>> assignmentsMap = new HashMap<>();
for(TaskRequest r: tasks)
jobIds.put(r.getId(), r);
int totalNumAllocations=0;
SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks.subList(n++, n), leases);
totalNumAllocations += schedulingResult.getNumAllocations();
VMAssignmentResult assignmentResult = schedulingResult.getResultMap().values().iterator().next();
TaskAssignmentResult taskAssignmentResult = assignmentResult.getTasksAssigned().iterator().next();
TaskRequest request = taskAssignmentResult.getRequest();
if(jobIds.remove(request.getId()) == null)
System.err.println(" Removed " + request.getId() + " already!");
else
totalAssignedCpus += request.getCPUs();
addToAsgmtMap(assignmentsMap, assignmentResult.getHostname(), request);
//System.out.println(assignmentResult.getHostname() + " : " + request.getId());
scheduler.getTaskAssigner().call(request, assignmentResult.getHostname());
VirtualMachineLease consumedLease = LeaseProvider.getConsumedLease(assignmentResult.getLeasesUsed().iterator().next(), request.getCPUs(),
request.getMemory(), taskAssignmentResult.getAssignedPorts());
for(int i=0; i<4; i++) {
leases.clear();
if(consumedLease.cpuCores()>0.0 && consumedLease.memoryMB()>0.0)
leases.add(consumedLease);
schedulingResult = scheduler.scheduleOnce(tasks.subList(n++, n), leases);
totalNumAllocations += schedulingResult.getNumAllocations();
assignmentResult = schedulingResult.getResultMap().values().iterator().next();
taskAssignmentResult = assignmentResult.getTasksAssigned().iterator().next();
request = taskAssignmentResult.getRequest();
if(jobIds.remove(request.getId()) == null)
System.err.println(" Removed " + request.getId() + " already!");
else
totalAssignedCpus += request.getCPUs();
addToAsgmtMap(assignmentsMap, assignmentResult.getHostname(), request);
//System.out.println(assignmentResult.getHostname() + " : " + request.getId());
scheduler.getTaskAssigner().call(request, assignmentResult.getHostname());
consumedLease = LeaseProvider.getConsumedLease(assignmentResult.getLeasesUsed().iterator().next(),
request.getCPUs(), request.getMemory(), taskAssignmentResult.getAssignedPorts());
}
int tasksLeft = tasks.size() - n;
//System.out.println("#Tasks left = " + tasksLeft);
long max=0;
long min=0;
double sum=0.0;
int numIters=0;
int totalTasksAssigned=n;
leases.clear();
if(consumedLease.cpuCores()>0.0 && consumedLease.memoryMB()>0.0)
leases.add(consumedLease);
long st = 0;
long totalTime=0;
int batchSize=200;
boolean first=true;
String lastJobId="-1";
while(n < tasks.size()) {
numIters++;
int until = Math.min(n + batchSize, tasks.size());
st = System.currentTimeMillis();
//System.out.println(n + " -> " + until);
schedulingResult = scheduler.scheduleOnce(tasks.subList(n, until), leases);
totalNumAllocations += schedulingResult.getNumAllocations();
leases.clear();
int assigned=0;
for(VMAssignmentResult result: schedulingResult.getResultMap().values()) {
double usedCpus=0.0;
double usedMem=0.0;
List<Integer> portsUsed = new ArrayList<>();
for(TaskAssignmentResult t: result.getTasksAssigned()) {
if(jobIds.remove(t.getRequest().getId()) == null)
System.err.println(" Removed " + t.getRequest().getId() + " already!");
lastJobId = t.getRequest().getId();
addToAsgmtMap(assignmentsMap, result.getHostname(), t.getRequest());
assigned++;
scheduler.getTaskAssigner().call(t.getRequest(), result.getHostname());
totalAssignedCpus += t.getRequest().getCPUs();
usedCpus += t.getRequest().getCPUs();
usedMem += t.getRequest().getMemory();
portsUsed.addAll(t.getAssignedPorts());
// StringBuffer buf = new StringBuffer(" host " + result.getHostname() + " task " + t.getTaskId() + " ports: ");
// for(Integer p: t.getAssignedPorts())
// buf.append(""+p).append(", ");
// System.out.println(buf.toString());
}
consumedLease = LeaseProvider.getConsumedLease(result);
if(consumedLease.cpuCores()>0.0 && consumedLease.memoryMB()>0.0)
leases.add(consumedLease);
}
//printResourceStatus(scheduler.getResourceStatus());
long delta = System.currentTimeMillis()-st;
//System.out.println(" delta = " + delta);
if(first)
first=false; // skip time measurements the first time
else {
totalTime += delta;
if(delta>max)
max=delta;
if(min==0.0 || min>delta)
min = delta;
}
//System.out.println(assigned + " of " + (until-n) + " tasks assigned using " + allocationsCounter.get() + " allocations");
totalTasksAssigned += assigned;
n = until;
}
System.out.printf("Scheduling time total=%d, avg=%8.2f (min=%d, max=%d) from %d iterations of %d tasks each\n",
totalTime, ((double) totalTime / Math.max(1, (numIters - 1))), min, max, numIters-1, batchSize);
System.out.println("Total tasks assigned: " + totalTasksAssigned + " of " + tasks.size()
+ " total #allocations=" + totalNumAllocations);
System.out.println("Total CPUs assigned = " + totalAssignedCpus);
int numHosts=0;
double ununsedMem=0.0;
double unusedCpus=0.0;
for(Map.Entry<String, Map<VMResource, Double[]>> entry: scheduler.getResourceStatus().entrySet()) {
numHosts++;
StringBuilder buf = new StringBuilder(" host ").append(entry.getKey()).append(": ");
boolean hasAvailCpu=true;
boolean hasAvailMem=true;
for(Map.Entry<VMResource, Double[]> resourceEntry: entry.getValue().entrySet()) {
switch (resourceEntry.getKey()) {
case CPU:
if(resourceEntry.getValue()[0]<tester.numCores) {
hasAvailCpu=false;
unusedCpus += tester.numCores-resourceEntry.getValue()[0];
}
break;
case Memory:
if(resourceEntry.getValue()[0]<tester.numCores*1000) {
hasAvailMem=false;
ununsedMem += tester.numCores*1000 - resourceEntry.getValue()[0];
}
break;
}
buf.append(resourceEntry.getKey()).append(": used=").append(resourceEntry.getValue()[0])
.append(", available=").append(resourceEntry.getValue()[1]).append(",");
}
if(!hasAvailCpu || !hasAvailMem) {
//System.out.println(" " + buf);
// for(TaskRequest r: assignmentsMap.get(entry.getKey())) {
// System.out.println(" task " + r.getId() + " cpu=" + r.getCPUs() + ", mem=" + r.getMemory());
// }
}
}
double util = (double)(tester.numCores*tester.numHosts-unusedCpus)*100.0/(tester.numCores*tester.numHosts);
System.out.printf("Utilization: %5.2f%%\n", util);
if(!jobIds.isEmpty()) {
System.out.printf(" Unused CPUs=%d, Memory=%d\n", (int)unusedCpus, (int)ununsedMem);
System.out.println(" Unassigned tasks:");
for(Map.Entry<String, TaskRequest> entry: jobIds.entrySet()) {
System.out.println(" Task " + entry.getKey() + " cpu=" + entry.getValue().getCPUs()
+ ", mem=" + entry.getValue().getMemory());
}
}
System.out.println("Total numHosts=" + numHosts);
}
private static void printResourceStatus(Map<String, Map<VMResource, Double[]>> resourceStatus) {
System.out.println("*****************");
for(Map.Entry<String, Map<VMResource, Double[]>> hostResourceEntry: resourceStatus.entrySet()) {
for(Map.Entry<VMResource, Double[]> resourceEntry: hostResourceEntry.getValue().entrySet()) {
if(resourceEntry.getKey()==VMResource.CPU) {
System.out.printf(" %s: used %3.1f of %3.1f\n", hostResourceEntry.getKey(), resourceEntry.getValue()[0], resourceEntry.getValue()[1]);
}
}
}
}
private static void test1(TaskScheduler scheduler, List<TaskRequest> tasks, List<VirtualMachineLease> leases,
AtomicLong allocationsCounter) {
int numTasksAssigned=0;
int numHostsUsed=0;
// Map<String,VMAssignmentResult> resultMap = scheduler.scheduleOnce(tasks, leases).getResultMap();
// System.out.println("Used " + resultMap.size() + " hosts of " + leases.size());
// int n=0;
// for(VMAssignmentResult result: resultMap.values())
// n += result.getTasksAssigned().size();
// System.out.println("Assigned " + n + " tasks of " + tasks.size());
for(int i=0; i<5; i++) {
Map<String,VMAssignmentResult> resultMap = scheduler.scheduleOnce(tasks, leases).getResultMap();
numHostsUsed = resultMap.size();
numTasksAssigned=0;
for(VMAssignmentResult result: resultMap.values())
numTasksAssigned += result.getTasksAssigned().size();
}
long st = System.currentTimeMillis();
int numIters=10;
allocationsCounter.set(0);
for(int i=0; i<numIters; i++) {
SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
Map<String,VMAssignmentResult> resultMap = schedulingResult.getResultMap();
numHostsUsed = resultMap.size();
numTasksAssigned=0;
for(VMAssignmentResult result: resultMap.values())
numTasksAssigned += result.getTasksAssigned().size();
}
long en = System.currentTimeMillis();
System.out.printf("Took %8.2f mS per scheduling iteration over %d iteration\n", ((double)(en-st)/(double)numIters), numIters);
System.out.printf("Allocation trials per iteration: %6.2f\n", (double) allocationsCounter.get() / numIters);
System.out.println("numHosts used=" + numHostsUsed + " of " + leases.size());
System.out.println("numTasks assigned=" + numTasksAssigned + " of " + tasks.size());
}
private static TaskScheduler getTaskScheduler() {
return new TaskScheduler.Builder()
.withFitnessGoodEnoughFunction(new Func1<Double, Boolean>() {
@Override
public Boolean call(Double aDouble) {
return aDouble >= GOOD_ENOUGH_FITNESS;
}
})
.withFitnessCalculator(BinPackingFitnessCalculators.cpuBinPacker)
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
System.err.println("Unexpected to reject lease on " + lease.hostname());
}
})
.build();
}
private static class BinSpreader implements VMTaskFitnessCalculator {
private VMTaskFitnessCalculator binPacker = BinPackingFitnessCalculators.cpuMemBinPacker;
@Override
public String getName() {
return "Bin Spreader";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
return 1.0 - binPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
}
}
}
| 9,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.