profile.go 40.4 KB
Newer Older
D
dogsheng 已提交
1 2
/*
 * Copyright (c) 2019 Huawei Technologies Co., Ltd.
3 4 5
 * A-Tune is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
6
 *     http://license.coscl.org.cn/MulanPSL2
D
dogsheng 已提交
7 8 9
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
10
 * See the Mulan PSL v2 for more details.
D
dogsheng 已提交
11 12 13 14 15 16
 * Create: 2019-10-29
 */

package main

import (
17 18 19 20 21
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
22 23 24 25 26 27 28 29 30 31 32 33 34
	PB "gitee.com/openeuler/A-Tune/api/profile"
	_ "gitee.com/openeuler/A-Tune/common/checker"
	"gitee.com/openeuler/A-Tune/common/config"
	"gitee.com/openeuler/A-Tune/common/http"
	"gitee.com/openeuler/A-Tune/common/log"
	"gitee.com/openeuler/A-Tune/common/models"
	"gitee.com/openeuler/A-Tune/common/profile"
	"gitee.com/openeuler/A-Tune/common/registry"
	"gitee.com/openeuler/A-Tune/common/schedule"
	SVC "gitee.com/openeuler/A-Tune/common/service"
	"gitee.com/openeuler/A-Tune/common/sqlstore"
	"gitee.com/openeuler/A-Tune/common/tuning"
	"gitee.com/openeuler/A-Tune/common/utils"
35
	"io"
D
dogsheng 已提交
36
	"io/ioutil"
G
gaoruoshu 已提交
37 38
	"mime/multipart"
	HTTP "net/http"
D
dogsheng 已提交
39 40
	"os"
	"path"
41
	"path/filepath"
D
dogsheng 已提交
42 43 44 45 46 47 48
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/go-ini/ini"
49
	"github.com/mitchellh/mapstructure"
D
dogsheng 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	"github.com/urfave/cli"
	"google.golang.org/grpc"
)

// Monitor : the body send to monitor service
type Monitor struct {
	Module  string `json:"module"`
	Purpose string `json:"purpose"`
	Field   string `json:"field"`
}

// CollectorPost : the body send to collection service
type CollectorPost struct {
	Monitors  []Monitor `json:"monitors"`
	SampleNum int       `json:"sample_num"`
	Pipe      string    `json:"pipe"`
66 67
	File      string    `json:"file"`
	DataType  string    `json:"data_type"`
D
dogsheng 已提交
68 69 70 71
}

// RespCollectorPost : the response of collection servie
type RespCollectorPost struct {
72 73
	Path string                 `json:"path"`
	Data map[string]interface{} `json:"data"`
D
dogsheng 已提交
74 75 76 77
}

// ClassifyPostBody : the body send to classify service
type ClassifyPostBody struct {
G
gaoruoshu 已提交
78 79 80
	Data      string `json:"data"`
	ModelPath string `json:"modelpath,omitempty"`
	Model     string `json:"model,omitempty"`
D
dogsheng 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
}

// RespClassify : the response of classify model
type RespClassify struct {
	ResourceLimit string  `json:"resource_limit"`
	WorkloadType  string  `json:"workload_type"`
	Percentage    float32 `json:"percentage"`
}

// ProfileServer : the type impletent the grpc server
type ProfileServer struct {
	utils.MutexLock
	ConfPath   string
	ScriptPath string
	Raw        *ini.File
}

func init() {
	svc := SVC.ProfileService{
		Name:    "opt.profile",
		Desc:    "opt profile module",
		NewInst: NewProfileServer,
	}
	if err := SVC.AddService(&svc); err != nil {
		fmt.Printf("Failed to load service project : %s\n", err)
		return
	}

	log.Info("load profile service successfully\n")
}

// NewProfileServer method new a instance of the grpc server
func NewProfileServer(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
	defaultConfigFile := path.Join(config.DefaultConfPath, "atuned.cnf")

	exist, err := utils.PathExist(defaultConfigFile)
	if err != nil {
		return nil, err
	}
	if !exist {
Z
Zhipeng Xie 已提交
121
		return nil, fmt.Errorf("could not find default config file")
D
dogsheng 已提交
122 123 124 125
	}

	cfg, err := ini.Load(defaultConfigFile)
	if err != nil {
H
hanxinke 已提交
126
		return nil, fmt.Errorf("failed to parse %s, %v", defaultConfigFile, err)
D
dogsheng 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	}

	return &ProfileServer{
		Raw: cfg,
	}, nil
}

// RegisterServer method register the grpc service
func (s *ProfileServer) RegisterServer(server *grpc.Server) error {
	PB.RegisterProfileMgrServer(server, s)
	return nil
}

// Healthy method, implement SvrService interface
func (s *ProfileServer) Healthy(opts ...interface{}) error {
	return nil
}

// Post method send POST to start analysis the workload type
func (p *ClassifyPostBody) Post() (*RespClassify, error) {
Z
Zhipeng Xie 已提交
147
	url := config.GetURL(config.ClassificationURI)
D
dogsheng 已提交
148 149 150 151 152 153 154
	response, err := http.Post(url, p)
	if err != nil {
		return nil, err
	}

	defer response.Body.Close()
	if response.StatusCode != 200 {
H
hanxinke 已提交
155
		return nil, fmt.Errorf("online learning failed")
D
dogsheng 已提交
156 157
	}
	resBody, err := ioutil.ReadAll(response.Body)
Z
Zhipeng Xie 已提交
158 159 160 161
	if err != nil {
		return nil, err
	}

D
dogsheng 已提交
162 163 164 165 166 167 168 169 170 171 172
	resPostIns := new(RespClassify)
	err = json.Unmarshal(resBody, resPostIns)
	if err != nil {
		return nil, err
	}

	return resPostIns, nil
}

// Post method send POST to start collection data
func (c *CollectorPost) Post() (*RespCollectorPost, error) {
Z
Zhipeng Xie 已提交
173
	url := config.GetURL(config.CollectorURI)
D
dogsheng 已提交
174 175 176 177 178 179 180
	response, err := http.Post(url, c)
	if err != nil {
		return nil, err
	}

	defer response.Body.Close()
	if response.StatusCode != 200 {
H
hanxinke 已提交
181
		return nil, fmt.Errorf("collect data failed")
D
dogsheng 已提交
182 183
	}
	resBody, err := ioutil.ReadAll(response.Body)
Z
Zhipeng Xie 已提交
184 185 186 187
	if err != nil {
		return nil, err
	}

D
dogsheng 已提交
188 189 190 191 192 193 194 195
	resPostIns := new(RespCollectorPost)
	err = json.Unmarshal(resBody, resPostIns)
	if err != nil {
		return nil, err
	}
	return resPostIns, nil
}

