profile.go 37.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
	respCollectPost, err := s.collection(npipe)
D
dogsheng 已提交
409
	if err != nil {
Z
Zhipeng Xie 已提交
410
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
411
		log.Errorf("collection system data error: %v", err)
D
dogsheng 已提交
412 413 414
		return err
	}

415
	workloadType, resourceLimit, err := s.classify(respCollectPost.Path, message.GetModel())
416 417 418 419
	if err != nil {
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
		return err
	}
D
dogsheng 已提交
420 421 422

	//3. judge the workload type is exist in the database
	classProfile := &sqlstore.GetClass{Class: workloadType}
H
hanxinke 已提交
423
	if err = sqlstore.GetClasses(classProfile); err != nil {
H
hanxinke 已提交
424 425
		log.Errorf("inquery workload type table failed %v", err)
		return fmt.Errorf("inquery workload type table failed %v", err)
D
dogsheng 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
	}
	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
449
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 2. Current System Workload Characterization is %s", apps)})
D
dogsheng 已提交
450
	log.Infof("workload %s support app: %s", workloadType, apps)
Z
Zhipeng Xie 已提交
451
	log.Infof("workload %s resource limit: %s, cluster result resource limit: %s",
452
		workloadType, apps, resourceLimit)
D
dogsheng 已提交
453

Z
Zhipeng Xie 已提交
454
	_ = stream.Send(&PB.AckCheck{Name: "\n 3. Build the best resource model..."})
D
dogsheng 已提交
455 456 457 458 459 460

	//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 已提交
461
		return fmt.Errorf("no profile or invaild profiles were specified")
D
dogsheng 已提交
462 463 464 465
	}

	//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 已提交
466
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 4. Match profile: %s", profileType)})
D
dogsheng 已提交
467 468 469
	pro, _ := profile.Load(profileNames)
	pro.SetWorkloadType(workloadType)

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

	//static profile setting
Z
Zhipeng Xie 已提交
474 475 476 477
	ch := make(chan *PB.AckCheck)
	go func() {
		for value := range ch {
			_ = stream.Send(value)
D
dogsheng 已提交
478 479
		}
	}()
Z
Zhipeng Xie 已提交
480 481

	_ = pro.RollbackActive(ch)
D
dogsheng 已提交
482 483 484 485 486 487 488

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

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

Z
Zhipeng Xie 已提交
494 495
	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 已提交
496 497 498 499
	if err := tuning.RuleTuned(workloadType); err != nil {
		return err
	}

Z
Zhipeng Xie 已提交
500
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("Completed optimization, please restart application!")})
D
dogsheng 已提交
501 502 503 504
	return nil
}

// Tuning method calling the bayes search method to tuned parameters
505 506 507 508 509
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 已提交
510

511
	ch := make(chan *PB.TuningMessage)
512
	defer close(ch)
Z
Zhipeng Xie 已提交
513 514 515 516 517
	go func() {
		for value := range ch {
			_ = stream.Send(value)
		}
	}()
D
dogsheng 已提交
518

519
	var optimizer = tuning.Optimizer{}
520
	defer optimizer.DeleteTask()
521

522 523 524 525 526
	stopCh := make(chan int, 1)
	var cycles int32 = 0
	var message string
	var step int32 = 1

