...

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  	if err != nil {
    36  		return err
    37  	}
    38  	return nil
    39  }
    40  
    41  // InjectChaos injects jvm chaos to a java process
    42  func InjectChaos(host string, port int, body []byte) error {
    43  	url := fmt.Sprintf(InjectURL, host, port)
    44  	return httpPost(url, body)
    45  }
    46  
    47  // RecoverChaos recovers jvm chaos from a java process
    48  func RecoverChaos(host string, port int, body []byte) error {
    49  	url := fmt.Sprintf(RecoverURL, host, port)
    50  	return httpPost(url, body)
    51  }
    52  
    53  func httpPost(url string, body []byte) error {
    54  	client := &http.Client{}
    55  	reqBody := bytes.NewBuffer([]byte(body))
    56  	request, err := http.NewRequest("POST", url, reqBody)
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	request.Header.Set("Content-type", "application/json")
    62  	response, err := client.Do(request)
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	if response.StatusCode != 200 {
    68  		data, err := ioutil.ReadAll(response.Body)
    69  		if err != nil {
    70  			return err
    71  		}
    72  		return fmt.Errorf("jvm sandbox error response:%s", data)
    73  	}
    74  	return nil
    75  }
    76