G
gaoruoshu 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
// Post method send POST to start transfer file
func Post(serviceType, paramName, path string) (string, error) {
	url := config.GetURL(config.TransferURI)
	file, err := os.Open(path)
	if err != nil {
		return "", fmt.Errorf("Path Error")
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		return "", fmt.Errorf("writer error")
	}
	_, err = io.Copy(part, file)
	extraParams := map[string]string{
		"service":  serviceType,
		"savepath": "/etc/atuned/" + serviceType + "/" + filepath.Base(path),
	}

	for key, val := range extraParams {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return "", fmt.Errorf("writer close error")
	}

	request, err := HTTP.NewRequest("POST", url, body)
	if err != nil {
		return "", fmt.Errorf("newRequest failed")
	}
	request.Header.Set("Content-Type", writer.FormDataContentType())
	client := &HTTP.Client{}
	resp, err := client.Do(request)
	if err != nil {
		return "", fmt.Errorf("do request error")
	} else {
		defer resp.Body.Close()

		body := &bytes.Buffer{}
		_, err := body.ReadFrom(resp.Body)
		if err != nil {
			return "", fmt.Errorf("body read form error")
		}
		res := body.String()
		res = res[1 : len(res)-2]
		return res, nil
	}
}

D
dogsheng 已提交
248 249
// Profile method set the workload type to effective manual
func (s *ProfileServer) Profile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_ProfileServer) error {
250 251 252
	profileNamesStr := profileInfo.GetName()
	profileNames := strings.Split(profileNamesStr, ",")
	profile, ok := profile.Load(profileNames)
D
dogsheng 已提交
253 254 255

	if !ok {
		fmt.Println("Failure Load ", profileInfo.GetName())
Z
Zhipeng Xie 已提交
256
		return fmt.Errorf("load profile %s Faild", profileInfo.GetName())
D
dogsheng 已提交
257 258 259 260 261 262
	}
	ch := make(chan *PB.AckCheck)
	ctx, cancel := context.WithCancel(context.Background())
	defer close(ch)
	defer cancel()

Z
Zhipeng Xie 已提交
263
	go func(ctx context.Context) {
D
dogsheng 已提交
264 265 266
		for {
			select {
			case value := <-ch:
Z
Zhipeng Xie 已提交
267
				_ = stream.Send(value)
D
dogsheng 已提交
268
			case <-ctx.Done():
Z
Zhipeng Xie 已提交
269
				return
D
dogsheng 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283
			}
		}
	}(ctx)

	if err := profile.RollbackActive(ch); err != nil {
		return err
	}

	return nil
}

// ListWorkload method list support workload
func (s *ProfileServer) ListWorkload(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_ListWorkloadServer) error {
	log.Debug("Begin to inquire all workloads\n")
284
	profileLogs, err := sqlstore.GetProfileLogs()
D
dogsheng 已提交
285 286 287 288
	if err != nil {
		return err
	}

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
	var activeName string
	if len(profileLogs) > 0 {
		activeName = profileLogs[0].ProfileID
	}

	if activeName != "" {
		classProfile := &sqlstore.GetClass{Class: activeName}
		err = sqlstore.GetClasses(classProfile)
		if err != nil {
			return fmt.Errorf("inquery workload type table faild %v", err)
		}
		if len(classProfile.Result) > 0 {
			activeName = classProfile.Result[0].ProfileType
		}
	}
	log.Debugf("active name is %s", activeName)

	err = filepath.Walk(config.DefaultProfilePath, func(absPath string, info os.FileInfo, err error) error {
		if info.Name() == "include" {
			return filepath.SkipDir
		}
		if !info.IsDir() {
			if !strings.HasSuffix(info.Name(), ".conf") {
				return nil
			}

			absFilename := absPath[len(config.DefaultProfilePath)+1:]
			filenameOnly := strings.TrimSuffix(strings.ReplaceAll(absFilename, "/", "-"),
				path.Ext(info.Name()))

			var active bool
			if filenameOnly == activeName {
				active = true
			}
			_ = stream.Send(&PB.ListMessage{
				ProfileNames: filenameOnly,
				Active:       strconv.FormatBool(active)})

		}
		return nil
	})

	if err != nil {
		return err
D
dogsheng 已提交
333 334 335 336 337 338 339
	}

	return nil
}

// CheckInitProfile method check the system init information
// like BIOS version, memory balanced...
Z
Zhipeng Xie 已提交
340 341 342
func (s *ProfileServer) CheckInitProfile(profileInfo *PB.ProfileInfo,
	stream PB.ProfileMgr_CheckInitProfileServer) error {
	ch := make(chan *PB.AckCheck)
D
dogsheng 已提交
343
	defer close(ch)
Z
Zhipeng Xie 已提交
344 345 346
	go func() {
		for value := range ch {
			_ = stream.Send(value)
D
dogsheng 已提交
347 348 349
		}
	}()

Z
Zhipeng Xie 已提交
350 351 352 353 354
	services := registry.GetCheckerServices()

	for _, service := range services {
		log.Infof("initializing checker service: %s", service.Name)
		if err := service.Instance.Init(); err != nil {
H
hanxinke 已提交
355
			return fmt.Errorf("service init failed: %v", err)
D
dogsheng 已提交
356
		}
Z
Zhipeng Xie 已提交
357
	}
D
dogsheng 已提交
358

Z
Zhipeng Xie 已提交
359 360 361 362 363
	// running checker service
	for _, srv := range services {
		service := srv
		checkerService, ok := service.Instance.(registry.CheckService)
		if !ok {
D
dogsheng 已提交
364 365 366
			continue
		}

Z
Zhipeng Xie 已提交
367 368 369 370 371
		if registry.IsCheckDisabled(service.Instance) {
			continue
		}
		err := checkerService.Check(ch)
		if err != nil {
H
hanxinke 已提交
372
			log.Errorf("service %s running failed, reason: %v", service.Name, err)
Z
Zhipeng Xie 已提交
373
			continue
D
dogsheng 已提交
374 375 376 377 378 379 380 381 382
		}
	}

	return nil
}