527
	for {
528 529 530
		select {
		case <-stopCh:
			if cycles > 0 {
531
				_ = stream.Send(&PB.TuningMessage{State: PB.TuningMessage_JobRestart})
532 533 534 535 536 537 538 539 540
			} else {
				_ = stream.Send(&PB.TuningMessage{State: PB.TuningMessage_Ending})
			}
			cycles--
		default:
		}
		if cycles < 0 {
			break
		}
541 542 543
		reply, err := stream.Recv()
		if err == io.EOF {
			break
544
		}
Z
Zhipeng Xie 已提交
545 546 547
		if err != nil {
			return err
		}
D
dogsheng 已提交
548

549 550 551 552 553 554
		state := reply.GetState()
		switch state {
		case PB.TuningMessage_SyncConfig:
			optimizer.Content = reply.GetContent()
			err = optimizer.SyncTunedNode(ch)
			if err != nil {
H
hanxinke 已提交
555 556
				return err
			}
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
		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 已提交
596

597
			if err = tuning.CheckServerPrj(project, &optimizer); err != nil {
598
				return err
D
dogsheng 已提交
599
			}
Z
Zhipeng Xie 已提交
600

601 602
			optimizer.Engine = reply.GetEngine()
			optimizer.Content = reply.GetContent()
603
			optimizer.Restart = reply.GetRestart()
604 605 606
			optimizer.RandomStarts = reply.GetRandomStarts()
			optimizer.FeatureFilterEngine = reply.GetFeatureFilterEngine()
			optimizer.FeatureFilterIters = reply.GetFeatureFilterIters()
607
			optimizer.SplitCount = reply.GetSplitCount()
608 609 610
			cycles = reply.GetFeatureFilterCycle()

			if cycles == 0 {
611 612 613 614 615
				if optimizer.Restart {
					message = fmt.Sprintf("%d.Continue to tuning the system......", step)
				} else {
					message = fmt.Sprintf("%d.Start to tuning the system......", step)
				}
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
				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 {
644 645 646
				return err
			}

647
		}
D
dogsheng 已提交
648 649 650 651 652 653 654 655 656
	}

	return nil
}

/*
UpgradeProfile method update the db file
*/
func (s *ProfileServer) UpgradeProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_UpgradeProfileServer) error {
657 658 659 660 661 662 663 664
	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 已提交
665 666 667 668 669 670 671 672 673
	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 已提交
674 675 676
		if err = os.MkdirAll(config.DefaultTempPath, 0750); err != nil {
			return err
		}
D
dogsheng 已提交
677 678 679 680 681
	}
	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 已提交
682
		_ = stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
D
dogsheng 已提交
683 684 685 686
		return nil
	}

	if err := utils.CopyFile(currenDbPath, newDbPath); err != nil {
Z
Zhipeng Xie 已提交
687
		_ = stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
D
dogsheng 已提交
688 689 690 691
		return nil
	}

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

Z
Zhipeng Xie 已提交
696
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("upgrade success"), Status: utils.SUCCESS})
D
dogsheng 已提交
697 698 699 700 701 702 703
	return nil
}

/*
InfoProfile method display the content of the specified workload type
*/
func (s *ProfileServer) InfoProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_InfoProfileServer) error {
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
	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 已提交
723

724 725
	if err != nil {
		return err
D
dogsheng 已提交
726 727
	}

728 729 730
	if context == "" {
		log.Errorf("profile %s is not exist", profileName)
		return fmt.Errorf("profile %s is not exist", profileName)
D
dogsheng 已提交
731 732 733 734 735 736 737 738
	}

	return nil
}

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

	profileLogs, err := sqlstore.GetProfileLogs()
D
dogsheng 已提交
744 745 746
	if err != nil {
		return err
	}
747 748 749 750 751 752 753

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

	if activeName == "" {
Z
Zhipeng Xie 已提交
754
		return fmt.Errorf("no active profile or more than 1 active profile")
D
dogsheng 已提交
755
	}
756 757 758 759 760 761 762 763 764
	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 已提交
765

766
	profile, ok := profile.LoadFromProfile(activeName)
D
dogsheng 已提交
767 768

	if !ok {
769 770
		log.WithField("profile", activeName).Errorf("Load profile %s Faild", activeName)
		return fmt.Errorf("load profile %s Faild", activeName)
D
dogsheng 已提交
771 772
	}

Z
Zhipeng Xie 已提交
773
	ch := make(chan *PB.AckCheck)
D
dogsheng 已提交
774
	defer close(ch)
