pluginManger.go 6.4 KB
Newer Older
LinuxSuRen's avatar
LinuxSuRen 已提交
1 2 3
package client

import (
LinuxSuRen's avatar
LinuxSuRen 已提交
4
	"bytes"
LinuxSuRen's avatar
LinuxSuRen 已提交
5
	"encoding/json"
LinuxSuRen's avatar
LinuxSuRen 已提交
6
	"fmt"
LinuxSuRen's avatar
LinuxSuRen 已提交
7
	"io"
LinuxSuRen's avatar
LinuxSuRen 已提交
8
	"io/ioutil"
LinuxSuRen's avatar
LinuxSuRen 已提交
9
	"log"
LinuxSuRen's avatar
LinuxSuRen 已提交
10
	"mime/multipart"
LinuxSuRen's avatar
LinuxSuRen 已提交
11
	"net/http"
LinuxSuRen's avatar
LinuxSuRen 已提交
12 13
	"os"
	"path/filepath"
LinuxSuRen's avatar
LinuxSuRen 已提交
14
	"strings"
LinuxSuRen's avatar
LinuxSuRen 已提交
15

LinuxSuRen's avatar
LinuxSuRen 已提交
16
	"github.com/jenkins-zh/jenkins-cli/util"
LinuxSuRen's avatar
LinuxSuRen 已提交
17 18 19 20 21 22
)

type PluginManager struct {
	JenkinsCore
}

LinuxSuRen's avatar
LinuxSuRen 已提交
23 24 25 26 27 28 29 30
type Plugin struct {
	Active       bool
	Enabled      bool
	Bundled      bool
	Downgradable bool
	Deleted      bool
}

LinuxSuRen's avatar
LinuxSuRen 已提交
31
// PluginList represent a list of plugins
LinuxSuRen's avatar
LinuxSuRen 已提交
32 33
type InstalledPluginList struct {
	Plugins []InstalledPlugin
LinuxSuRen's avatar
LinuxSuRen 已提交
34 35
}

LinuxSuRen's avatar
LinuxSuRen 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
type AvailablePluginList struct {
	Data   []AvailablePlugin
	Status string
}

type AvailablePlugin struct {
	Plugin

	// for the available list
	Name      string
	Installed bool
	Website   string
	Title     string
}

// InstalledPlugin represent the installed plugin from Jenkins
type InstalledPlugin struct {
	Plugin

	Enable             bool
LinuxSuRen's avatar
LinuxSuRen 已提交
56 57 58 59 60 61 62 63 64 65 66 67
	ShortName          string
	LongName           string
	Version            string
	URL                string
	HasUpdate          bool
	Pinned             bool
	RequiredCoreVesion string
	MinimumJavaVersion string
	SupportDynamicLoad string
	BackVersion        string
}

LinuxSuRen's avatar
LinuxSuRen 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81
// CheckUpdate fetch the lastest plugins from update center site
func (p *PluginManager) CheckUpdate(handle func(*http.Response)) {
	api := fmt.Sprintf("%s/pluginManager/checkUpdatesServer", p.URL)
	req, err := http.NewRequest("POST", api, nil)
	if err == nil {
		p.AuthHandle(req)
	} else {
		log.Fatal(err)
	}

	if err = p.CrumbHandle(req); err != nil {
		log.Fatal(err)
	}

LinuxSuRen's avatar
LinuxSuRen 已提交
82
	client := p.GetClient()
LinuxSuRen's avatar
LinuxSuRen 已提交
83 84 85 86 87 88 89
	if response, err := client.Do(req); err == nil {
		p.handleCheck(handle)(response)
	} else {
		log.Fatal(err)
	}
}