// Analysis method analysis the system traffic load
func (s *ProfileServer) Analysis(message *PB.AnalysisMessage, stream PB.ProfileMgr_AnalysisServer) error {
	if !s.TryLock() {
383
		return fmt.Errorf("dynamic optimizer search or analysis has been in running")
D
dogsheng 已提交
384 385 386
	}
	defer s.Unlock()

Z
Zhipeng Xie 已提交
387
	_ = stream.Send(&PB.AckCheck{Name: "1. Analysis system runtime information: CPU Memory IO and Network..."})
D
dogsheng 已提交
388 389 390

	npipe, err := utils.CreateNamedPipe()
	if err != nil {
H
hanxinke 已提交
391
		return fmt.Errorf("create named pipe failed")
D
dogsheng 已提交
392 393 394 395 396 397 398 399 400 401 402 403
	}

	defer os.Remove(npipe)

	go func() {
		file, _ := os.OpenFile(npipe, os.O_RDONLY, os.ModeNamedPipe)
		reader := bufio.NewReader(file)

		scanner := bufio.NewScanner(reader)

		for scanner.Scan() {
			line := scanner.Text()
Z
Zhipeng Xie 已提交
404
			_ = stream.Send(&PB.AckCheck{Name: line, Status: utils.INFO})
D
dogsheng 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		}
	}()

	//1. get the dimension structure of the system data to be collected
	collections, err := sqlstore.GetCollections()
	if err != nil {
		log.Errorf("inquery collection tables error: %v", err)
		return err
	}
	// 1.1 send the collect data command to the monitor service
	monitors := make([]Monitor, 0)
	for _, collection := range collections {
		re := regexp.MustCompile(`\{([^}]+)\}`)
		matches := re.FindAllStringSubmatch(collection.Metrics, -1)
		if len(matches) > 0 {
			for _, match := range matches {
Z
Zhipeng Xie 已提交
421 422 423
				if len(match) < 2 {
					continue
				}
424 425 426 427 428 429 430
				var value string
				if s.Raw.Section("system").Haskey(match[1]) {
					value = s.Raw.Section("system").Key(match[1]).Value()
				} else if s.Raw.Section("server").Haskey(match[1]) {
					value = s.Raw.Section("server").Key(match[1]).Value()
				} else {
					return fmt.Errorf("%s is not exist in the system or server section", match[1])
D
dogsheng 已提交
431
				}
432
				re = regexp.MustCompile(`\{(` + match[1] + `)\}`)
D
dogsheng 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445
				collection.Metrics = re.ReplaceAllString(collection.Metrics, value)
			}
		}

		monitor := Monitor{Module: collection.Module, Purpose: collection.Purpose, Field: collection.Metrics}
		monitors = append(monitors, monitor)
	}

	sampleNum := s.Raw.Section("server").Key("sample_num").MustInt(20)
	collectorBody := new(CollectorPost)
	collectorBody.SampleNum = sampleNum
	collectorBody.Monitors = monitors
	collectorBody.Pipe = npipe
446
	collectorBody.File = "/run/atuned/test.csv"
D
dogsheng 已提交
447 448 449

	respCollectPost, err := collectorBody.Post()
	if err != nil {
Z
Zhipeng Xie 已提交
450
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
D
dogsheng 已提交
451 452 453
		return err
	}

G
gaoruoshu 已提交
454
	dataPath, err := Post("classification", "file", respCollectPost.Path)
455
	if err != nil {
G
gaoruoshu 已提交
456
		log.Errorf("Failed transfer file to server: %v", err)
457 458 459
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
		return err
	}
G
gaoruoshu 已提交
460
	defer os.Remove(dataPath)
461

D
dogsheng 已提交
462 463
	//2. send the collected data to the model for completion type identification
	body := new(ClassifyPostBody)
G
gaoruoshu 已提交
464
	body.Data = dataPath
D
dogsheng 已提交
465 466 467 468 469 470 471 472
	body.ModelPath = path.Join(config.DefaultAnalysisPath, "models")

	if message.GetModel() != "" {
		body.Model = message.GetModel()
	}
	respPostIns, err := body.Post()

	if err != nil {
Z
Zhipeng Xie 已提交
473
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
D
dogsheng 已提交
474 475 476 477
		return err
	}

	workloadType := respPostIns.WorkloadType
Z
Zhipeng Xie 已提交
478
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 2. Current System Workload Characterization is %s", workloadType)})
D
dogsheng 已提交
479 480 481

	//3. judge the workload type is exist in the database
	classProfile := &sqlstore.GetClass{Class: workloadType}
H
hanxinke 已提交
482
	if err = sqlstore.GetClasses(classProfile); err != nil {
H
hanxinke 已提交
483 484
		log.Errorf("inquery workload type table failed %v", err)
		return fmt.Errorf("inquery workload type table failed %v", err)
D
dogsheng 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
	}
	if len(classProfile.Result) == 0 {
		log.Errorf("%s is not exist in the table", workloadType)
		return fmt.Errorf("%s is not exist in the table", workloadType)
	}

	// the workload type is already actived
	if classProfile.Result[0].Active {
		log.Infof("analysis result %s is the same with current active workload type", workloadType)
		return nil
	}

	//4. inquery the support app of the workload type
	classApps := &sqlstore.GetClassApp{Class: workloadType}
	err = sqlstore.GetClassApps(classApps)
	if err != nil {
		log.Errorf("inquery support app depend on class error: %v", err)
		return err
	}
	if len(classApps.Result) == 0 {
		return fmt.Errorf("class %s is not exist in the tables", workloadType)
	}
	apps := classApps.Result[0].Apps
	log.Infof("workload %s support app: %s", workloadType, apps)
Z
Zhipeng Xie 已提交
509 510
	log.Infof("workload %s resource limit: %s, cluster result resource limit: %s",
		workloadType, apps, respPostIns.ResourceLimit)
D
dogsheng 已提交
511

Z
Zhipeng Xie 已提交
512
	_ = stream.Send(&PB.AckCheck{Name: "\n 3. Build the best resource model..."})
D
dogsheng 已提交
513 514 515 516 517 518

	//5. get the profile type depend on the workload type
	profileType := classProfile.Result[0].ProfileType
	profileNames := strings.Split(profileType, ",")
	if len(profileNames) == 0 {
		log.Errorf("No profile or invaild profiles were specified.")
Z
Zhipeng Xie 已提交
519
		return fmt.Errorf("no profile or invaild profiles were specified")
D
dogsheng 已提交
520 521 522 523
	}

	//6. get the profile info depend on the profile type
	log.Infof("the resource model of the profile type is %s", profileType)
Z
Zhipeng Xie 已提交
524
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 4. Match profile: %s", profileType)})
D
dogsheng 已提交
525 526 527
	pro, _ := profile.Load(profileNames)
	pro.SetWorkloadType(workloadType)

Z
Zhipeng Xie 已提交
528
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 5. bengin to set static profile")})
D
dogsheng 已提交
529 530 531
	log.Infof("bengin to set static profile")

	//static profile setting
Z
Zhipeng Xie 已提交
532 533 534 535
	ch := make(chan *PB.AckCheck)
	go func() {
		for value := range ch {
			_ = stream.Send(value)
D
dogsheng 已提交
536 537
		}
	}()
Z
Zhipeng Xie 已提交
538 539

	_ = pro.RollbackActive(ch)
D
dogsheng 已提交
540 541 542 543 544 545 546

	rules := &sqlstore.GetRuleTuned{Class: workloadType}
	if err := sqlstore.GetRuleTuneds(rules); err != nil {
		return err
	}

	if len(rules.Result) < 1 {
Z
Zhipeng Xie 已提交
547
		_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("Completed optimization, please restart application!")})
D
dogsheng 已提交
548 549 550 551
		log.Info("no rules to tuned")
		return nil
	}

Z
Zhipeng Xie 已提交
552 553
	log.Info("begin to dynamic tuning depending on rules")
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 6. bengin to set dynamic profile")})
D
dogsheng 已提交
554 555 556 557
	if err := tuning.RuleTuned(workloadType); err != nil {
		return err
	}

Z
Zhipeng Xie 已提交
558
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("Completed optimization, please restart application!")})
D
dogsheng 已提交
559 560 561 562
	return nil
}