Z
Zhipeng Xie 已提交
775 776 777
	go func() {
		for value := range ch {
			_ = stream.Send(value)
D
dogsheng 已提交
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
		}
	}()

	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 已提交
796
		_ = stream.Send(&PB.AckCheck{Name: "no profile need to rollback"})
D
dogsheng 已提交
797 798 799 800 801 802 803 804
		return nil
	}

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

	//static profile setting
Z
Zhipeng Xie 已提交
805 806 807 808
	ch := make(chan *PB.AckCheck)
	go func() {
		for value := range ch {
			_ = stream.Send(value)
D
dogsheng 已提交
809 810 811 812
		}
	}()

	for _, pro := range profileLogs {
Z
Zhipeng Xie 已提交
813
		log.Infof("begin to restore profile id: %d", pro.ID)
D
dogsheng 已提交
814
		profileInfo := profile.HistoryProfile{}
Z
Zhipeng Xie 已提交
815 816
		_ = profileInfo.Load(pro.Context)
		_ = profileInfo.Resume(ch)
D
dogsheng 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843

		// 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 {
844 845 846 847 848 849 850 851
	isLocalAddr, err := SVC.CheckRpcIsLocalAddr(stream.Context())
	if err != nil {
		return err
	}
	if !isLocalAddr {
		return fmt.Errorf("the collection command can not be remotely operated")
	}

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
	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())
	}

872 873
	classProfile := &sqlstore.GetClass{Class: message.GetType()}
	if err = sqlstore.GetClasses(classProfile); err != nil {
D
dogsheng 已提交
874 875
		return err
	}
876 877 878 879 880 881 882 883
	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 已提交
884 885 886 887 888 889 890 891 892 893
	}

	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 已提交
894
	if err = utils.InterfaceByName(message.GetNetwork()); err != nil {
D
dogsheng 已提交
895 896 897
		return err
	}

H
hanxinke 已提交
898
	if err = utils.DiskByName(message.GetBlock()); err != nil {
D
dogsheng 已提交
899 900 901
		return err
	}

902
	collections, err := sqlstore.GetCollections()
D
dogsheng 已提交
903
	if err != nil {
904
		log.Errorf("inquery collection tables error: %v", err)
D
dogsheng 已提交
905 906 907
		return err
	}

908 909 910 911 912 913 914 915 916
	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 已提交
917

918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
				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
941
	nowTime := time.Now().Format("20060702-150405")
942 943
	fileName := fmt.Sprintf("%s-%s.csv", message.GetWorkload(), nowTime)
	collectorBody.File = path.Join(message.GetOutputPath(), fileName)
944 945 946 947 948 949
	if include == "" {
		include = "default"
	}
	collectorBody.DataType = fmt.Sprintf("%s:%s", include, message.GetType())

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

	_, err = collectorBody.Post()
D
dogsheng 已提交
952
	if err != nil {
953
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
D
dogsheng 已提交
954 955 956
		return err
	}

957
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("generate %s successfully", collectorBody.File)})
D
dogsheng 已提交
958 959 960 961 962 963 964
	return nil
}

/*
Training method train the collected data to generate the model
*/
func (s *ProfileServer) Training(message *PB.TrainMessage, stream PB.ProfileMgr_TrainingServer) error {
965 966 967 968 969 970 971 972
	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 已提交
973 974 975
	DataPath := message.GetDataPath()
	OutputPath := message.GetOutputPath()

G
gaoruoshu 已提交
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
	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 已提交
991
	trainBody := new(models.Training)
G
gaoruoshu 已提交
992
	trainBody.DataPath = trainPath
D
dogsheng 已提交
993 994 995 996 997 998 999 1000
	trainBody.OutputPath = OutputPath
	trainBody.ModelPath = path.Join(config.DefaultAnalysisPath, "models")

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

H
hanxinke 已提交
1005
	_ = stream.Send(&PB.AckCheck{Name: "training the self collect data failed"})
D
dogsheng 已提交
1006 1007 1008 1009 1010
	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 已提交
1011
	_ = stream.Send(&PB.AckCheck{Name: "1. Analysis system runtime information: CPU Memory IO and Network..."})
D
dogsheng 已提交
1012 1013 1014

	npipe, err := utils.CreateNamedPipe()
	if err != nil {
H
hanxinke 已提交
1015
		return fmt.Errorf("create named pipe failed")
D
dogsheng 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
	}

	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 已提交
1027
			_ = stream.Send(&PB.AckCheck{Name: line, Status: utils.INFO})
D
dogsheng 已提交
1028 1029 1030
		}
	}()

