Exemple #1
0
// Subscribes a customer to a new plan.
//
// see https://stripe.com/docs/api#update_subscription
func (self *SubscriptionClient) Update(customerId string, params *SubscriptionParams) (*Subscription, error) {
	values := url.Values{"plan": {params.Plan}}

	// set optional parameters
	if len(params.Coupon) != 0 {
		values.Add("coupon", params.Coupon)
	}
	if params.Prorate {
		values.Add("prorate", "true")
	}
	if params.TrialEnd != 0 {
		values.Add("trial_end", strconv.FormatInt(params.TrialEnd, 10))
	}
	if params.Quantity != 0 {
		values.Add("quantity", strconv.FormatInt(params.Quantity, 10))
	}
	// attach a new card, if requested
	if len(params.Token) != 0 {
		values.Add("card", params.Token)
	} else if params.Card != nil {
		appendCardParamsToValues(params.Card, &values)
	}

	s := Subscription{}
	path := "/v1/customers/" + url.QueryEscape(customerId) + "/subscription"
	err := query("POST", path, values, &s)
	return &s, err
}
Exemple #2
0
// human friendly version string - major.minor.patch
func (v Version) String() string {
	return strings.Join(([]string{
		strconv.FormatInt(v.Major, BASE10),
		strconv.FormatInt(v.Minor, BASE10),
		strconv.FormatInt(v.Patch, BASE10)}),
		SEPARATOR)
}
func joinCpu(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "cpu")
	if err != nil && !cgroups.IsNotFound(err) {
		return err
	}
	if c.CpuQuota != 0 {
		if err = writeFile(path, "cpu.cfs_quota_us", strconv.FormatInt(c.CpuQuota, 10)); err != nil {
			return err
		}
	}
	if c.CpuPeriod != 0 {
		if err = writeFile(path, "cpu.cfs_period_us", strconv.FormatInt(c.CpuPeriod, 10)); err != nil {
			return err
		}
	}
	if c.CpuRtPeriod != 0 {
		if err = writeFile(path, "cpu.rt_period_us", strconv.FormatInt(c.CpuRtPeriod, 10)); err != nil {
			return err
		}
	}
	if c.CpuRtRuntime != 0 {
		if err = writeFile(path, "cpu.rt_runtime_us", strconv.FormatInt(c.CpuRtRuntime, 10)); err != nil {
			return err
		}
	}

	return nil
}
Exemple #4
0
// UpdateAutoScalingGroup updates the scaling group.
//
// To update an auto scaling group with a launch configuration that has the InstanceMonitoring
// flag set to False, you must first ensure that collection of group metrics is disabled.
// Otherwise calls to UpdateAutoScalingGroup will fail.
func (as *AutoScaling) UpdateAutoScalingGroup(ag AutoScalingGroup) (resp *SimpleResp, err error) {
	resp = &SimpleResp{}
	params := makeParams("UpdateAutoScalingGroup")
	params["AutoScalingGroupName"] = ag.AutoScalingGroupName
	addParamsList(params, "AvailabilityZones.member", ag.AvailabilityZones)
	if ag.DefaultCooldown > 0 {
		params["DefaultCooldown"] = strconv.FormatInt(ag.DefaultCooldown, 10)
	}
	params["DesiredCapacity"] = strconv.FormatInt(ag.DesiredCapacity, 10)
	if ag.HealthCheckGracePeriod > 0 {
		params["HealthCheckGracePeriod"] = strconv.FormatInt(ag.HealthCheckGracePeriod, 10)
	}
	if ag.HealthCheckType == "ELB" {
		params["HealthCheckType"] = ag.HealthCheckType
	}
	params["LaunchConfigurationName"] = ag.LaunchConfigurationName
	if ag.MaxSize > 0 {
		params["MaxSize"] = strconv.FormatInt(ag.MaxSize, 10)
	}
	if ag.MinSize > 0 {
		params["MinSize"] = strconv.FormatInt(ag.MinSize, 10)
	}
	if len(ag.TerminationPolicies) > 0 {
		addParamsList(params, "TerminationPolicies.member", ag.TerminationPolicies)
	}
	if len(ag.VPCZoneIdentifier) > 0 {
		params["VPCZoneIdentifier"] = ag.VPCZoneIdentifier
	}
	err = as.query(params, resp)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
Exemple #5
0
func newLabels(container *api.Container, pod *api.Pod, restartCount int) map[string]string {
	labels := map[string]string{}
	labels[kubernetesPodNameLabel] = pod.Name
	labels[kubernetesPodNamespaceLabel] = pod.Namespace
	labels[kubernetesPodUIDLabel] = string(pod.UID)
	if pod.DeletionGracePeriodSeconds != nil {
		labels[kubernetesPodDeletionGracePeriodLabel] = strconv.FormatInt(*pod.DeletionGracePeriodSeconds, 10)
	}
	if pod.Spec.TerminationGracePeriodSeconds != nil {
		labels[kubernetesPodTerminationGracePeriodLabel] = strconv.FormatInt(*pod.Spec.TerminationGracePeriodSeconds, 10)
	}

	labels[kubernetesContainerNameLabel] = container.Name
	labels[kubernetesContainerHashLabel] = strconv.FormatUint(kubecontainer.HashContainer(container), 16)
	labels[kubernetesContainerRestartCountLabel] = strconv.Itoa(restartCount)
	labels[kubernetesContainerTerminationMessagePathLabel] = container.TerminationMessagePath
	if container.Lifecycle != nil && container.Lifecycle.PreStop != nil {
		// Using json enconding so that the PreStop handler object is readable after writing as a label
		rawPreStop, err := json.Marshal(container.Lifecycle.PreStop)
		if err != nil {
			glog.Errorf("Unable to marshal lifecycle PreStop handler for container %q of pod %q: %v", container.Name, format.Pod(pod), err)
		} else {
			labels[kubernetesContainerPreStopHandlerLabel] = string(rawPreStop)
		}
	}

	return labels
}
Exemple #6
0
func (txn *dbTxn) Inc(k kv.Key, step int64) (int64, error) {
	log.Debugf("Inc %q, step %d txn:%d", k, step, txn.tid)
	k = kv.EncodeKey(k)

	txn.markOrigin(k)
	val, err := txn.UnionStore.Get(k)
	if kv.IsErrNotFound(err) {
		err = txn.UnionStore.Set(k, []byte(strconv.FormatInt(step, 10)))
		if err != nil {
			return 0, errors.Trace(err)
		}

		return step, nil
	}
	if err != nil {
		return 0, errors.Trace(err)
	}

	intVal, err := strconv.ParseInt(string(val), 10, 0)
	if err != nil {
		return intVal, errors.Trace(err)
	}

	intVal += step
	err = txn.UnionStore.Set(k, []byte(strconv.FormatInt(intVal, 10)))
	if err != nil {
		return 0, errors.Trace(err)
	}
	txn.store.compactor.OnSet(k)
	return intVal, nil
}
Exemple #7
0
// UploadSignedURL returns a signed URL that allows anyone holding the URL
// to upload the object at path. The signature is valid until expires.
// contenttype is a string like image/png
// path is the resource name in s3 terminalogy like images/ali.png [obviously exclusing the bucket name itself]
func (b *Bucket) UploadSignedURL(path, method, content_type string, expires time.Time) string {
	expire_date := expires.Unix()
	if method != "POST" {
		method = "PUT"
	}
	stringToSign := method + "\n\n" + content_type + "\n" + strconv.FormatInt(expire_date, 10) + "\n/" + b.Name + "/" + path
	fmt.Println("String to sign:\n", stringToSign)
	a := b.S3.Auth
	secretKey := a.SecretKey
	accessId := a.AccessKey
	mac := hmac.New(sha1.New, []byte(secretKey))
	mac.Write([]byte(stringToSign))
	macsum := mac.Sum(nil)
	signature := base64.StdEncoding.EncodeToString([]byte(macsum))
	signature = strings.TrimSpace(signature)

	signedurl, err := url.Parse("https://" + b.Name + ".s3.amazonaws.com/")
	if err != nil {
		log.Println("ERROR sining url for S3 upload", err)
		return ""
	}
	signedurl.Path += path
	params := url.Values{}
	params.Add("AWSAccessKeyId", accessId)
	params.Add("Expires", strconv.FormatInt(expire_date, 10))
	params.Add("Signature", signature)
	if a.Token() != "" {
		params.Add("token", a.Token())
	}

	signedurl.RawQuery = params.Encode()
	return signedurl.String()
}
Exemple #8
0
func (q Query) String() string {
	s := q.Aggregator + ":"
	if q.Downsample != "" {
		s += q.Downsample + ":"
	}
	if q.Rate {
		s += "rate"
		if q.RateOptions.Counter {
			s += "{counter"
			if q.RateOptions.CounterMax != 0 {
				s += ","
				s += strconv.FormatInt(q.RateOptions.CounterMax, 10)
			}
			if q.RateOptions.ResetValue != 0 {
				if q.RateOptions.CounterMax == 0 {
					s += ","
				}
				s += ","
				s += strconv.FormatInt(q.RateOptions.ResetValue, 10)
			}
			s += "}"
		}
		s += ":"
	}
	s += q.Metric
	if len(q.Tags) > 0 {
		s += q.Tags.String()
	}
	if len(q.Filters) > 0 {
		s += q.Filters.String()
	}
	return s
}
Exemple #9
0
func checkOut() bool {
	value := strconv.FormatInt(int64(linuxSpec.Spec.Process.User.UID), 10)
	job := "Uid"
	resultTag := false
	if checkResult(job, value) {
		resultTag = true
	} else {
		resultTag = false
	}

	value = strconv.FormatInt(int64(linuxSpec.Spec.Process.User.GID), 10)
	job = "Gid"
	if checkResult(job, value) {
		resultTag = true
	} else {
		resultTag = false
	}

	tmpValue := linuxSpec.Spec.Process.User.AdditionalGids
	job = "Groups"
	for _, tv := range tmpValue {
		tvs := strconv.FormatInt(int64(tv), 10)
		if checkResult(job, tvs) {
			resultTag = true
		} else {
			resultTag = false
		}
	}

	return resultTag
}
func (hp *HttpProtocol) transData(server string, transData *TransData) (err error) {
	/* compose req */
	uri := hp.regTopic.ReplaceAllString(hp.uri, transData.topic)
	uri = hp.regMethod.ReplaceAllString(uri, transData.method)
	uri = hp.regPartition.ReplaceAllString(uri, strconv.FormatInt(int64(transData.partition), 10))
	uri = hp.regTransid.ReplaceAllString(uri, strconv.FormatInt(transData.transid, 10))
	url := fmt.Sprintf("http://%s%s", server, uri)
	req, err := http.NewRequest("POST", url, bytes.NewReader(transData.data))
	if err != nil {
		logger.Warning("module [%s]: fail to transData: url=%s, topic=%s, partition=%d, transid=%d, method=%s, err=%s", hp.moduleName, url, transData.topic, transData.partition, transData.transid, transData.method, err.Error())
		return err
	}
	/* add header */
	req.Header = hp.header
	req.Host = hp.reqHeaderHost
	/* Post */
	res, err := hp.client.Do(req)
	if err != nil {
		logger.Warning("module [%s]: fail to transData: url=%s, topic=%s, partition=%d, transid=%d, method=%s, err=%s", hp.moduleName, url, transData.topic, transData.partition, transData.transid, transData.method, err.Error())
		return err
	}
	defer res.Body.Close()
	/* check res: 200 不重试;其他,重试 */
	if res.StatusCode == http.StatusOK {
		logger.Notice("module [%s]: success transData: url=%s, topic=%s, partition=%d, transid=%d, method=%s, datalen=%d, http_status_code=%d", hp.moduleName, url, transData.topic, transData.partition, transData.transid, transData.method, len(transData.data), res.StatusCode)
		return nil
	} else {
		logger.Warning("module [%s]: fail to transData: url=%s, topic=%s, partition=%d, transid=%d, method=%s, http_status_code=%d", hp.moduleName, url, transData.topic, transData.partition, transData.transid, transData.method, res.StatusCode)
		return errors.New("fail to trans")
	}
	return nil
}
Exemple #11
0
func (i Int) floatString(verb byte, prec int) string {
	switch verb {
	case 'f', 'F':
		str := strconv.FormatInt(int64(i), 10)
		if prec > 0 {
			str += "." + zeros(prec)
		}
		return str
	case 'e', 'E':
		sign := ""
		if i < 0 {
			sign = "-"
			i = -i
		}
		return eFormat(verb, prec, sign, strconv.FormatInt(int64(i), 10), i.eExponent())
	case 'g', 'G':
		// Exponent is always positive so it's easy.
		if i.eExponent() >= prec {
			// Use e format.
			return i.floatString(verb-2, prec-1)
		}
		// Use f format, but this is just an integer.
		return fmt.Sprintf("%d", int64(i))
	default:
		Errorf("can't handle verb %c for int", verb)
	}
	return ""
}
Exemple #12
0
//checkResults checks the results between
func checkResults() string {
	for metric, expected := range expectedValues {
		switch m := metric.(type) {
		case *metrics.Counter:
			val, ok := expected.(uint64)
			if !ok {
				return "unexpected type"
			}
			if m.Get() != val {
				return ("unexpected value - got: " +
					strconv.FormatInt(int64(m.Get()), 10) + " but wanted " + strconv.FormatInt(int64(val), 10))
			}
		case *metrics.Gauge:
			val, ok := expected.(float64)
			if !ok {
				return "unexpected type"
			}
			if m.Get() != val {
				return ("unexpected value - got: " +
					strconv.FormatFloat(float64(m.Get()), 'f', 5, 64) + " but wanted " +
					strconv.FormatFloat(float64(val), 'f', 5, 64))
			}
		}
	}
	return ""
}
Exemple #13
0
// ToString converts a interface to a string.
func ToString(value interface{}) (string, error) {
	switch v := value.(type) {
	case bool:
		if v {
			return "1", nil
		}
		return "0", nil
	case int:
		return strconv.FormatInt(int64(v), 10), nil
	case int64:
		return strconv.FormatInt(int64(v), 10), nil
	case uint64:
		return strconv.FormatUint(uint64(v), 10), nil
	case float32:
		return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
	case float64:
		return strconv.FormatFloat(float64(v), 'f', -1, 64), nil
	case string:
		return v, nil
	case []byte:
		return string(v), nil
	case mysql.Time:
		return v.String(), nil
	case mysql.Duration:
		return v.String(), nil
	case mysql.Decimal:
		return v.String(), nil
	case mysql.Hex:
		return v.ToString(), nil
	case mysql.Bit:
		return v.ToString(), nil
	default:
		return "", errors.Errorf("cannot convert %v(type %T) to string", value, value)
	}
}
Exemple #14
0
func (dir *Directory) save(i int64, l [][]string) error {
	b := new(bytes.Buffer)
	w := csv.NewWriter(b)
	w.WriteAll(l)
	w.Flush()

	// done!

	part := strconv.FormatInt(i, 10) + "."
	p, e := LoadDPs(dir.R, part)
	if e != nil {
		p = new(DirPage)
		e = nil
	}
	p.Version = (p.Version + 1) % 8
	e = SaveDPs(dir.R, p, part)
	if e != nil {
		return e
	}
	pver := part + strconv.FormatInt(p.Version, 10)
	f, e := dir.R.Create(pver)
	if e != nil {
		return e
	}
	defer f.Close()
	e = f.Truncate(int64(b.Len()))
	if e != nil {
		return e
	}
	_, e = f.WriteAt(b.Bytes(), 0)
	return e
}
Exemple #15
0
// Coerce types (string,int,int64, float, []byte) into String type
func CoerceString(v interface{}) (string, error) {
	switch val := v.(type) {
	case string:
		if val == "null" || val == "NULL" {
			return "", nil
		}
		return val, nil
	case int:
		return strconv.Itoa(val), nil
	case int32:
		return strconv.FormatInt(int64(val), 10), nil
	case int64:
		return strconv.FormatInt(val, 10), nil
	case uint32:
		return strconv.FormatUint(uint64(val), 10), nil
	case uint64:
		return strconv.FormatUint(val, 10), nil
	case float32:
		return strconv.FormatFloat(float64(val), 'f', -1, 32), nil
	case float64:
		return strconv.FormatFloat(val, 'f', -1, 64), nil
	case []byte:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	case json.RawMessage:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	}
	return "", fmt.Errorf("Could not coerce to string: %v", v)
}
Exemple #16
0
// SignedURLWithMethod returns a signed URL that allows anyone holding the URL
// to either retrieve the object at path or make a HEAD request against it. The signature is valid until expires.
func (b *Bucket) SignedURLWithMethod(method, path string, expires time.Time, params url.Values, headers http.Header) string {
	var uv = url.Values{}

	if params != nil {
		uv = params
	}

	if b.S3.Signature == aws.V2Signature {
		uv.Set("Expires", strconv.FormatInt(expires.Unix(), 10))
	} else {
		uv.Set("X-Amz-Expires", strconv.FormatInt(expires.Unix()-time.Now().Unix(), 10))
	}

	req := &request{
		method:  method,
		bucket:  b.Name,
		path:    path,
		params:  uv,
		headers: headers,
	}
	err := b.S3.prepare(req)
	if err != nil {
		panic(err)
	}
	u, err := req.url()
	if err != nil {
		panic(err)
	}
	if b.S3.Auth.Token() != "" && b.S3.Signature == aws.V2Signature {
		return u.String() + "&x-amz-security-token=" + url.QueryEscape(req.headers["X-Amz-Security-Token"][0])
	} else {
		return u.String()
	}
}
Exemple #17
0
// Create a new volume.
func (ec2 *EC2Conn) CreateVolume(options *CreateVolume) (resp *CreateVolumeResp, err error) {
	params := makeParams("CreateVolume")
	params["AvailabilityZone"] = options.AvailZone
	if options.Size > 0 {
		params["Size"] = strconv.FormatInt(options.Size, 10)
	}

	if options.SnapshotId != "" {
		params["SnapshotId"] = options.SnapshotId
	}

	if options.VolumeType != "" {
		params["VolumeType"] = options.VolumeType
	}

	if options.IOPS > 0 {
		params["Iops"] = strconv.FormatInt(options.IOPS, 10)
	}

	resp = &CreateVolumeResp{}
	err = ec2.query(params, resp)
	if err != nil {
		return nil, err
	}

	return
}
Exemple #18
0
func TestGetSpot(t *testing.T) {
	opt := aetest.Options{AppID: "t2jp-2015", StronglyConsistentDatastore: true}
	inst, err := aetest.NewInstance(&opt)
	defer inst.Close()
	input, err := json.Marshal(Spot{SpotName: "foo", Body: "bar"})
	req, err := inst.NewRequest("POST", "/edit/v1/spots", bytes.NewBuffer(input))
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}
	loginUser := user.User{Email: "*****@*****.**", Admin: false, ID: "111111"}
	aetest.Login(&loginUser, req)
	// ctx := appengine.NewContext(req)
	res := httptest.NewRecorder()
	c := web.C{}
	spotCreateHandler(c, res, req)
	if res.Code != http.StatusCreated {
		t.Fatalf("Fail to request spots create, status code: %v", res.Code)
	}
	var getResponse GetResponse
	err = json.NewDecoder(res.Body).Decode(&getResponse)
	spotCode := getResponse.Item.SpotCode
	t.Logf("spot code: %v", strconv.FormatInt(spotCode, 10))
	getReq, err := inst.NewRequest("GET", "/edit/v1/spots/"+strconv.FormatInt(spotCode, 10), nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}
	getRes := httptest.NewRecorder()
	getC := web.C{URLParams: map[string]string{"spotCode": strconv.FormatInt(spotCode, 10)}}
	spotGetHandler(getC, getRes, getReq)
	if getRes.Code != http.StatusOK {
		t.Fatalf("Fail to request spot get, status code: %v", getRes.Code)
	}
}
Exemple #19
0
func handleLog(client *client.Client, namespace, podID string, logOptions *api.PodLogOptions, out io.Writer) error {
	// TODO: transform this into a PodLogOptions call
	req := client.RESTClient.Get().
		Namespace(namespace).
		Name(podID).
		Resource("pods").
		SubResource("log").
		Param("follow", strconv.FormatBool(logOptions.Follow)).
		Param("container", logOptions.Container).
		Param("previous", strconv.FormatBool(logOptions.Previous)).
		Param("timestamps", strconv.FormatBool(logOptions.Timestamps))

	if logOptions.SinceSeconds != nil {
		req.Param("sinceSeconds", strconv.FormatInt(*logOptions.SinceSeconds, 10))
	}
	if logOptions.SinceTime != nil {
		req.Param("sinceTime", logOptions.SinceTime.Format(time.RFC3339))
	}
	if logOptions.LimitBytes != nil {
		req.Param("limitBytes", strconv.FormatInt(*logOptions.LimitBytes, 10))
	}
	if logOptions.TailLines != nil {
		req.Param("tailLines", strconv.FormatInt(*logOptions.TailLines, 10))
	}
	readCloser, err := req.Stream()
	if err != nil {
		return err
	}

	defer readCloser.Close()
	_, err = io.Copy(out, readCloser)
	return err
}
Exemple #20
0
func (p *UpdateStoragePoolParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["capacitybytes"]; found {
		vv := strconv.FormatInt(v.(int64), 10)
		u.Set("capacitybytes", vv)
	}
	if v, found := p.p["capacityiops"]; found {
		vv := strconv.FormatInt(v.(int64), 10)
		u.Set("capacityiops", vv)
	}
	if v, found := p.p["enabled"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("enabled", vv)
	}
	if v, found := p.p["id"]; found {
		u.Set("id", v.(string))
	}
	if v, found := p.p["tags"]; found {
		vv := strings.Join(v.([]string), ",")
		u.Set("tags", vv)
	}
	return u
}
Exemple #21
0
func (k *Kraken) GetTradesHistory(tradeType string, showRelatedTrades bool, start, end, offset int64) {
	values := url.Values{}

	if len(tradeType) > 0 {
		values.Set("aclass", tradeType)
	}

	if showRelatedTrades {
		values.Set("trades", "true")
	}

	if start != 0 {
		values.Set("start", strconv.FormatInt(start, 10))
	}

	if end != 0 {
		values.Set("end", strconv.FormatInt(end, 10))
	}

	if offset != 0 {
		values.Set("offset", strconv.FormatInt(offset, 10))
	}

	result, err := k.SendAuthenticatedHTTPRequest(KRAKEN_TRADES_HISTORY, values)

	if err != nil {
		log.Println(err)
		return
	}

	log.Println(result)
}
Exemple #22
0
func prepareBlockDevices(params map[string]string, blockDevs []BlockDeviceMapping) {
	for i, b := range blockDevs {
		n := strconv.Itoa(i + 1)
		prefix := "BlockDeviceMapping." + n
		if b.DeviceName != "" {
			params[prefix+".DeviceName"] = b.DeviceName
		}
		if b.VirtualName != "" {
			params[prefix+".VirtualName"] = b.VirtualName
		}
		if b.SnapshotId != "" {
			params[prefix+".Ebs.SnapshotId"] = b.SnapshotId
		}
		if b.VolumeType != "" {
			params[prefix+".Ebs.VolumeType"] = b.VolumeType
		}
		if b.VolumeSize > 0 {
			params[prefix+".Ebs.VolumeSize"] = strconv.FormatInt(b.VolumeSize, 10)
		}
		if b.IOPS > 0 {
			params[prefix+".Ebs.Iops"] = strconv.FormatInt(b.IOPS, 10)
		}
		if b.DeleteOnTermination {
			params[prefix+".Ebs.DeleteOnTermination"] = "true"
		}
	}
}
Exemple #23
0
// PutScheduledUpdateGroupAction creates or updates a scheduled scaling action for an
// AutoScaling group. Scheduled actions can be made up to thirty days in advance. When updating
// a scheduled scaling action, if you leave a parameter unspecified, the corresponding value
// remains unchanged in the affected AutoScaling group.
//
// Auto Scaling supports the date and time expressed in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT
// only.
func (as *AutoScaling) PutScheduledUpdateGroupAction(rp PutScheduledActionRequestParams) (
	resp *SimpleResp, err error) {
	resp = &SimpleResp{}
	params := makeParams("PutScheduledUpdateGroupAction")
	params["AutoScalingGroupName"] = rp.AutoScalingGroupName
	params["ScheduledActionName"] = rp.ScheduledActionName
	if len(rp.EndTime) > 0 {
		params["EndTime"] = rp.EndTime
	}
	if len(rp.StartTime) > 0 {
		params["StartTime"] = rp.StartTime
	}
	if rp.MaxSize > 0 {
		params["MaxSize"] = strconv.FormatInt(rp.MaxSize, 10)
	}
	if rp.MinSize > 0 {
		params["MinSize"] = strconv.FormatInt(rp.MinSize, 10)
	}
	if len(rp.Recurrence) > 0 {
		params["Recurrence"] = rp.Recurrence
	}
	err = as.query(params, resp)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
Exemple #24
0
func (daemon *Daemon) initCgroupsPath(path string) error {
	if path == "/" || path == "." {
		return nil
	}

	daemon.initCgroupsPath(filepath.Dir(path))

	_, root, err := cgroups.FindCgroupMountpointAndRoot("cpu")
	if err != nil {
		return err
	}

	path = filepath.Join(root, path)
	sysinfo := sysinfo.New(false)
	if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
		return err
	}
	if sysinfo.CPURealtimePeriod && daemon.configStore.CPURealtimePeriod != 0 {
		if err := ioutil.WriteFile(filepath.Join(path, "cpu.rt_period_us"), []byte(strconv.FormatInt(daemon.configStore.CPURealtimePeriod, 10)), 0700); err != nil {
			return err
		}
	}
	if sysinfo.CPURealtimeRuntime && daemon.configStore.CPURealtimeRuntime != 0 {
		if err := ioutil.WriteFile(filepath.Join(path, "cpu.rt_runtime_us"), []byte(strconv.FormatInt(daemon.configStore.CPURealtimeRuntime, 10)), 0700); err != nil {
			return err
		}
	}

	return nil
}
Exemple #25
0
//登录
func (this *AccountController) Login() {

	if this.userid > 0 {
		this.Redirect("/admin", 302)
	}

	if this.GetString("dosubmit") == "yes" {
		account := strings.TrimSpace(this.GetString("account"))
		password := strings.TrimSpace(this.GetString("password"))
		remember := this.GetString("remember")
		if account != "" && password != "" {
			var user models.User
			user.Name = account
			if user.Read("name") != nil || user.Password != util.Md5([]byte(password)) {
				this.Data["errmsg"] = "帐号或密码错误"
			} else if user.Active == 0 {
				this.Data["errmsg"] = "该帐号未激活"
			} else {
				user.LoginCount += 1
				user.LastIp = this.getClientIp()
				user.LastLogin = this.getTime()
				user.Update()
				authkey := util.Md5([]byte(this.getClientIp() + "|" + user.Password))
				if remember == "yes" {
					this.Ctx.SetCookie("auth", strconv.FormatInt(user.Id, 10)+"|"+authkey, 7*86400)
				} else {
					this.Ctx.SetCookie("auth", strconv.FormatInt(user.Id, 10)+"|"+authkey)
				}

				this.Redirect("/admin", 302)
			}
		}
	}
	this.TplNames = this.moduleName + "/account/login.html"
}
Exemple #26
0
func (raw *rawCgroup) setupMemory(c *Cgroup, pid int) (err error) {
	dir, err := raw.join("memory", pid)
	// only return an error for memory if it was not specified
	if err != nil && (c.Memory != 0 || c.MemorySwap != 0) {
		return err
	}
	defer func() {
		if err != nil {
			os.RemoveAll(dir)
		}
	}()

	if c.Memory != 0 || c.MemorySwap != 0 {
		if c.Memory != 0 {
			if err := writeFile(dir, "memory.limit_in_bytes", strconv.FormatInt(c.Memory, 10)); err != nil {
				return err
			}
			if err := writeFile(dir, "memory.soft_limit_in_bytes", strconv.FormatInt(c.Memory, 10)); err != nil {
				return err
			}
		}
		// By default, MemorySwap is set to twice the size of RAM.
		// If you want to omit MemorySwap, set it to `-1'.
		if c.MemorySwap != -1 {
			if err := writeFile(dir, "memory.memsw.limit_in_bytes", strconv.FormatInt(c.Memory*2, 10)); err != nil {
				return err
			}
		}
	}
	return nil
}
Exemple #27
0
func addBlockDeviceParams(params map[string]string, blockdevices []BlockDeviceMapping) {
	for i, k := range blockdevices {
		// Fixup index since Amazon counts these from 1
		prefix := "BlockDeviceMapping." + strconv.Itoa(i+1) + "."

		if k.DeviceName != "" {
			params[prefix+"DeviceName"] = k.DeviceName
		}
		if k.VirtualName != "" {
			params[prefix+"VirtualName"] = k.VirtualName
		}
		if k.SnapshotId != "" {
			params[prefix+"Ebs.SnapshotId"] = k.SnapshotId
		}
		if k.VolumeType != "" {
			params[prefix+"Ebs.VolumeType"] = k.VolumeType
		}
		if k.IOPS != 0 {
			params[prefix+"Ebs.Iops"] = strconv.FormatInt(k.IOPS, 10)
		}
		if k.VolumeSize != 0 {
			params[prefix+"Ebs.VolumeSize"] = strconv.FormatInt(k.VolumeSize, 10)
		}
		if k.DeleteOnTermination {
			params[prefix+"Ebs.DeleteOnTermination"] = "true"
		}
	}
}
Exemple #28
0
// Route routes an update packet to the correct server.
func (r *Router) Route(cancelSignal <-chan bool, uaid, chid string, version int64, sentAt time.Time, logID string) (err error) {
	startTime := time.Now()
	locator := r.Locator()
	if locator == nil {
		if r.logger.ShouldLog(ERROR) {
			r.logger.Error("router", "No discovery service set; unable to route message",
				LogFields{"rid": logID, "uaid": uaid, "chid": chid})
		}
		r.metrics.Increment("router.broadcast.error")
		return ErrNoLocator
	}
	segment := capn.NewBuffer(nil)
	routable := NewRootRoutable(segment)
	routable.SetChannelID(chid)
	routable.SetVersion(version)
	routable.SetTime(sentAt.UnixNano())
	contacts, err := locator.Contacts(uaid)
	if err != nil {
		if r.logger.ShouldLog(CRITICAL) {
			r.logger.Critical("router", "Could not query discovery service for contacts",
				LogFields{"rid": logID, "error": err.Error()})
		}
		r.metrics.Increment("router.broadcast.error")
		return err
	}
	if r.logger.ShouldLog(DEBUG) {
		r.logger.Debug("router", "Fetched contact list from discovery service",
			LogFields{"rid": logID, "servers": strings.Join(contacts, ", ")})
	}
	if r.logger.ShouldLog(INFO) {
		r.logger.Info("router", "Sending push...", LogFields{
			"rid":     logID,
			"uaid":    uaid,
			"chid":    chid,
			"version": strconv.FormatInt(version, 10),
			"time":    strconv.FormatInt(sentAt.UnixNano(), 10)})
	}
	ok, err := r.notifyAll(cancelSignal, contacts, uaid, segment, logID)
	endTime := time.Now()
	if err != nil {
		if r.logger.ShouldLog(WARNING) {
			r.logger.Warn("router", "Could not post to server",
				LogFields{"rid": logID, "error": err.Error()})
		}
		r.metrics.Increment("router.broadcast.error")
		return err
	}
	var counterName, timerName string
	if ok {
		counterName = "router.broadcast.hit"
		timerName = "updates.routed.hits"
	} else {
		counterName = "router.broadcast.miss"
		timerName = "updates.routed.misses"
	}
	r.metrics.Increment(counterName)
	r.metrics.Timer(timerName, endTime.Sub(sentAt))
	r.metrics.Timer("router.handled", endTime.Sub(startTime))
	return nil
}
func joinMemory(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "memory")
	if err != nil && !cgroups.IsNotFound(err) {
		return err
	}

	// -1 disables memoryswap
	if c.MemorySwap > 0 {
		err = writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(c.MemorySwap, 10))
		if err != nil {
			return err
		}
	}
	if c.OomKillDisable {
		if err := writeFile(path, "memory.oom_control", "1"); err != nil {
			return err
		}
	}

	if c.MemorySwappiness >= 0 && c.MemorySwappiness <= 100 {
		err = writeFile(path, "memory.swappiness", strconv.FormatInt(c.MemorySwappiness, 10))
		if err != nil {
			return err
		}
	} else if c.MemorySwappiness == -1 {
		return nil
	} else {
		return fmt.Errorf("invalid value:%d. valid memory swappiness range is 0-100", c.MemorySwappiness)
	}

	return nil
}
Exemple #30
0
func Format_size(size int64) string {
	//size = 1073741824
	if size >= 1099511627776 {
		if size%1099511627776 == 0 {
			return strconv.FormatInt(size/1099511627776, 10) + " T"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1099511627776), 'f', 2, 64) + " T"
		}

	} else if size >= 1073741824 {
		if size%1073741824 == 0 {
			return strconv.FormatInt(size/1073741824, 10) + " G"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1073741824), 'f', 2, 64) + " G"
		}

	} else if size >= 1048576 {
		if size%1048576 == 0 {
			return strconv.FormatInt(size/1048576, 10) + " M"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1048576), 'f', 2, 64) + " M"
		}

	} else if size >= 1024 {
		if size%1024 == 0 {
			return strconv.FormatInt(size/1024, 10) + " K"
		} else {
			return strconv.FormatFloat(float64(size)/float64(1024), 'f', 2, 64) + " K"
		}

	} else {
		return strconv.FormatInt(size, 10) + " B"
	}

}