// Tuning method calling the bayes search method to tuned parameters
563 564 565 566 567
func (s *ProfileServer) Tuning(stream PB.ProfileMgr_TuningServer) error {
	if !s.TryLock() {
		return fmt.Errorf("dynamic optimizer search or analysis has been in running")
	}
	defer s.Unlock()
D
dogsheng 已提交
568

569
	ch := make(chan *PB.TuningMessage)
570
	defer close(ch)
Z
Zhipeng Xie 已提交
571 572 573 574 575
	go func() {
		for value := range ch {
			_ = stream.Send(value)
		}
	}()
D
dogsheng 已提交
576

577
	var optimizer = tuning.Optimizer{}
578

579 580 581 582 583
	stopCh := make(chan int, 1)
	var cycles int32 = 0
	var message string
	var step int32 = 1

584
	for {
585 586 587 588 589 590 591 592 593 594 595 596 597
		select {
		case <-stopCh:
			if cycles > 0 {
				_ = stream.Send(&PB.TuningMessage{State: PB.TuningMessage_JobInit})
			} else {
				_ = stream.Send(&PB.TuningMessage{State: PB.TuningMessage_Ending})
			}
			cycles--
		default:
		}
		if cycles < 0 {
			break
		}
598 599 600
		reply, err := stream.Recv()
		if err == io.EOF {
			break
601
		}
Z
Zhipeng Xie 已提交
602 603 604
		if err != nil {
			return err
		}
D
dogsheng 已提交
605

606 607 608 609 610 611
		state := reply.GetState()
		switch state {
		case PB.TuningMessage_SyncConfig:
			optimizer.Content = reply.GetContent()
			err = optimizer.SyncTunedNode(ch)
			if err != nil {
H
hanxinke 已提交
612 613
				return err
			}
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
		case PB.TuningMessage_JobRestart:
			log.Infof("restart cycles is: %d", cycles)
			optimizer.Content = reply.GetContent()
			if cycles > 0 {
				message = fmt.Sprintf("%d、Starting the next cycle of parameter selection......", step)
				step += 1
				ch <- &PB.TuningMessage{State: PB.TuningMessage_Display, Content: []byte(message)}
				if err = optimizer.InitFeatureSel(ch, stopCh); err != nil {
					return err
				}
			} else {
				message = fmt.Sprintf("%d、Start to tuning the system......", step)
				step += 1
				ch <- &PB.TuningMessage{State: PB.TuningMessage_Display, Content: []byte(message)}
				if err = optimizer.InitTuned(ch, stopCh); err != nil {
					return err
				}
			}
		case PB.TuningMessage_JobInit:
			project := reply.GetName()
			if len(strings.TrimSpace(project)) == 0 {
				if err != nil {
					return err
				}
				message = fmt.Sprintf("%d.Begin to Analysis the system......", step)
				step += 1
				ch <- &PB.TuningMessage{State: PB.TuningMessage_Display, Content: []byte(message)}
				project, err = s.Getworkload()
				if err != nil {
					return err
				}
				message = fmt.Sprintf("%d.Current runing application is: %s", step, project)
				step += 1
				ch <- &PB.TuningMessage{State: PB.TuningMessage_Display, Content: []byte(message)}
			}

			message = fmt.Sprintf("%d.Loading its corresponding tuning project: %s", step, project)
			step += 1
			ch <- &PB.TuningMessage{State: PB.TuningMessage_Display, Content: []byte(message)}
H
hanxinke 已提交
653

654
			if err := tuning.CheckServerPrj(project, &optimizer); err != nil {
655
				return err
D
dogsheng 已提交
656
			}
Z
Zhipeng Xie 已提交
657

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
			optimizer.Engine = reply.GetEngine()
			optimizer.Content = reply.GetContent()
			optimizer.RandomStarts = reply.GetRandomStarts()
			optimizer.FeatureFilterEngine = reply.GetFeatureFilterEngine()
			optimizer.FeatureFilterIters = reply.GetFeatureFilterIters()
			cycles = reply.GetFeatureFilterCycle()

			if cycles == 0 {
				message = fmt.Sprintf("%d.Start to tuning the system......", step)
				ch <- &PB.TuningMessage{State: PB.TuningMessage_Display, Content: []byte(message)}
				step += 1
				if err = optimizer.InitTuned(ch, stopCh); err != nil {
					return err
				}
			} else {
				message = fmt.Sprintf("%d.Starting to select the important parameters......", step)
				ch <- &PB.TuningMessage{State: PB.TuningMessage_Display, Content: []byte(message)}
				step += 1
				if err = optimizer.InitFeatureSel(ch, stopCh); err != nil {
					return err
				}
			}
		case PB.TuningMessage_Restore:
			project := reply.GetName()
			log.Infof("begin to restore project: %s", project)
			if err := tuning.CheckServerPrj(project, &optimizer); err != nil {
				return err
			}
			if err := optimizer.RestoreConfigTuned(ch); err != nil {
				return err
			}
			log.Infof("restore project %s success", project)
			return nil
		case PB.TuningMessage_BenchMark:
			optimizer.Content = reply.GetContent()
			err := optimizer.DynamicTuned(ch, stopCh)
			if err != nil {
695 696 697
				return err
			}

698
		}
D
dogsheng 已提交
699 700 701 702 703 704 705 706 707
	}

	return nil
}

/*
UpgradeProfile method update the db file
*/
func (s *ProfileServer) UpgradeProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_UpgradeProfileServer) error {
708 709 710 711 712 713 714 715
	isLocalAddr, err := SVC.CheckRpcIsLocalAddr(stream.Context())
	if err != nil {
		return err
	}
	if !isLocalAddr {
		return fmt.Errorf("the upgrade command can not be remotely operated")
	}

D
dogsheng 已提交
716 717 718 719 720 721 722 723 724
	log.Debug("Begin to upgrade profiles\n")
	currenDbPath := path.Join(config.DatabasePath, config.DatabaseName)
	newDbPath := profileInfo.GetName()

	exist, err := utils.PathExist(config.DefaultTempPath)
	if err != nil {
		return err
	}
	if !exist {
Z
Zhipeng Xie 已提交
725 726 727
		if err = os.MkdirAll(config.DefaultTempPath, 0750); err != nil {
			return err
		}
D
dogsheng 已提交
728 729 730 731 732
	}
	timeUnix := strconv.FormatInt(time.Now().Unix(), 10) + ".db"
	tempFile := path.Join(config.DefaultTempPath, timeUnix)

	if err := utils.CopyFile(tempFile, currenDbPath); err != nil {
Z
Zhipeng Xie 已提交
733
		_ = stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
D
dogsheng 已提交
734 735 736 737
		return nil
	}

	if err := utils.CopyFile(currenDbPath, newDbPath); err != nil {
Z
Zhipeng Xie 已提交
738
		_ = stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
D
dogsheng 已提交
739 740 741 742
		return nil
	}

	if err := sqlstore.Reload(currenDbPath); err != nil {
Z
Zhipeng Xie 已提交
743
		_ = stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
D
dogsheng 已提交
744 745 746
		return nil
	}

Z
Zhipeng Xie 已提交
747
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("upgrade success"), Status: utils.SUCCESS})
D
dogsheng 已提交
748 749 750 751 752 753 754
	return nil
}