1031
	respCollectPost, err := s.collection(npipe)
D
dogsheng 已提交
1032
	if err != nil {
1033
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
1034
		log.Errorf("collection system data error: %v", err)
1035 1036
		return err
	}
D
dogsheng 已提交
1037

1038 1039
	var customeModel string
	workloadType, _, err := s.classify(respCollectPost.Path, customeModel)
D
dogsheng 已提交
1040
	if err != nil {
Z
Zhipeng Xie 已提交
1041
		_ = stream.Send(&PB.AckCheck{Name: err.Error()})
D
dogsheng 已提交
1042 1043
		return err
	}
Z
Zhipeng Xie 已提交
1044
	_ = stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 2. Current System Workload Characterization is %s", workloadType)})
D
dogsheng 已提交
1045 1046 1047 1048 1049
	return nil
}

// Define method user define workload type and profile
func (s *ProfileServer) Define(ctx context.Context, message *PB.DefineMessage) (*PB.Ack, error) {
1050 1051 1052 1053 1054 1055 1056 1057
	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")
	}

1058 1059 1060
	serviceType := message.GetServiceType()
	applicationName := message.GetApplicationName()
	scenarioName := message.GetScenarioName()
D
dogsheng 已提交
1061
	content := string(message.GetContent())
1062
	profileName := serviceType + "-" + applicationName + "-" + scenarioName
D
dogsheng 已提交
1063

1064
	workloadTypeExist, err := sqlstore.ExistWorkloadType(profileName)
D
dogsheng 已提交
1065 1066 1067
	if err != nil {
		return &PB.Ack{}, err
	}
1068 1069 1070
	if !workloadTypeExist {
		if err = sqlstore.InsertClassApps(&sqlstore.ClassApps{
			Class:     profileName,
1071
			Apps:      profileName,
1072 1073 1074
			Deletable: true}); err != nil {
			return &PB.Ack{}, err
		}
D
dogsheng 已提交
1075 1076
	}

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
	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 已提交
1091 1092 1093 1094 1095 1096 1097 1098
	if err != nil {
		return &PB.Ack{}, err
	}

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

1099 1100 1101
	dstPath := path.Join(config.DefaultProfilePath, serviceType, applicationName)
	err = utils.CreateDir(dstPath, utils.FilePerm)
	if err != nil {
D
dogsheng 已提交
1102 1103 1104
		return &PB.Ack{}, err
	}

1105 1106 1107 1108
	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 已提交
1109 1110 1111 1112 1113 1114 1115
		return &PB.Ack{}, err
	}

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

// Delete method delete the self define workload type from database
1116
func (s *ProfileServer) Delete(ctx context.Context, message *PB.ProfileInfo) (*PB.Ack, error) {
1117 1118 1119 1120 1121 1122 1123 1124
	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")
	}

1125
	profileName := message.GetName()
D
dogsheng 已提交
1126

1127 1128
	classApps := &sqlstore.GetClassApp{Class: profileName}
	if err = sqlstore.GetClassApps(classApps); err != nil {
D
dogsheng 已提交
1129 1130 1131
		return &PB.Ack{}, err
	}

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

1136
	if err = sqlstore.DeleteClassApps(profileName); err != nil {
D
dogsheng 已提交
1137 1138 1139
		return &PB.Ack{}, err
	}