90
// GetAvailablePlugins get the aviable plugins from Jenkins
LinuxSuRen's avatar
LinuxSuRen 已提交
91 92
func (p *PluginManager) GetAvailablePlugins() (pluginList *AvailablePluginList, err error) {
	var (
93 94
		statusCode int
		data       []byte
LinuxSuRen's avatar
LinuxSuRen 已提交
95 96
	)

97 98 99 100
	if statusCode, data, err = p.Request("GET", "/pluginManager/plugins", nil, nil); err == nil {
		if statusCode == 200 {
			pluginList = &AvailablePluginList{}
			err = json.Unmarshal(data, pluginList)
LinuxSuRen's avatar
LinuxSuRen 已提交
101
		} else {
102 103 104 105
			err = fmt.Errorf("unexpected status code: %d", statusCode)
			if p.Debug {
				ioutil.WriteFile("debug.html", data, 0664)
			}
LinuxSuRen's avatar
LinuxSuRen 已提交
106 107 108 109 110
		}
	}
	return
}

111
// GetPlugins get installed plugins
LinuxSuRen's avatar
LinuxSuRen 已提交
112
func (p *PluginManager) GetPlugins() (pluginList *InstalledPluginList, err error) {
LinuxSuRen's avatar
LinuxSuRen 已提交
113
	var (
114 115
		statusCode int
		data       []byte
LinuxSuRen's avatar
LinuxSuRen 已提交
116 117
	)

118 119 120 121
	if statusCode, data, err = p.Request("GET", "/pluginManager/api/json?depth=1", nil, nil); err == nil {
		if statusCode == 200 {
			pluginList = &InstalledPluginList{}
			err = json.Unmarshal(data, pluginList)
LinuxSuRen's avatar
LinuxSuRen 已提交
122
		} else {
123 124 125 126
			err = fmt.Errorf("unexpected status code: %d", statusCode)
			if p.Debug {
				ioutil.WriteFile("debug.html", data, 0664)
			}
LinuxSuRen's avatar
LinuxSuRen 已提交
127 128 129 130 131
		}
	}
	return
}

LinuxSuRen's avatar
LinuxSuRen 已提交
132 133 134 135 136 137 138 139 140 141 142
func getPluginsInstallQuery(names []string) string {
	pluginNames := make([]string, 0)
	for _, name := range names {
		if name == "" {
			continue
		}
		pluginNames = append(pluginNames, fmt.Sprintf("plugin.%s=", name))
	}
	return strings.Join(pluginNames, "&")
}

LinuxSuRen's avatar
LinuxSuRen 已提交
143 144
// InstallPlugin install a plugin by name
func (p *PluginManager) InstallPlugin(names []string) (err error) {
LinuxSuRen's avatar
LinuxSuRen 已提交
145
	api := fmt.Sprintf("%s/pluginManager/install?%s", p.URL, getPluginsInstallQuery(names))
LinuxSuRen's avatar
LinuxSuRen 已提交
146 147 148 149 150 151 152
	var (
		req      *http.Request
		response *http.Response
	)

	req, err = http.NewRequest("POST", api, nil)
	if err == nil {
LinuxSuRen's avatar
LinuxSuRen 已提交
153 154 155
		if err = p.AuthHandle(req); err != nil {
			log.Fatal(err)
		}
LinuxSuRen's avatar
LinuxSuRen 已提交
156 157 158 159
	} else {
		return
	}

LinuxSuRen's avatar
LinuxSuRen 已提交
160
	client := p.GetClient()
LinuxSuRen's avatar
LinuxSuRen 已提交
161 162 163 164 165 166
	if response, err = client.Do(req); err == nil {
		code := response.StatusCode
		var data []byte
		data, err = ioutil.ReadAll(response.Body)
		if code == 200 {
			fmt.Println("install succeed.")
LinuxSuRen's avatar
LinuxSuRen 已提交
167 168 169 170 171 172 173 174
		} else if code == 400 {
			if errMsg, ok := response.Header["X-Error"]; ok {
				for _, msg := range errMsg {
					fmt.Println(msg)
				}
			} else {
				fmt.Println("Cannot found plugins", names)
			}
LinuxSuRen's avatar
LinuxSuRen 已提交
175
		} else {
LinuxSuRen's avatar
LinuxSuRen 已提交
176 177 178 179 180 181 182
			fmt.Println(response.Header)
			fmt.Println("status code", code)
			if err == nil && p.Debug && len(data) > 0 {
				ioutil.WriteFile("debug.html", data, 0664)
			} else if err != nil {
				log.Fatal(err)
			}
LinuxSuRen's avatar
LinuxSuRen 已提交
183 184 185 186 187 188 189 190 191
		}
	} else {
		log.Fatal(err)
	}
	return
}

