...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/jvm/sandbox.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/jvm

     1  // Copyright 2020 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package jvm
    15  
    16  import (
    17  	"bytes"
    18  	"fmt"
    19  	"io/ioutil"
    20  	"net/http"
    21  )
    22  
    23  const (
    24  	BaseURL    = "http://%s:%d/sandbox/default/module/http/"
    25  	ActiveURL  = BaseURL + "sandbox-module-mgr/active?ids=chaosblade"
    26  	InjectURL  = BaseURL + "chaosblade/create"
    27  	RecoverURL = BaseURL + "chaosblade/destroy"
    28  )
    29  
    30  // ActiveSandbox activates sandboxes
    31  func ActiveSandbox(host string, port int) error {
    32  	url := fmt.Sprintf(ActiveURL, host, port)
    33  
    34  	_, err := http.Get(url)
    35  	return err
    36  }
    37  
    38  // InjectChaos injects jvm chaos to a java process
    39  func InjectChaos(host string, port int, body []byte) error {
    40  	url := fmt.Sprintf(InjectURL, host, port)
    41  	return httpPost(url, body)
    42  }
    43  
    44  // RecoverChaos recovers jvm chaos from a java process
    45  func RecoverChaos(host string, port int, body []byte) error {
    46  	url := fmt.Sprintf(RecoverURL, host, port)
    47  	return httpPost(url, body)
    48  }
    49  
    50  func httpPost(url string, body []byte) error {
    51  	client := &http.Client{}
    52  	reqBody := bytes.NewBuffer([]byte(body))
    53  	request, err := http.NewRequest("POST", url, reqBody)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	request.Header.Set("Content-type", "application/json")
    59  	response, err := client.Do(request)
    60  	if err != nil {
    61  		return err
    62  	}
    63  
    64  	if response.StatusCode != 200 {
    65  		data, err := ioutil.ReadAll(response.Body)
    66  		if err != nil {
    67  			return err
    68  		}
    69  		return fmt.Errorf("jvm sandbox error response:%s", data)
    70  	}
    71  	return nil
    72  }
    73