/*
InfoProfile method display the content of the specified workload type
*/
func (s *ProfileServer) InfoProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_InfoProfileServer) error {
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
	var context string
	profileName := profileInfo.GetName()
	err := filepath.Walk(config.DefaultProfilePath, func(absPath string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			absFilename := absPath[len(config.DefaultProfilePath)+1:]
			filenameOnly := strings.TrimSuffix(strings.ReplaceAll(absFilename, "/", "-"),
				path.Ext(info.Name()))
			if filenameOnly == profileName {
				data, err := ioutil.ReadFile(absPath)
				if err != nil {
					return err
				}
				context = "\n*** " + profileName + ":\n" + string(data)
				_ = stream.Send(&PB.ProfileInfo{Name: context})
				return nil
			}
		}
		return nil
	})
D
dogsheng 已提交
774

775 776
	if err != nil {
		return err
D
dogsheng 已提交
777 778
	}

779 780 781
	if context == "" {
		log.Errorf("profile %s is not exist", profileName)
		return fmt.Errorf("profile %s is not exist", profileName)
D
dogsheng 已提交
782 783 784 785 786 787 788 789
	}

	return nil
}

/*
CheckActiveProfile method check current active profile is effective
*/
Z
Zhipeng Xie 已提交
790 791
func (s *ProfileServer) CheckActiveProfile(profileInfo *PB.ProfileInfo,
	stream PB.ProfileMgr_CheckActiveProfileServer) error {
D
dogsheng 已提交
792
	log.Debug("Begin to check active profiles\n")
793 794

	profileLogs, err := sqlstore.GetProfileLogs()
D
dogsheng 已提交
795 796 797
	if err != nil {
		return err
	}
798 799 800 801 802 803 804

	var activeName string
	if len(profileLogs) > 0 {
		activeName = profileLogs[0].ProfileID
	}

	if activeName == "" {
Z
Zhipeng Xie 已提交
805
		return fmt.Errorf("no active profile or more than 1 active profile")
D
dogsheng 已提交
806
	}
807 808 809 810 811 812 813 814 815
	classProfile := &sqlstore.GetClass{Class: activeName}
	err = sqlstore.GetClasses(classProfile)
	if err != nil {
		return fmt.Errorf("inquery workload type table faild %v", err)
	}
	if len(classProfile.Result) > 0 {
		activeName = classProfile.Result[0].ProfileType
	}
	log.Debugf("active name is %s", activeName)
D
dogsheng 已提交
816

817
	profile, ok := profile.LoadFromProfile(activeName)
D
dogsheng 已提交
818 819

	if !ok {
820 821
		log.WithField("profile", activeName).Errorf("Load profile %s Faild", activeName)
		return fmt.Errorf("load profile %s Faild", activeName)
D
dogsheng 已提交
822 823
	}

Z
Zhipeng Xie 已提交
824
	ch := make(chan *PB.AckCheck)
D
dogsheng 已提交
825
	defer close(ch)
Z
Zhipeng Xie 已提交
826 827 828
	go func() {
		for value := range ch {
			_ = stream.Send(value)
D
dogsheng 已提交
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
		}
	}()

	if err := profile.Check(ch); err != nil {
		return err
	}

	return nil
}

// ProfileRollback method rollback the profile to init state
func (s *ProfileServer) ProfileRollback(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_ProfileRollbackServer) error {
	profileLogs, err := sqlstore.GetProfileLogs()
	if err != nil {
		return err
	}

	if len(profileLogs) < 1 {
Z
Zhipeng Xie 已提交
847
		_ = stream.Send(&PB.AckCheck{Name: "no profile need to rollback"})
D
dogsheng 已提交
848 849 850 851 852 853 854 855
		return nil
	}

	sort.Slice(profileLogs, func(i, j int) bool {
		return profileLogs[i].ID > profileLogs[j].ID
	})

	//static profile setting
Z
Zhipeng Xie 已提交
856 857 858 859
	ch := make(chan *PB.AckCheck)
	go func() {
		for value := range ch {
			_ = stream.Send(value)
D
dogsheng 已提交
860 861 862 863
		}
	}()

	for _, pro := range profileLogs {
Z
Zhipeng Xie 已提交
864
		log.Infof("begin to restore profile id: %d", pro.ID)
D
dogsheng 已提交
865
		profileInfo := profile.HistoryProfile{}
Z
Zhipeng Xie 已提交
866 867
		_ = profileInfo.Load(pro.Context)
		_ = profileInfo.Resume(ch)
D
dogsheng 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894

		// delete profile log after restored
		if err := sqlstore.DelProfileLogByID(pro.ID); err != nil {
			return err
		}
		//delete backup dir
		if err := os.RemoveAll(pro.BackupPath); err != nil {
			return err
		}

		// update active profile after restored
		if err := sqlstore.ActiveProfile(pro.ProfileID); err != nil {
			return nil
		}
	}

	if err := sqlstore.InActiveProfile(); err != nil {
		return nil
	}

	return nil
}