1140 1141 1142
	profileNameExist, err := sqlstore.ExistProfileName(profileName)
	if err != nil {
		return &PB.Ack{}, err
D
dogsheng 已提交
1143
	}
1144 1145 1146
	if profileNameExist {
		if err := sqlstore.DeleteClassProfile(profileName); err != nil {
			log.Errorf("delete item from class_profile table failed %v ", err)
D
dogsheng 已提交
1147 1148 1149
		}
	}

1150 1151
	if err := profile.DeleteProfile(profileName); err != nil {
		log.Errorf("delete item from profile table failed %v", err)
D
dogsheng 已提交
1152
	}
1153

D
dogsheng 已提交
1154 1155 1156 1157
	return &PB.Ack{Status: "OK"}, nil
}

// Update method update the content of the specified workload type from database
1158
func (s *ProfileServer) Update(ctx context.Context, message *PB.ProfileInfo) (*PB.Ack, error) {
1159 1160 1161 1162 1163 1164 1165 1166
	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")
	}

1167
	profileName := message.GetName()
D
dogsheng 已提交
1168 1169
	content := string(message.GetContent())

1170
	profileExist, err := profile.ExistProfile(profileName)
D
dogsheng 已提交
1171 1172 1173 1174
	if err != nil {
		return &PB.Ack{}, err
	}

1175 1176
	if !profileExist {
		return &PB.Ack{}, fmt.Errorf("profile name %s is exist", profileName)
D
dogsheng 已提交
1177 1178
	}

1179 1180
	err = profile.UpdateProfile(profileName, content)
	if err != nil {
D
dogsheng 已提交
1181 1182 1183 1184 1185
		return &PB.Ack{}, err
	}
	return &PB.Ack{Status: "OK"}, nil
}

Z
Zhipeng Xie 已提交
1186 1187 1188
// Schedule cpu/irq/numa ...
func (s *ProfileServer) Schedule(message *PB.ScheduleMessage,
	stream PB.ProfileMgr_ScheduleServer) error {
1189
	pids := message.GetApp()
D
dogsheng 已提交
1190 1191 1192 1193
	Strategy := message.GetStrategy()

	scheduler := schedule.GetScheduler()

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
	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 已提交
1210 1211
	return nil
}
1212

1213
func (s *ProfileServer) collection(npipe string) (*RespCollectorPost, error) {
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	//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"
1253 1254 1255
	if npipe != "" {
		collectorBody.Pipe = npipe
	}
1256 1257 1258 1259 1260 1261 1262 1263 1264

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

1265
func (s *ProfileServer) classify(dataPath string, customeModel string) (string, string, error) {
1266 1267 1268 1269 1270 1271 1272 1273
	//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
	}
1274 1275
	defer os.Remove(dataPath)

1276 1277 1278 1279
	body := new(ClassifyPostBody)
	body.Data = dataPath
	body.ModelPath = path.Join(config.DefaultAnalysisPath, "models")

1280 1281 1282
	if customeModel != "" {
		body.Model = customeModel
	}
1283 1284 1285 1286 1287
	respPostIns, err := body.Post()
	if err != nil {
		return workloadType, resourceLimit, err
	}

1288
	log.Infof("workload: %s, cluster result resource limit: %s",
1289 1290 1291 1292 1293 1294 1295
		respPostIns.WorkloadType, respPostIns.ResourceLimit)
	resourceLimit = respPostIns.ResourceLimit
	workloadType = respPostIns.WorkloadType
	return workloadType, resourceLimit, nil
}

func (s *ProfileServer) Getworkload() (string, error) {
1296 1297 1298
	var npipe string
	var customeModel string
	respCollectPost, err := s.collection(npipe)
1299 1300 1301 1302
	if err != nil {
		return "", err
	}

1303
	workload, _, err := s.classify(respCollectPost.Path, customeModel)
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
	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")})
1324 1325
	var npipe string
	respCollectPost, err := s.collection(npipe)
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
	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
}