// UninstallPlugin uninstall a plugin by name
func (p *PluginManager) UninstallPlugin(name string) (err error) {
192
	api := fmt.Sprintf("/pluginManager/plugin/%s/uninstall", name)
LinuxSuRen's avatar
LinuxSuRen 已提交
193
	var (
194 195
		statusCode int
		data       []byte
LinuxSuRen's avatar
LinuxSuRen 已提交
196 197
	)

198 199
	if statusCode, data, err = p.Request("POST", api, nil, nil); err == nil {
		if statusCode == 200 {
LinuxSuRen's avatar
LinuxSuRen 已提交
200 201
			fmt.Println("uninstall succeed.")
		} else {
202 203 204 205
			err = fmt.Errorf("unexpected status code: %d", statusCode)
			if p.Debug {
				ioutil.WriteFile("debug.html", data, 0664)
			}
LinuxSuRen's avatar
LinuxSuRen 已提交
206 207 208 209 210
		}
	}
	return
}

211 212
// Upload will upload a file from local filesystem into Jenkins
func (p *PluginManager) Upload(pluginFile string) {
LinuxSuRen's avatar
LinuxSuRen 已提交
213 214
	api := fmt.Sprintf("%s/pluginManager/uploadPlugin", p.URL)
	extraParams := map[string]string{}
215
	request, err := newfileUploadRequest(api, extraParams, "@name", pluginFile)
LinuxSuRen's avatar
LinuxSuRen 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	if err != nil {
		log.Fatal(err)
	}

	if err == nil {
		p.AuthHandle(request)
	} else {
		return
	}

	client := p.GetClient()
	var response *http.Response
	response, err = client.Do(request)
	if err != nil {
		log.Fatal(err)
	} else if response.StatusCode != 200 {
232
		fmt.Println("StatusCode", response.StatusCode)
LinuxSuRen's avatar
LinuxSuRen 已提交
233
		var data []byte
234 235
		if data, err = ioutil.ReadAll(response.Body); err == nil && p.Debug {
			ioutil.WriteFile("debug.html", data, 0664)
LinuxSuRen's avatar
LinuxSuRen 已提交
236 237 238 239 240 241
		} else {
			log.Fatal(err)
		}
	}
}

LinuxSuRen's avatar
LinuxSuRen 已提交
242 243
func (p *PluginManager) handleCheck(handle func(*http.Response)) func(*http.Response) {
	if handle == nil {
LinuxSuRen's avatar
LinuxSuRen 已提交
244 245 246
		handle = func(*http.Response) {
			// Do nothing, just for avoid nil exception
		}
LinuxSuRen's avatar
LinuxSuRen 已提交
247 248 249
	}
	return handle
}
LinuxSuRen's avatar
LinuxSuRen 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}

	var total float64
	if stat, err := file.Stat(); err != nil {
		panic(err)
	} else {
		total = float64(stat.Size())
	}
	defer file.Close()

265 266 267 268 269 270
	bytesBuffer := &bytes.Buffer{}
	progressWriter := &util.ProgressIndicator{
		Total:  total,
		Writer: bytesBuffer,
		Reader: bytesBuffer,
		Title:  "Uploading",
LinuxSuRen's avatar
LinuxSuRen 已提交
271
	}
272 273
	progressWriter.Init()
	writer := multipart.NewWriter(bytesBuffer)
LinuxSuRen's avatar
LinuxSuRen 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		return nil, err
	}

	_, err = io.Copy(part, file)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}

289
	req, err := http.NewRequest("POST", uri, progressWriter)
LinuxSuRen's avatar
LinuxSuRen 已提交
290 291 292
	req.Header.Set("Content-Type", writer.FormDataContentType())
	return req, err
}