/*
Collection method call collection script to collect system data.
*/
func (s *ProfileServer) Collection(message *PB.CollectFlag, stream PB.ProfileMgr_CollectionServer) error {
895 896 897 898 899 900 901 902
	isLocalAddr, err := SVC.CheckRpcIsLocalAddr(stream.Context())
	if err != nil {
		return err
	}
	if !isLocalAddr {
		return fmt.Errorf("the collection command can not be remotely operated")
	}

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	if valid := utils.IsInputStringValid(message.GetWorkload()); !valid {
		return fmt.Errorf("input:%s is invalid", message.GetWorkload())
	}

	if valid := utils.IsInputStringValid(message.GetOutputPath()); !valid {
		return fmt.Errorf("input:%s is invalid", message.GetOutputPath())
	}

	if valid := utils.IsInputStringValid(message.GetType()); !valid {
		return fmt.Errorf("input:%s is invalid", message.GetType())
	}

	if valid := utils.IsInputStringValid(message.GetBlock()); !valid {
		return fmt.Errorf("input:%s is invalid", message.GetBlock())
	}

	if valid := utils.IsInputStringValid(message.GetNetwork()); !valid {
		return fmt.Errorf("input:%s is invalid", message.GetNetwork())
	}

923 924
	classProfile := &sqlstore.GetClass{Class: message.GetType()}
	if err = sqlstore.GetClasses(classProfile); err != nil {
D
dogsheng 已提交
925 926
		return err
	}
927 928 929 930 931 932 933 934
	if len(classProfile.Result) == 0 {
		return fmt.Errorf("app type %s is not exist, use define command first", message.GetType())
	}

	profileType := classProfile.Result[0].ProfileType
	include, err := profile.GetProfileInclude(profileType)
	if err != nil {
		return err
D
dogsheng 已提交
935 936 937 938 939 940 941 942 943 944
	}

	exist, err := utils.PathExist(message.GetOutputPath())
	if err != nil {
		return err
	}
	if !exist {
		return fmt.Errorf("output_path %s is not exist", message.GetOutputPath())
	}

H
hanxinke 已提交
945
	if err = utils.InterfaceByName(message.GetNetwork()); err != nil {
D
dogsheng 已提交
946 947 948
		return err
	}

H
hanxinke 已提交
949
	if err = utils.DiskByName(message.GetBlock()); err != nil {
D
dogsheng 已提交
950 951 952
		return err
	}

953
	collections, err := sqlstore.GetCollections()
D
dogsheng 已提交
954
	if err != nil {
955
		log.Errorf("inquery collection tables error: %v", err)
D
dogsheng 已提交
956 957 958
		return err
	}

959 960 961 962 963 964 965 966 967
	monitors := make([]Monitor, 0)
	for _, collection := range collections {
		re := regexp.MustCompile(`\{([^}]+)\}`)
		matches := re.FindAllStringSubmatch(collection.Metrics, -1)
		if len(matches) > 0 {
			for _, match := range matches {
				if len(match) < 2 {
					continue
				}
D
dogsheng 已提交
968

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
				var value string
				if match[1] == "disk" {
					value = message.GetBlock()
				} else if match[1] == "network" {
					value = message.GetNetwork()
				} else if match[1] == "interval" {
					value = strconv.FormatInt(message.GetInterval(), 10)
				} else {
					log.Warnf("%s is not recognized", match[1])
					continue
				}
				re = regexp.MustCompile(`\{(` + match[1] + `)\}`)
				collection.Metrics = re.ReplaceAllString(collection.Metrics, value)
			}
		}

		monitor := Monitor{Module: collection.Module, Purpose: collection.Purpose, Field: collection.Metrics}
		monitors = append(monitors, monitor)
	}

	collectorBody := new(CollectorPost)
	collectorBody.SampleNum = int(message.GetDuration() / message.GetInterval())
	collectorBody.Monitors = monitors
992
	nowTime := time.Now().Format("20060702-150405")
993 994
	fileName := fmt.Sprintf("%s-%s.csv", message.GetWorkload(), nowTime)
	collectorBody.File = path.Join(message.GetOutputPath(), fileName)
995 996 997 998 999 1000
	if include == "" {
		include = "default"
	}
	collectorBody.DataType = fmt.Sprintf("%s:%s", include, message.GetType())

	_ = stream.Send(&PB.AckCheck{Name: "start to collect data"})
1001 1002

	_, err = collectorBody.Post()
D
dogsheng 已提交
1003
	if err != nil {
1004
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
D
dogsheng 已提交
1005 1006 1007
		return err
	}

1008
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("generate %s successfully", collectorBody.File)})
D
dogsheng 已提交
1009 1010 1011 1012 1013 1014 1015
	return nil
}

/*
Training method train the collected data to generate the model
*/
func (s *ProfileServer) Training(message *PB.TrainMessage, stream PB.ProfileMgr_TrainingServer) error {
1016 1017 1018 1019 1020 1021 1022 1023
	isLocalAddr, err := SVC.CheckRpcIsLocalAddr(stream.Context())
	if err != nil {
		return err
	}
	if !isLocalAddr {
		return fmt.Errorf("the train command can not be remotely operated")
	}

D
dogsheng 已提交
1024 1025 1026
	DataPath := message.GetDataPath()
	OutputPath := message.GetOutputPath()

G
gaoruoshu 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	compressPath, err := utils.CreateCompressFile(DataPath)
	if err != nil {
		log.Debugf("Failed to compress %s: %v", DataPath, err)
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
		return err
	}
	defer os.Remove(compressPath)

	trainPath, err := Post("training", "file", compressPath)
	if err != nil {
		log.Debugf("Failed to transfer file: %v", err)
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
		return err
	}

D
dogsheng 已提交
1042
	trainBody := new(models.Training)
G
gaoruoshu 已提交
1043
	trainBody.DataPath = trainPath
D
dogsheng 已提交
1044 1045 1046 1047 1048 1049 1050 1051
	trainBody.OutputPath = OutputPath
	trainBody.ModelPath = path.Join(config.DefaultAnalysisPath, "models")

	success, err := trainBody.Post()
	if err != nil {
		return err
	}
	if success {
Z
Zhipeng Xie 已提交
1052
		_ = stream.Send(&PB.AckCheck{Name: "training the self collect data success"})
D
dogsheng 已提交
1053 1054 1055
		return nil
	}

H
hanxinke 已提交
1056
	_ = stream.Send(&PB.AckCheck{Name: "training the self collect data failed"})
D
dogsheng 已提交
1057 1058 1059 1060 1061
	return nil
}

