Skip to content

Commit

Permalink
update mcsfunc
Browse files Browse the repository at this point in the history
  • Loading branch information
inada-s committed Apr 20, 2020
1 parent c2061c2 commit ad2c3bb
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 70 deletions.
8 changes: 8 additions & 0 deletions gdxsv/lbs_lobby.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,20 +59,28 @@ func NewLobby(app *Lbs, platform uint8, lobbyID uint16) *LbsLobby {
lobby.Rule.ReloadFlag = 1
case 10:
lobby.McsRegion = "asia-east1"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 11:
lobby.McsRegion = "asia-east2"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 12:
lobby.McsRegion = "asia-northeast1"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 13:
lobby.McsRegion = "asia-northeast2"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 14:
lobby.McsRegion = "australia-southeast1"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 15:
lobby.McsRegion = "europe-west3"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 16:
lobby.McsRegion = "us-central1"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 17:
lobby.McsRegion = "us-east1"
lobby.Comment = fmt.Sprintf("<B>%s<B><BR>%s<END>", lobby.McsRegion, gcpLocationName[lobby.McsRegion])
case 19:
lobby.Comment = "<B>ダメージレベル4<B><BR><B>DAMAGELEVEL4<END>"
lobby.Rule.DamageLevel = 3
Expand Down
55 changes: 25 additions & 30 deletions gdxsv/lbs_mcsfunc.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,31 @@ var (
mcsFuncRequestTime = map[string]time.Time{}
)

var gcpLocationName = map[string]string{
"asia-east1": "Changhua County, Taiwan",
"asia-east2": "Hong Kong",
"asia-northeast1": "Tokyo, Japan",
"asia-northeast2": "Osaka, Japan",
"asia-northeast3": "Seoul, South Korea",
"asia-south1": "Mumbai, India",
"asia-southeast1": "Jurong West, Singapore",
"australia-southeast1": "Sydney, Australia",
"europe-north1": "Hamina, Finland",
"europe-west1": "St. Ghislain, Belgium",
"europe-west2": "London, England, UK",
"europe-west3": "Frankfurt, Germany",
"europe-west4": "Eemshaven, Netherlands",
"europe-west6": "Zürich, Switzerland",
"northamerica-northeast1": "Montreal, Quebec, Canada",
"southamerica-east1": "Osasco (Sao Paulo), Brazil",
"us-central1": "Council Bluffs, Iowa, USA",
"us-east1": "Moncks Corner, South Carolina, USA",
"us-east4": "Ashburn, Northern Virginia, USA",
"us-west1": "The Dalles, Oregon, USA",
"us-west2": "Los Angeles, California, USA",
"us-west3": "Salt Lake City, Utah, USA",
}

func getMcsFuncClient() (*http.Client, error) {
if mcsFuncClientCache != nil && time.Since(mcsFuncClientCreated).Minutes() <= 30.0 {
return mcsFuncClientCache, nil
Expand Down Expand Up @@ -70,40 +95,10 @@ func McsFuncAlloc(region string) error {
}

func GoMcsFuncAlloc(region string) {

go func() {
err := McsFuncAlloc(region)
if err != nil {
glog.Error(err)
}
}()
}

func McsFuncList() error {
client, err := getMcsFuncClient()
if err != nil {
return err
}

resp, err := client.Get(conf.McsFuncURL + "/alloc?region=asia-northeast1")
if err != nil {
return err
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
glog.Info(string(body))
return nil
}

func GoMcsFuncList() {
go func() {
err := McsFuncList()
if err != nil {
glog.Error(err)
}
}()
}
1 change: 1 addition & 0 deletions infra/mcsfunc/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules/
gdxsv-service-key.json
87 changes: 47 additions & 40 deletions infra/mcsfunc/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ const gcpRegions = {
"us-west3": { "zones": ["a", "b", "c"], "location": "Salt Lake City, Utah, USA" },
}

const startupScript = `\
function getStartupScript(version) {
return `\
#!/bin/bash
apt-get update
Expand All @@ -46,45 +47,35 @@ function finish {
}
trap finish EXIT
readonly LATEST_TAG=$(curl -sL https://api.github.com/repos/inada-s/gdxsv/releases/latest | jq -r '.tag_name')
readonly DOWNLOAD_URL=$(curl -sL https://api.github.com/repos/inada-s/gdxsv/releases/latest | jq -r '.assets[].browser_download_url')
readonly VERSION=${version}
if [[ ! -d $LATEST_TAG/bin ]]; then
echo "Downloading latest version..."
mkdir -p $LATEST_TAG
pushd $LATEST_TAG
if [[ -z $VERSION || $VERSION == "latest" ]]; then
readonly TAG_NAME=$(curl -sL https://api.github.com/repos/inada-s/gdxsv/releases/latest | jq -r '.tag_name')
readonly DOWNLOAD_URL=$(curl -sL https://api.github.com/repos/inada-s/gdxsv/releases/latest | jq -r '.assets[].browser_download_url')
else
readonly TAG_NAME=$VERSION
readonly DOWNLOAD_URL=$(curl -sL https://api.github.com/repos/inada-s/gdxsv/releases/tags/$TAG_NAME | jq -r '.assets[].browser_download_url')
fi
if [[ ! -d $TAG_NAME/bin ]]; then
echo "Downloading $TAG_NAME"
mkdir -p $TAG_NAME
pushd $TAG_NAME
wget $DOWNLOAD_URL
tar xzvf bin.tgz && rm bin.tgz
popd
fi
export GDXSV_LOBBY_PUBLIC_ADDR="zdxsv.net:9876"
export GDXSV_BATTLE_ADDR=":9877"
export GDXSV_LOBBY_PUBLIC_ADDR=zdxsv.net:9876
export GDXSV_BATTLE_ADDR=:9877
export GDXSV_BATTLE_REGION=$(basename $(curl -s -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/zone))
export GDXSV_BATTLE_PUBLIC_ADDR="$(curl -s https://ipinfo.io/ip):9877"
$LATEST_TAG/bin/gdxsv -v=3 mcs
export GDXSV_BATTLE_PUBLIC_ADDR=$(curl -s https://ipinfo.io/ip):9877
$TAG_NAME/bin/gdxsv -v=3 mcs
EOF
chmod +x /home/ubuntu/launch-mcs.sh
su ubuntu -c 'cd /home/ubuntu && nohup ./launch-mcs.sh'
su ubuntu -c 'cd /home/ubuntu && nohup ./launch-mcs.sh >> gdxsv.log &'
`

const createMcsVMConfig = {
os: "ubuntu",
http: true,
tags: [ "gdxsv-mcs" ],
machineType: "g1-small",
scheduling: {
preemptible: true
},
metadata: {
items: [
{
key: "startup-script",
value: startupScript,
},
],
},
}

function forResponse(vm) {
Expand Down Expand Up @@ -121,7 +112,7 @@ exports.cloudFunctionEntryPoint = async (req, res) => {
const [vms] = await compute.getVMs({
autoPaginate: false,
maxResults: 100,
filter: "name eq gdxsv-mcs*",
filter: "name eq gdxsv-mcs.*",
});

const vmlist = [];
Expand All @@ -145,7 +136,7 @@ exports.cloudFunctionEntryPoint = async (req, res) => {
const [vms] = await compute.getVMs({
autoPaginate: false,
maxResults: 100,
filter: "name eq gdxsv-mcs*",
filter: "name eq gdxsv-mcs.*",
});

const vmlist = [];
Expand All @@ -164,7 +155,9 @@ exports.cloudFunctionEntryPoint = async (req, res) => {

if (req.url.startsWith("/alloc")) {
const region = query["region"];
const version = query["version"] ? query["version"] : "latest";
const regionInfo = gcpRegions[region];
const vmName = "gdxsv-mcs-" + region + "-" + version.replace(/\./g, "-")

if (!regionInfo) {
res.status(400).send('invalid region');
Expand All @@ -174,9 +167,8 @@ exports.cloudFunctionEntryPoint = async (req, res) => {
let [vms] = await compute.getVMs({
autoPaginate: false,
maxResults: 100,
filter: "name eq gdxsv-mcs*",
filter: "name eq " + vmName,
})
vms = vms.filter(vm => vm.metadata.zone.includes(region));

console.log("" + vms.length + "vms found.");

Expand All @@ -189,10 +181,12 @@ exports.cloudFunctionEntryPoint = async (req, res) => {

console.log("running vm not found");

for (let vm of vms.filter(vm => vm.metadata.status == "TERMINATED")){
for (let vm of vms.filter(vm => vm.metadata.status == "TERMINATED")) {
try {
console.log("starting vm...", vm);
let [operation] = await vm.setMetadata({ 'startup-script' : startupScript });
let [operation] = await vm.setMetadata({
'startup-script': getStartupScript(version),
});
await operation.promise();
[operation] = await vm.start();
await operation.promise();
Expand All @@ -215,18 +209,31 @@ exports.cloudFunctionEntryPoint = async (req, res) => {
try {
console.log("trying to create new vm in", zoneName);
const zone = compute.zone(zoneName);
const [vm, operation] = await zone.createVM("gdxsv-mcs", createMcsVMConfig);
const [vm, operation] = await zone.createVM(vmName, {
os: "ubuntu",
http: true,
tags: ["gdxsv-mcs"],
machineType: "g1-small",
scheduling: { preemptible: true },
metadata: {
items: [
{ key: "startup-script", value: getStartupScript(version) },
],
},
});

await operation.promise();
console.log("vm created");
[vm.metadata] = await vm.waitFor("RUNNING", { timeout: 30 });
const [metadata] = await vm.waitFor("RUNNING", { timeout: 30 });
vm.metadata = metadata
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(forResponse(vm), null, " "));
console.log("wait done");
return;
} catch (e) {
console.log(e);
continue;
}
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(forResponse(vm), null, " "));
return;
}

console.log('failed to allocate vm');
Expand Down

0 comments on commit ad2c3bb

Please sign in to comment.