// Charaterization method will be deprecate in the future
func (s *ProfileServer) Charaterization(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_CharaterizationServer) error {
Z
Zhipeng Xie 已提交
1062
	_ = stream.Send(&PB.AckCheck{Name: "1. Analysis system runtime information: CPU Memory IO and Network..."})
D
dogsheng 已提交
1063 1064 1065

	npipe, err := utils.CreateNamedPipe()
	if err != nil {
H
hanxinke 已提交
1066
		return fmt.Errorf("create named pipe failed")
D
dogsheng 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
	}

	defer os.Remove(npipe)

	go func() {
		file, _ := os.OpenFile(npipe, os.O_RDONLY, os.ModeNamedPipe)
		reader := bufio.NewReader(file)

		scanner := bufio.NewScanner(reader)

		for scanner.Scan() {
			line := scanner.Text()
Z
Zhipeng Xie 已提交
1079
			_ = stream.Send(&PB.AckCheck{Name: line, Status: utils.INFO})
D
dogsheng 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
		}
	}()

	//1. get the dimension structure of the system data to be collected
	collections, err := sqlstore.GetCollections()
	if err != nil {
		log.Errorf("inquery collection tables error: %v", err)
		return err
	}
	// 1.1 send the collect data command to the monitor service
	monitors := make([]Monitor, 0)
	for _, collection := range collections {
		re := regexp.MustCompile(`\{([^}]+)\}`)
		matches := re.FindAllStringSubmatch(collection.Metrics, -1)
		if len(matches) > 0 {
			for _, match := range matches {
Z
Zhipeng Xie 已提交
1096 1097 1098
				if len(match) < 2 {
					continue
				}
1099 1100 1101 1102 1103 1104 1105
				var value string
				if s.Raw.Section("system").Haskey(match[1]) {
					value = s.Raw.Section("system").Key(match[1]).Value()
				} else if s.Raw.Section("server").Haskey(match[1]) {
					value = s.Raw.Section("server").Key(match[1]).Value()
				} else {
					return fmt.Errorf("%s is not exist in the system or server section", match[1])
D
dogsheng 已提交
1106
				}
1107
				re = regexp.MustCompile(`\{(` + match[1] + `)\}`)
D
dogsheng 已提交
1108 1109 1110 1111 1112 1113 1114 1115
				collection.Metrics = re.ReplaceAllString(collection.Metrics, value)
			}
		}

		monitor := Monitor{Module: collection.Module, Purpose: collection.Purpose, Field: collection.Metrics}
		monitors = append(monitors, monitor)
	}

Z
Zhipeng Xie 已提交
1116
	sampleNum := s.Raw.Section("server").Key("sample_num").MustInt(20)
D
dogsheng 已提交
1117
	collectorBody := new(CollectorPost)
Z
Zhipeng Xie 已提交
1118
	collectorBody.SampleNum = sampleNum
D
dogsheng 已提交
1119 1120
	collectorBody.Monitors = monitors
	collectorBody.Pipe = npipe
1121
	collectorBody.File = "/run/atuned/test.csv"
D
dogsheng 已提交
1122 1123 1124

	respCollectPost, err := collectorBody.Post()
	if err != nil {
Z
Zhipeng Xie 已提交
1125
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
D
dogsheng 已提交
1126 1127 1128
		return err
	}

G
gaoruoshu 已提交
1129
	dataPath, err := Post("classification", "file", respCollectPost.Path)
1130
	if err != nil {
G
gaoruoshu 已提交
1131
		log.Errorf("Failed transfer file to server: %v", err)
1132 1133 1134
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
		return err
	}
G
gaoruoshu 已提交
1135
	defer os.Remove(dataPath)
1136

D
dogsheng 已提交
1137 1138
	//2. send the collected data to the model for completion type identification
	body := new(ClassifyPostBody)
G
gaoruoshu 已提交
1139
	body.Data = dataPath
D
dogsheng 已提交
1140 1141 1142 1143 1144
	body.ModelPath = path.Join(config.DefaultAnalysisPath, "models")

	respPostIns, err := body.Post()

	if err != nil {
Z
Zhipeng Xie 已提交
1145
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
D
dogsheng 已提交
1146 1147 1148 1149
		return err
	}

	workloadType := respPostIns.WorkloadType
Z
Zhipeng Xie 已提交
1150
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 2. Current System Workload Characterization is %s", workloadType)})
D
dogsheng 已提交
1151 1152 1153 1154 1155
	return nil
}

// Define method user define workload type and profile
func (s *ProfileServer) Define(ctx context.Context, message *PB.DefineMessage) (*PB.Ack, error) {
1156 1157 1158 1159 1160 1161 1162 1163
	isLocalAddr, err := SVC.CheckRpcIsLocalAddr(ctx)
	if err != nil {
		return &PB.Ack{}, err
	}
	if !isLocalAddr {
		return &PB.Ack{}, fmt.Errorf("the define command can not be remotely operated")
	}

1164 1165 1166
	serviceType := message.GetServiceType()
	applicationName := message.GetApplicationName()
	scenarioName := message.GetScenarioName()
D
dogsheng 已提交
1167
	content := string(message.GetContent())
1168
	profileName := serviceType + "-" + applicationName + "-" + scenarioName
D
dogsheng 已提交
1169

1170
	workloadTypeExist, err := sqlstore.ExistWorkloadType(profileName)
D
dogsheng 已提交
1171 1172 1173
	if err != nil {
		return &PB.Ack{}, err
	}
1174 1175 1176 1177 1178 1179
	if !workloadTypeExist {
		if err = sqlstore.InsertClassApps(&sqlstore.ClassApps{
			Class:     profileName,
			Deletable: true}); err != nil {
			return &PB.Ack{}, err
		}
D
dogsheng 已提交
1180 1181
	}

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
	profileNameExist, err := sqlstore.ExistProfileName(profileName)
	if err != nil {
		return &PB.Ack{}, err
	}
	if !profileNameExist {
		if err = sqlstore.InsertClassProfile(&sqlstore.ClassProfile{
			Class:       profileName,
			ProfileType: profileName,
			Active:      false}); err != nil {
			return &PB.Ack{}, err
		}
	}

	profileExist, err := profile.ExistProfile(profileName)
D
dogsheng 已提交
1196 1197 1198 1199 1200 1201 1202 1203
	if err != nil {
		return &PB.Ack{}, err
	}

	if profileExist {
		return &PB.Ack{Status: fmt.Sprintf("%s is already exist", profileName)}, nil
	}

1204 1205 1206
	dstPath := path.Join(config.DefaultProfilePath, serviceType, applicationName)
	err = utils.CreateDir(dstPath, utils.FilePerm)
	if err != nil {
D
dogsheng 已提交
1207 1208 1209
		return &PB.Ack{}, err
	}

1210 1211 1212 1213
	dstFile := path.Join(dstPath, fmt.Sprintf("%s.conf", scenarioName))
	err = utils.WriteFile(dstFile, content, utils.FilePerm, os.O_WRONLY|os.O_CREATE)
	if err != nil {
		log.Error(err)
D
dogsheng 已提交
1214 1215 1216 1217 1218 1219 1220
		return &PB.Ack{}, err
	}

	return &PB.Ack{Status: "OK"}, nil
}

// Delete method delete the self define workload type from database
1221
func (s *ProfileServer) Delete(ctx context.Context, message *PB.ProfileInfo) (*PB.Ack, error) {
1222 1223 1224 1225 1226 1227 1228 1229
	isLocalAddr, err := SVC.CheckRpcIsLocalAddr(ctx)
	if err != nil {
		return &PB.Ack{}, err
	}
	if !isLocalAddr {
		return &PB.Ack{}, fmt.Errorf("the undefine command can not be remotely operated")
	}

1230
	profileName := message.GetName()
D
dogsheng 已提交
1231

1232 1233
	classApps := &sqlstore.GetClassApp{Class: profileName}
	if err = sqlstore.GetClassApps(classApps); err != nil {
D
dogsheng 已提交
1234 1235 1236
		return &PB.Ack{}, err
	}

1237 1238
	if len(classApps.Result) != 1 || !classApps.Result[0].Deletable {
		return &PB.Ack{Status: "only self defined type can be deleted"}, nil
D
dogsheng 已提交
1239 1240
	}

1241
	if err = sqlstore.DeleteClassApps(profileName); err != nil {
D
dogsheng 已提交
1242 1243 1244
		return &PB.Ack{}, err
	}

1245 1246 1247
	profileNameExist, err := sqlstore.ExistProfileName(profileName)
	if err != nil {
		return &PB.Ack{}, err
D
dogsheng 已提交
1248
	}
1249 1250 1251
	if profileNameExist {
		if err := sqlstore.DeleteClassProfile(profileName); err != nil {
			log.Errorf("delete item from class_profile table failed %v ", err)
D
dogsheng 已提交
1252 1253 1254
		}
	}

1255 1256
	if err := profile.DeleteProfile(profileName); err != nil {
		log.Errorf("delete item from profile table failed %v", err)
D
dogsheng 已提交
1257
	}
1258

D
dogsheng 已提交
1259 1260 1261 1262
	return &PB.Ack{Status: "OK"}, nil
}

// Update method update the content of the specified workload type from database
1263
func (s *ProfileServer) Update(ctx context.Context, message *PB.ProfileInfo) (*PB.Ack, error) {
1264 1265 1266 1267 1268 1269 1270 1271
	isLocalAddr, err := SVC.CheckRpcIsLocalAddr(ctx)
	if err != nil {
		return &PB.Ack{}, err
	}
	if !isLocalAddr {
		return &PB.Ack{}, fmt.Errorf("the update command can not be remotely operated")
	}

1272
	profileName := message.GetName()
D
dogsheng 已提交
1273 1274
	content := string(message.GetContent())

1275
	profileExist, err := profile.ExistProfile(profileName)
D
dogsheng 已提交
1276 1277 1278 1279
	if err != nil {
		return &PB.Ack{}, err
	}

1280 1281
	if !profileExist {
		return &PB.Ack{}, fmt.Errorf("profile name %s is exist", profileName)
D
dogsheng 已提交
1282 1283
	}

1284 1285
	err = profile.UpdateProfile(profileName, content)
	if err != nil {
D
dogsheng 已提交
1286 1287 1288 1289 1290
		return &PB.Ack{}, err
	}
	return &PB.Ack{Status: "OK"}, nil
}

Z
Zhipeng Xie 已提交
1291 1292 1293
// Schedule cpu/irq/numa ...
func (s *ProfileServer) Schedule(message *PB.ScheduleMessage,
	stream PB.ProfileMgr_ScheduleServer) error {
1294
	pids := message.GetApp()
D
dogsheng 已提交
1295 1296 1297 1298
	Strategy := message.GetStrategy()

	scheduler := schedule.GetScheduler()

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	ch := make(chan *PB.AckCheck)
	defer close(ch)
	go func() {
		for value := range ch {
			_ = stream.Send(value)
		}
	}()

	err := scheduler.Schedule(pids, Strategy, true, ch)

	if err != nil {
		_ = stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
		return err
	}

	_ = stream.Send(&PB.AckCheck{Name: "schedule finished"})
D
dogsheng 已提交
1315 1316
	return nil
}
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384

func (s *ProfileServer) collection() (*RespCollectorPost, error) {
	//1. get the dimension structure of the system data to be collected
	collections, err := sqlstore.GetCollections()
	if err != nil {
		log.Errorf("inquery collection tables error: %v", err)
		return nil, err
	}

	// 1.1 send the collect data command to the monitor service
	monitors := make([]Monitor, 0)
	for _, collection := range collections {
		re := regexp.MustCompile(`\{([^}]+)\}`)
		matches := re.FindAllStringSubmatch(collection.Metrics, -1)
		if len(matches) > 0 {
			for _, match := range matches {
				if len(match) < 2 {
					continue
				}
				var value string
				if s.Raw.Section("system").Haskey(match[1]) {
					value = s.Raw.Section("system").Key(match[1]).Value()
				} else if s.Raw.Section("server").Haskey(match[1]) {
					value = s.Raw.Section("server").Key(match[1]).Value()
				} else {
					return nil, fmt.Errorf("%s is not exist in the system or server section", match[1])
				}
				re = regexp.MustCompile(`\{(` + match[1] + `)\}`)
				collection.Metrics = re.ReplaceAllString(collection.Metrics, value)
			}
		}

		monitor := Monitor{Module: collection.Module, Purpose: collection.Purpose, Field: collection.Metrics}
		monitors = append(monitors, monitor)
	}

	sampleNum := s.Raw.Section("server").Key("sample_num").MustInt(20)
	collectorBody := new(CollectorPost)
	collectorBody.SampleNum = sampleNum
	collectorBody.Monitors = monitors
	collectorBody.File = "/run/atuned/test.csv"

	log.Infof("tuning collector body is:", collectorBody)
	respCollectPost, err := collectorBody.Post()
	if err != nil {
		return nil, err
	}
	return respCollectPost, nil
}

func (s *ProfileServer) classify(dataPath string) (string, string, error) {
	//2. send the collected data to the model for completion type identification
	var resourceLimit string
	var workloadType string
	dataPath, err := Post("classification", "file", dataPath)
	if err != nil {
		log.Errorf("Failed transfer file to server: %v", err)
		return workloadType, resourceLimit, err
	}
	body := new(ClassifyPostBody)
	body.Data = dataPath
	body.ModelPath = path.Join(config.DefaultAnalysisPath, "models")

	respPostIns, err := body.Post()
	if err != nil {
		return workloadType, resourceLimit, err
	}

1385
	log.Infof("workload: %s, cluster result resource limit: %s",
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
		respPostIns.WorkloadType, respPostIns.ResourceLimit)
	resourceLimit = respPostIns.ResourceLimit
	workloadType = respPostIns.WorkloadType
	return workloadType, resourceLimit, nil
}

func (s *ProfileServer) Getworkload() (string, error) {
	respCollectPost, err := s.collection()
	if err != nil {
		return "", err
	}

	workload, _, err := s.classify(respCollectPost.Path)
	if err != nil {
		return "", err
	}
	if len(workload) == 0 {
		return "", fmt.Errorf("workload is empty")
	}
	return workload, nil
}

// Generate method generate the yaml file for tuning
func (s *ProfileServer) Generate(message *PB.ProfileInfo, stream PB.ProfileMgr_GenerateServer) error {
	ch := make(chan *PB.AckCheck)
	defer close(ch)
	go func() {
		for value := range ch {
			_ = stream.Send(value)
		}
	}()

	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("1.Start to analysis the system bottleneck")})
	respCollectPost, err := s.collection()
	if err != nil {
		return err
	}
	log.Infof("collect data response body is: %+v", respCollectPost)
	collectData := respCollectPost.Data
	projectName := message.GetName()

	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("2.Finding potential tuning parameters")})

	var tuningData tuning.TuningData
	err = mapstructure.Decode(collectData, &tuningData)
	if err != nil {
		return err
	}
	log.Infof("decode to structure is: %+v", tuningData)

	ruleFile := path.Join(config.DefaultRulePath, config.TuningRuleFile)
	engine := tuning.NewRuleEngine(ruleFile)
	if engine == nil {
		fmt.Errorf("create rules engine failed")
	}

	tuningFile := tuning.NewTuningFile(projectName, ch)
	err = tuningFile.Load()
	if err != nil {
		return err
	}
	engine.AddContext("TuningData", &tuningData)
	engine.AddContext("TuningFile", tuningFile)
	err = engine.Execute()
	if err != nil {
		return err
	}

	if len(tuningFile.PrjSrv.Object) <= 0 {
		_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("   No tuning parameters founed")})
		return nil
	}
	dstFile := path.Join(config.DefaultTuningPath, fmt.Sprintf("%s.yaml", projectName))
	log.Infof("generate tuning file: %s", dstFile)

	err = tuningFile.Save(dstFile)
	if err != nil {
		return err
	}
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("3. Generate tuning project: %s\n    project name: %s", dstFile, projectName)})

	return nil
}