<commit_before>package v2

import (
	"fmt"
	"net/url"
)

func upgradeV1(originalSimulation SimulationViewV1) SimulationViewV5 {
	var pairs []RequestMatcherResponsePairViewV5
	for _, pairV1 := range originalSimulation.RequestResponsePairViewV1 {

		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}
		var headers map[string][]string

		isNotRecording := pairV1.Request.RequestType != nil && *pairV1.Request.RequestType != "recording"

		if isNotRecording {
			headers = pairV1.Request.Headers
		}
		if pairV1.Request.Scheme != nil {

			if isNotRecording {
				schemeMatchers = append(schemeMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Scheme,
				})
			} else {
				schemeMatchers = append(schemeMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Scheme,
				})
			}
		}

		if pairV1.Request.Method != nil {
			if isNotRecording {
				methodMatchers = append(methodMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Method,
				})
			} else {
				methodMatchers = append(methodMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Method,
				})
			}
		}

		if pairV1.Request.Destination != nil {
			if isNotRecording {
				destinationMatchers = append(destinationMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Destination,
				})
			} else {
				destinationMatchers = append(destinationMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Destination,
				})
			}
		}

		if pairV1.Request.Path != nil {
			if isNotRecording {
				pathMatchers = append(pathMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Path,
				})
			} else {
				pathMatchers = append(pathMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Path,
				})
			}
		}

		if pairV1.Request.Query != nil {
			query, _ := url.QueryUnescape(*pairV1.Request.Query)
			if isNotRecording {
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   query,
				})
			} else {
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   query,
				})
			}
		}

		if pairV1.Request.Body != nil {
			if isNotRecording {
				bodyMatchers = append(bodyMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Body,
				})
			} else {
				bodyMatchers = append(bodyMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Body,
				})
			}
		}

		pair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Scheme:        schemeMatchers,
				Method:        methodMatchers,
				Destination:   destinationMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Body:          bodyMatchers,
				Headers:       headers,
				RequiresState: nil,
			},
			Response: ResponseDetailsViewV5{
				Body:        pairV1.Response.Body,
				EncodedBody: pairV1.Response.EncodedBody,
				Headers:     pairV1.Response.Headers,
				Status:      pairV1.Response.Status,
				Templated:   false,
			},
		}
		pairs = append(pairs, pair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: pairs,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func upgradeV2(originalSimulation SimulationViewV2) SimulationViewV5 {
	requestReponsePairs := []RequestMatcherResponsePairViewV5{}

	for _, requestResponsePairV2 := range originalSimulation.DataViewV2.RequestResponsePairs {
		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}

		schemeMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Scheme)
		methodMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Method)
		destinationMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Destination)
		pathMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Path)
		bodyMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Body)

		if requestResponsePairV2.RequestMatcher.Query != nil {
			if requestResponsePairV2.RequestMatcher.Query.ExactMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.ExactMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   unescapedQuery,
				})
			}
			if requestResponsePairV2.RequestMatcher.Query.GlobMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.GlobMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   unescapedQuery,
				})
			}
		}
		requestResponsePair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Destination:   destinationMatchers,
				Headers:       requestResponsePairV2.RequestMatcher.Headers,
				Method:        methodMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Scheme:        schemeMatchers,
				Body:          bodyMatchers,
				RequiresState: nil,
			},
			Response: ResponseDetailsViewV5{
				Body:        requestResponsePairV2.Response.Body,
				EncodedBody: requestResponsePairV2.Response.EncodedBody,
				Headers:     requestResponsePairV2.Response.Headers,
				Status:      requestResponsePairV2.Response.Status,
				Templated:   false,
			},
		}

		requestReponsePairs = append(requestReponsePairs, requestResponsePair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: requestReponsePairs,
			GlobalActions:        originalSimulation.GlobalActions,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func upgradeV3(originalSimulation SimulationViewV3) SimulationViewV5 {
	requestReponsePairs := []RequestMatcherResponsePairViewV5{}

	for _, requestResponsePairV2 := range originalSimulation.DataViewV3.RequestResponsePairs {
		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}

		schemeMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Scheme)
		methodMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Method)
		destinationMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Destination)
		pathMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Path)
		bodyMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Body)

		if requestResponsePairV2.RequestMatcher.Query != nil {
			if requestResponsePairV2.RequestMatcher.Query.ExactMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.ExactMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   unescapedQuery,
				})
			}
			if requestResponsePairV2.RequestMatcher.Query.GlobMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.GlobMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   unescapedQuery,
				})
			}
		}
		requestResponsePair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Destination:   destinationMatchers,
				Headers:       requestResponsePairV2.RequestMatcher.Headers,
				Method:        methodMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Scheme:        schemeMatchers,
				Body:          bodyMatchers,
				RequiresState: nil,
			},
			Response: ResponseDetailsViewV5{
				Body:        requestResponsePairV2.Response.Body,
				EncodedBody: requestResponsePairV2.Response.EncodedBody,
				Headers:     requestResponsePairV2.Response.Headers,
				Status:      requestResponsePairV2.Response.Status,
				Templated:   requestResponsePairV2.Response.Templated,
			},
		}

		requestReponsePairs = append(requestReponsePairs, requestResponsePair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: requestReponsePairs,
			GlobalActions:        originalSimulation.GlobalActions,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func upgradeV4(originalSimulation SimulationViewV4) SimulationViewV5 {
	requestReponsePairs := []RequestMatcherResponsePairViewV5{}

	for _, requestResponsePairV2 := range originalSimulation.DataViewV4.RequestResponsePairs {
		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}

		schemeMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Scheme)
		methodMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Method)
		destinationMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Destination)
		pathMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Path)
		bodyMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Body)

		if requestResponsePairV2.RequestMatcher.Query != nil {
			if requestResponsePairV2.RequestMatcher.Query.ExactMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.ExactMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   unescapedQuery,
				})
			}
			if requestResponsePairV2.RequestMatcher.Query.GlobMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.GlobMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   unescapedQuery,
				})
			}
		}
		requestResponsePair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Destination:   destinationMatchers,
				Headers:       requestResponsePairV2.RequestMatcher.Headers,
				Method:        methodMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Scheme:        schemeMatchers,
				Body:          bodyMatchers,
				RequiresState: requestResponsePairV2.RequestMatcher.RequiresState,
			},
			Response: ResponseDetailsViewV5{
				Body:        requestResponsePairV2.Response.Body,
				EncodedBody: requestResponsePairV2.Response.EncodedBody,
				Headers:     requestResponsePairV2.Response.Headers,
				Status:      requestResponsePairV2.Response.Status,
				Templated:   requestResponsePairV2.Response.Templated,
			},
		}

		requestReponsePairs = append(requestReponsePairs, requestResponsePair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: requestReponsePairs,
			GlobalActions:        originalSimulation.GlobalActions,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func v2GetMatchersFromRequestFieldMatchersView(requestFieldMatchers *RequestFieldMatchersView) []MatcherViewV5 {
	matchers := []MatcherViewV5{}
	if requestFieldMatchers != nil {
		if requestFieldMatchers.ExactMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "exact",
				Value:   *requestFieldMatchers.ExactMatch,
			})
		}
		if requestFieldMatchers.GlobMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "glob",
				Value:   *requestFieldMatchers.GlobMatch,
			})
		}
		if requestFieldMatchers.JsonMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "json",
				Value:   *requestFieldMatchers.JsonMatch,
			})
		}
		if requestFieldMatchers.JsonPathMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "jsonpath",
				Value:   *requestFieldMatchers.JsonPathMatch,
			})
		}
		if requestFieldMatchers.RegexMatch != nil {
			fmt.Println("in regex")
			matchers = append(matchers, MatcherViewV5{
				Matcher: "regex",
				Value:   *requestFieldMatchers.RegexMatch,
			})
		}
		if requestFieldMatchers.XmlMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "xml",
				Value:   *requestFieldMatchers.XmlMatch,
			})
		}
		if requestFieldMatchers.XpathMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "xpath",
				Value:   *requestFieldMatchers.XpathMatch,
			})
		}
	}
	return matchers
}

func newMetaView(originalMeta MetaView) MetaView {
	return MetaView{
		SchemaVersion:   "v5",
		HoverflyVersion: originalMeta.HoverflyVersion,
		TimeExported:    originalMeta.TimeExported,
	}
}
<commit_msg>Fixed bug where response.TransitionsState and response.RemovesState wasn't being copied as part of simulation upgrading<commit_after>package v2

import (
	"fmt"
	"net/url"
)

func upgradeV1(originalSimulation SimulationViewV1) SimulationViewV5 {
	var pairs []RequestMatcherResponsePairViewV5
	for _, pairV1 := range originalSimulation.RequestResponsePairViewV1 {

		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}
		var headers map[string][]string

		isNotRecording := pairV1.Request.RequestType != nil && *pairV1.Request.RequestType != "recording"

		if isNotRecording {
			headers = pairV1.Request.Headers
		}
		if pairV1.Request.Scheme != nil {

			if isNotRecording {
				schemeMatchers = append(schemeMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Scheme,
				})
			} else {
				schemeMatchers = append(schemeMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Scheme,
				})
			}
		}

		if pairV1.Request.Method != nil {
			if isNotRecording {
				methodMatchers = append(methodMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Method,
				})
			} else {
				methodMatchers = append(methodMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Method,
				})
			}
		}

		if pairV1.Request.Destination != nil {
			if isNotRecording {
				destinationMatchers = append(destinationMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Destination,
				})
			} else {
				destinationMatchers = append(destinationMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Destination,
				})
			}
		}

		if pairV1.Request.Path != nil {
			if isNotRecording {
				pathMatchers = append(pathMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Path,
				})
			} else {
				pathMatchers = append(pathMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Path,
				})
			}
		}

		if pairV1.Request.Query != nil {
			query, _ := url.QueryUnescape(*pairV1.Request.Query)
			if isNotRecording {
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   query,
				})
			} else {
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   query,
				})
			}
		}

		if pairV1.Request.Body != nil {
			if isNotRecording {
				bodyMatchers = append(bodyMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   *pairV1.Request.Body,
				})
			} else {
				bodyMatchers = append(bodyMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   *pairV1.Request.Body,
				})
			}
		}

		pair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Scheme:        schemeMatchers,
				Method:        methodMatchers,
				Destination:   destinationMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Body:          bodyMatchers,
				Headers:       headers,
				RequiresState: nil,
			},
			Response: ResponseDetailsViewV5{
				Body:             pairV1.Response.Body,
				EncodedBody:      pairV1.Response.EncodedBody,
				Headers:          pairV1.Response.Headers,
				Status:           pairV1.Response.Status,
				Templated:        false,
				TransitionsState: nil,
				RemovesState:     nil,
			},
		}
		pairs = append(pairs, pair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: pairs,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func upgradeV2(originalSimulation SimulationViewV2) SimulationViewV5 {
	requestReponsePairs := []RequestMatcherResponsePairViewV5{}

	for _, requestResponsePairV2 := range originalSimulation.DataViewV2.RequestResponsePairs {
		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}

		schemeMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Scheme)
		methodMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Method)
		destinationMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Destination)
		pathMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Path)
		bodyMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Body)

		if requestResponsePairV2.RequestMatcher.Query != nil {
			if requestResponsePairV2.RequestMatcher.Query.ExactMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.ExactMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   unescapedQuery,
				})
			}
			if requestResponsePairV2.RequestMatcher.Query.GlobMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.GlobMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   unescapedQuery,
				})
			}
		}
		requestResponsePair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Destination:   destinationMatchers,
				Headers:       requestResponsePairV2.RequestMatcher.Headers,
				Method:        methodMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Scheme:        schemeMatchers,
				Body:          bodyMatchers,
				RequiresState: nil,
			},
			Response: ResponseDetailsViewV5{
				Body:             requestResponsePairV2.Response.Body,
				EncodedBody:      requestResponsePairV2.Response.EncodedBody,
				Headers:          requestResponsePairV2.Response.Headers,
				Status:           requestResponsePairV2.Response.Status,
				Templated:        false,
				TransitionsState: nil,
				RemovesState:     nil,
			},
		}

		requestReponsePairs = append(requestReponsePairs, requestResponsePair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: requestReponsePairs,
			GlobalActions:        originalSimulation.GlobalActions,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func upgradeV3(originalSimulation SimulationViewV3) SimulationViewV5 {
	requestReponsePairs := []RequestMatcherResponsePairViewV5{}

	for _, requestResponsePairV2 := range originalSimulation.DataViewV3.RequestResponsePairs {
		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}

		schemeMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Scheme)
		methodMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Method)
		destinationMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Destination)
		pathMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Path)
		bodyMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Body)

		if requestResponsePairV2.RequestMatcher.Query != nil {
			if requestResponsePairV2.RequestMatcher.Query.ExactMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.ExactMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   unescapedQuery,
				})
			}
			if requestResponsePairV2.RequestMatcher.Query.GlobMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.GlobMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   unescapedQuery,
				})
			}
		}
		requestResponsePair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Destination:   destinationMatchers,
				Headers:       requestResponsePairV2.RequestMatcher.Headers,
				Method:        methodMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Scheme:        schemeMatchers,
				Body:          bodyMatchers,
				RequiresState: nil,
			},
			Response: ResponseDetailsViewV5{
				Body:             requestResponsePairV2.Response.Body,
				EncodedBody:      requestResponsePairV2.Response.EncodedBody,
				Headers:          requestResponsePairV2.Response.Headers,
				Status:           requestResponsePairV2.Response.Status,
				Templated:        requestResponsePairV2.Response.Templated,
				TransitionsState: nil,
				RemovesState:     nil,
			},
		}

		requestReponsePairs = append(requestReponsePairs, requestResponsePair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: requestReponsePairs,
			GlobalActions:        originalSimulation.GlobalActions,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func upgradeV4(originalSimulation SimulationViewV4) SimulationViewV5 {
	requestReponsePairs := []RequestMatcherResponsePairViewV5{}

	for _, requestResponsePairV2 := range originalSimulation.DataViewV4.RequestResponsePairs {
		schemeMatchers := []MatcherViewV5{}
		methodMatchers := []MatcherViewV5{}
		destinationMatchers := []MatcherViewV5{}
		pathMatchers := []MatcherViewV5{}
		queryMatchers := []MatcherViewV5{}
		bodyMatchers := []MatcherViewV5{}

		schemeMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Scheme)
		methodMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Method)
		destinationMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Destination)
		pathMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Path)
		bodyMatchers = v2GetMatchersFromRequestFieldMatchersView(requestResponsePairV2.RequestMatcher.Body)

		if requestResponsePairV2.RequestMatcher.Query != nil {
			if requestResponsePairV2.RequestMatcher.Query.ExactMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.ExactMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "exact",
					Value:   unescapedQuery,
				})
			}
			if requestResponsePairV2.RequestMatcher.Query.GlobMatch != nil {
				unescapedQuery, _ := url.QueryUnescape(*requestResponsePairV2.RequestMatcher.Query.GlobMatch)
				queryMatchers = append(queryMatchers, MatcherViewV5{
					Matcher: "glob",
					Value:   unescapedQuery,
				})
			}
		}
		requestResponsePair := RequestMatcherResponsePairViewV5{
			RequestMatcher: RequestMatcherViewV5{
				Destination:   destinationMatchers,
				Headers:       requestResponsePairV2.RequestMatcher.Headers,
				Method:        methodMatchers,
				Path:          pathMatchers,
				Query:         queryMatchers,
				Scheme:        schemeMatchers,
				Body:          bodyMatchers,
				RequiresState: requestResponsePairV2.RequestMatcher.RequiresState,
			},
			Response: ResponseDetailsViewV5{
				Body:             requestResponsePairV2.Response.Body,
				EncodedBody:      requestResponsePairV2.Response.EncodedBody,
				Headers:          requestResponsePairV2.Response.Headers,
				Status:           requestResponsePairV2.Response.Status,
				Templated:        requestResponsePairV2.Response.Templated,
				TransitionsState: requestResponsePairV2.Response.TransitionsState,
				RemovesState:     requestResponsePairV2.Response.RemovesState,
			},
		}

		requestReponsePairs = append(requestReponsePairs, requestResponsePair)
	}

	return SimulationViewV5{
		DataViewV5{
			RequestResponsePairs: requestReponsePairs,
			GlobalActions:        originalSimulation.GlobalActions,
		},
		newMetaView(originalSimulation.MetaView),
	}
}

func v2GetMatchersFromRequestFieldMatchersView(requestFieldMatchers *RequestFieldMatchersView) []MatcherViewV5 {
	matchers := []MatcherViewV5{}
	if requestFieldMatchers != nil {
		if requestFieldMatchers.ExactMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "exact",
				Value:   *requestFieldMatchers.ExactMatch,
			})
		}
		if requestFieldMatchers.GlobMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "glob",
				Value:   *requestFieldMatchers.GlobMatch,
			})
		}
		if requestFieldMatchers.JsonMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "json",
				Value:   *requestFieldMatchers.JsonMatch,
			})
		}
		if requestFieldMatchers.JsonPathMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "jsonpath",
				Value:   *requestFieldMatchers.JsonPathMatch,
			})
		}
		if requestFieldMatchers.RegexMatch != nil {
			fmt.Println("in regex")
			matchers = append(matchers, MatcherViewV5{
				Matcher: "regex",
				Value:   *requestFieldMatchers.RegexMatch,
			})
		}
		if requestFieldMatchers.XmlMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "xml",
				Value:   *requestFieldMatchers.XmlMatch,
			})
		}
		if requestFieldMatchers.XpathMatch != nil {
			matchers = append(matchers, MatcherViewV5{
				Matcher: "xpath",
				Value:   *requestFieldMatchers.XpathMatch,
			})
		}
	}
	return matchers
}

func newMetaView(originalMeta MetaView) MetaView {
	return MetaView{
		SchemaVersion:   "v5",
		HoverflyVersion: originalMeta.HoverflyVersion,
		TimeExported:    originalMeta.TimeExported,
	}
}
<|endoftext|>


<commit_before>package t

import (
	. "github.com/alecthomas/chroma" // nolint
	"github.com/alecthomas/chroma/lexers/internal"
)

// TradingView lexer.
var TradingView = internal.Register(MustNewLexer(
	&Config{
		Name:      "TradingView",
		Aliases:   []string{"tradingview", "tv"},
		Filenames: []string{"*.tv"},
		MimeTypes: []string{"text/x-tradingview"},
		DotAll:    true,
	},
	Rules{
		"root": {
			{`[^\S\n]+|\n|[()]`, Text, nil},
			{`(//.*?)(\n)`, ByGroups(CommentSingle, Text), nil},
			{`>=|<=|==|!=|>|<|\?|-|\+|\*|\/|%|\[|\]`, Operator, nil},
			{`[:,.]`, Punctuation, nil},
			{`=`, KeywordPseudo, nil},
			{`"(\\\\|\\"|[^"\n])*["\n]`, LiteralString, nil},
			{`'\\.'|'[^\\]'`, LiteralString, nil},
			{`[0-9](\.[0-9]*)?([eE][+-][0-9]+)?`, LiteralNumber, nil},
			{`(abs|acos|alertcondition|alma|asin|atan|atr|avg|barcolor|barssince|bgcolor|cci|ceil|change|cog|correlation|cos|crossover|crossunder|cum|dev|ema|exp|falling|fill|fixnan|floor|heikinashi|highest|highestbars|hline|iff|input|kagi|linebreak|linreg|log|log10|lowest|lowestbars|macd|max|min|mom|nz|percentile_linear_interpolation|percentile_nearest_rank|percentrank|pivothigh|pivotlow|plot|plotarrow|plotbar|plotcandle|plotchar|plotshape|pointfigure|pow|renko|rising|rma|roc|round|rsi|sar|security|sign|sin|sma|sqrt|stdev|stoch|study|sum|swma|tan|tostring|tsi|valuewhen|variance|vwma|wma|strategy\.(cancel|cancel_all|close|close_all|entry|exit|order)|strategy\.risk\.(allow_entry_in|max_cons_loss_days|max_drawdown|max_intraday_filled_orders|max_intraday_loss|max_position_size))\b`, NameFunction, nil},
			{`\b(cross|dayofmonth|dayofweek|hour|minute|month|na|offset|second|tickerid|time|tr|vwap|weekofyear|year)(\()`, ByGroups(NameFunction, Text), nil}, // functions that can also be variable
			{`(accdist|aqua|area|areabr|black|blue|bool|circles|close|columns|currency\.(AUD|CAD|CHF|EUR|GBP|HKD|JPY|NOK|NONE|NZD|SEK|SGD|TRY|USD|ZAR)|dashed|dotted|float|friday|fuchsia|gray|green|high|histogram|hl2|hlc3|integer|interval|isdaily|isdwm|isintraday|ismonthly|isweekly|lime|line|linebr|location\.(abovebar|belowbar|bottom|top)|low|maroon|monday|n|navy|ohlc4|olive|open|orange|period|purple|red|resolution|saturday|scale\.(left|none|right)|session|session\.(extended|regular)|silver|size\.(auto|huge|large|normal|small|tiny)|solid|source|string|sunday|symbol|syminfo\.(mintick|pointvalue|prefix|root|session)|teal|thursday|ticker|tuesday|volume|wednesday|white|yellow|strategy\.(cash|position_size|closedtrades|direction\.(all|long|short)|equity|eventrades|fixed|grossloss|grossprofit|initial_capital|long|losstrades|max_contracts_held_all|max_contracts_held_long|max_contracts_held_short|max_drawdown|netprofit|oca\.(cancel|none|reduce)|openprofit|opentrades|percent_of_equity|position_avg_price|position_entry_name|short|wintrades)|shape\.(arrowdown|arrowup|circle|cross|diamond|flag|labeldown|labelup|square|triangledown|triangleup|xcross)|barstate\.is(first|history|last|new|realtime)|barmerge\.(gaps_on|gaps_off|lookahead_on|lookahead_off)|strategy\.commission\.(cash_per_contract|cash_per_order|percent))\b`, NameVariable, nil},
			{`(cross|dayofmonth|dayofweek|hour|minute|month|na|second|tickerid|time|tr|vwap|weekofyear|year)(\b[^\(])`, ByGroups(NameVariable, Text), nil}, // variables that can also be function
			{`(true|false)\b`, KeywordConstant, nil},
			{`(and|or|not|if|else|for)\b`, OperatorWord, nil},
			{`@?[_a-zA-Z]\w*`, Text, nil},
		},
	},
))
<commit_msg>Added missing 'to' keyword to TradingView lexer<commit_after>package t

import (
	. "github.com/alecthomas/chroma" // nolint
	"github.com/alecthomas/chroma/lexers/internal"
)

// TradingView lexer.
var TradingView = internal.Register(MustNewLexer(
	&Config{
		Name:      "TradingView",
		Aliases:   []string{"tradingview", "tv"},
		Filenames: []string{"*.tv"},
		MimeTypes: []string{"text/x-tradingview"},
		DotAll:    true,
	},
	Rules{
		"root": {
			{`[^\S\n]+|\n|[()]`, Text, nil},
			{`(//.*?)(\n)`, ByGroups(CommentSingle, Text), nil},
			{`>=|<=|==|!=|>|<|\?|-|\+|\*|\/|%|\[|\]`, Operator, nil},
			{`[:,.]`, Punctuation, nil},
			{`=`, KeywordPseudo, nil},
			{`"(\\\\|\\"|[^"\n])*["\n]`, LiteralString, nil},
			{`'\\.'|'[^\\]'`, LiteralString, nil},
			{`[0-9](\.[0-9]*)?([eE][+-][0-9]+)?`, LiteralNumber, nil},
			{`(abs|acos|alertcondition|alma|asin|atan|atr|avg|barcolor|barssince|bgcolor|cci|ceil|change|cog|correlation|cos|crossover|crossunder|cum|dev|ema|exp|falling|fill|fixnan|floor|heikinashi|highest|highestbars|hline|iff|input|kagi|linebreak|linreg|log|log10|lowest|lowestbars|macd|max|min|mom|nz|percentile_linear_interpolation|percentile_nearest_rank|percentrank|pivothigh|pivotlow|plot|plotarrow|plotbar|plotcandle|plotchar|plotshape|pointfigure|pow|renko|rising|rma|roc|round|rsi|sar|security|sign|sin|sma|sqrt|stdev|stoch|study|sum|swma|tan|tostring|tsi|valuewhen|variance|vwma|wma|strategy\.(cancel|cancel_all|close|close_all|entry|exit|order)|strategy\.risk\.(allow_entry_in|max_cons_loss_days|max_drawdown|max_intraday_filled_orders|max_intraday_loss|max_position_size))\b`, NameFunction, nil},
			{`\b(cross|dayofmonth|dayofweek|hour|minute|month|na|offset|second|tickerid|time|tr|vwap|weekofyear|year)(\()`, ByGroups(NameFunction, Text), nil}, // functions that can also be variable
			{`(accdist|aqua|area|areabr|black|blue|bool|circles|close|columns|currency\.(AUD|CAD|CHF|EUR|GBP|HKD|JPY|NOK|NONE|NZD|SEK|SGD|TRY|USD|ZAR)|dashed|dotted|float|friday|fuchsia|gray|green|high|histogram|hl2|hlc3|integer|interval|isdaily|isdwm|isintraday|ismonthly|isweekly|lime|line|linebr|location\.(abovebar|belowbar|bottom|top)|low|maroon|monday|n|navy|ohlc4|olive|open|orange|period|purple|red|resolution|saturday|scale\.(left|none|right)|session|session\.(extended|regular)|silver|size\.(auto|huge|large|normal|small|tiny)|solid|source|string|sunday|symbol|syminfo\.(mintick|pointvalue|prefix|root|session)|teal|thursday|ticker|tuesday|volume|wednesday|white|yellow|strategy\.(cash|position_size|closedtrades|direction\.(all|long|short)|equity|eventrades|fixed|grossloss|grossprofit|initial_capital|long|losstrades|max_contracts_held_all|max_contracts_held_long|max_contracts_held_short|max_drawdown|netprofit|oca\.(cancel|none|reduce)|openprofit|opentrades|percent_of_equity|position_avg_price|position_entry_name|short|wintrades)|shape\.(arrowdown|arrowup|circle|cross|diamond|flag|labeldown|labelup|square|triangledown|triangleup|xcross)|barstate\.is(first|history|last|new|realtime)|barmerge\.(gaps_on|gaps_off|lookahead_on|lookahead_off)|strategy\.commission\.(cash_per_contract|cash_per_order|percent))\b`, NameVariable, nil},
			{`(cross|dayofmonth|dayofweek|hour|minute|month|na|second|tickerid|time|tr|vwap|weekofyear|year)(\b[^\(])`, ByGroups(NameVariable, Text), nil}, // variables that can also be function
			{`(true|false)\b`, KeywordConstant, nil},
			{`(and|or|not|if|else|for|to)\b`, OperatorWord, nil},
			{`@?[_a-zA-Z]\w*`, Text, nil},
		},
	},
))
<|endoftext|>


<commit_before>package main

import (
	"time"

	"github.com/mozilla/TLS-Observer/certificate"
	"github.com/mozilla/TLS-Observer/config"
	"github.com/mozilla/TLS-Observer/connection"
	"github.com/mozilla/TLS-Observer/modules/amqpmodule"
)

//CREATE TABLE scans  (
//	id                         	serial primary key,
//	time_stamp	           		timestamp NOT NULL,
//  target						varchar NOT NULL,
//  replay 				        integer NULL, //hours or days
//	cert_id		              	varchar references certificates(id),
//	conn_id                  	varchar references connections(id),
//	worker_outputs              	integer[] NULL, // ids of the worker table references applying to this scan
//	score                    	varchar NULL,
//	old_compliant               bool NULL,
//	intermediate_compliant      bool NULL,
//
//);

//CREATE TABLE worker_output  (
//	id                         	serial primary key,
//	worker_name	           		varchar NOT NULL,
//  output						jsonb NULL
//);

func main() {
	var err error

	printIntro()

	conf := config.ObserverConfig{}

	var cfgFile string
	flag.StringVar(&cfgFile, "c", "/etc/observer/observer.cfg", "Input file csv format")
	flag.Parse()

	_, err = os.Stat(cfgFile)
	failOnError(err, "Missing configuration file from '-c' or /etc/observer/observer.cfg")

	conf, err = config.ObserverConfigLoad(cfgFile)
	if err != nil {
		conf = config.GetObserverDefaults()
	}

	cores := runtime.NumCPU()
	runtime.GOMAXPROCS(cores * conf.General.GoRoutines)

	broker, err = amqpmodule.RegisterURL(conf.General.RabbitMQRelay)

	failOnError(err, "Failed to register RabbitMQ")

	msgs, err := broker.Consume(rxQueue, rxRoutKey)

	for d := range msgs {

		go func(domain []byte) {

			resChan := make(chan modules.ModuleResult)

			//run certificate go routine
			go func() {
				certificate.HandleCert(domain)
			}()
			//run connection go routine
			go func() {
				connection.Connect(domain)
			}()

			go func() {
				for name, wrkInfo := range worker.AvailableWorkers {

					go wrkInfo.Runner.(modules.Moduler).Run(domain, resChan)
				}
			}()

			timeout := make(chan bool, 1)
			go func() {
				time.Sleep(10 * time.Second)
				timeout <- true
			}()

			select {
			case <-timeout:

			case <-resChan:

			}

		}(d.Body)
	}

	select {}
}
<commit_msg>main app starting to form<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"runtime"
	"time"

	"github.com/mozilla/TLS-Observer/certificate"
	"github.com/mozilla/TLS-Observer/config"
	"github.com/mozilla/TLS-Observer/connection"
	"github.com/mozilla/TLS-Observer/modules/amqpmodule"
	"github.com/mozilla/TLS-Observer/worker"
)

type Scan struct {
	id               string
	time_stamp       time.Time
	target           string
	replay           int //hours or days
	has_tls          bool
	cert_id          string
	is_valid         bool
	validation_error string
	is_ubuntu_valid  bool
	is_mozilla_valid bool
	is_windows_valid bool
	is_apple_valid   bool
	conn_info        []byte
}

const rxQueue = "cert_rx_queue"
const rxRoutKey = "scan_ready"

var broker *amqpmodule.Broker

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
		panic(fmt.Sprintf("%s: %s", msg, err))
	}
}

func main() {
	var err error

	conf := config.ObserverConfig{}

	var cfgFile string
	flag.StringVar(&cfgFile, "c", "/etc/observer/observer.cfg", "Input file csv format")
	flag.Parse()

	_, err = os.Stat(cfgFile)
	failOnError(err, "Missing configuration file from '-c' or /etc/observer/observer.cfg")

	conf, err = config.ObserverConfigLoad(cfgFile)
	if err != nil {
		conf = config.GetObserverDefaults()
	}

	cores := runtime.NumCPU()
	runtime.GOMAXPROCS(cores * conf.General.GoRoutines)

	broker, err = amqpmodule.RegisterURL(conf.General.RabbitMQRelay)

	failOnError(err, "Failed to register RabbitMQ")

	msgs, err := broker.Consume(rxQueue, rxRoutKey)

	for d := range msgs {

		go func(id []byte) {

			scan := getScan(string(id))

			resChan := make(chan worker.WorkerResult)
			defer close(resChan)

			go func() {
				certID, jsonCert, err := certificate.HandleCert(scan.target)
				err, ok := err.(certificate.NoTLSCertsErr)

				if ok {
					//nil cert, does not implement TLS
				}

			}()
			//run connection go routine
			go func() {
				js, err := connection.Connect(scan.target)
			}()

			go func() {
				for name, wrkInfo := range worker.AvailableWorkers {

					go wrkInfo.Runner.(worker.Worker).Run([]byte(scan.target), resChan)
				}
			}()

			timeout := make(chan bool, 1)
			go func() {
				time.Sleep(10 * time.Second)
				timeout <- true
			}()

			select {
			case <-timeout:
			//wait no more than 10 secs for all workers to finish.

			case <-resChan:

			}

		}(d)
	}

	select {}
}

func getScan(id string) Scan {

	s := Scan{}
	return s

}
<|endoftext|>


<commit_before>package containercommands

import (
	"fmt"

	"github.com/jrperritt/rack/handler"
	"github.com/jrperritt/rack/internal/github.com/codegangsta/cli"
	"github.com/jrperritt/rack/internal/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers"
	"github.com/jrperritt/rack/util"
)

var update = cli.Command{
	Name:        "update",
	Usage:       util.Usage(commandPrefix, "update", "--name <containerName>"),
	Description: "Updates a container",
	Action:      actionUpdate,
	Flags:       util.CommandFlags(flagsUpdate, keysUpdate),
	BashComplete: func(c *cli.Context) {
		util.CompleteFlags(util.CommandFlags(flagsUpdate, keysUpdate))
	},
}

func flagsUpdate() []cli.Flag {
	return []cli.Flag{
		cli.StringFlag{
			Name:  "name",
			Usage: "[required] The name of the container",
		},
		cli.StringFlag{
			Name:  "metadata",
			Usage: "[optional] Comma-separated key-value pairs for the container. Example: key1=val1,key2=val2",
		},
		cli.StringFlag{
			Name:  "container-read",
			Usage: "[optional] Comma-separated list of users for whom to grant read access to the container",
		},
		cli.StringFlag{
			Name:  "container-write",
			Usage: "[optional] Comma-separated list of users for whom to grant write access to the container",
		},
	}
}

var keysUpdate = []string{}

type paramsUpdate struct {
	container string
	opts      containers.UpdateOpts
}

type commandUpdate handler.Command

func actionUpdate(c *cli.Context) {
	command := &commandUpdate{
		Ctx: &handler.Context{
			CLIContext: c,
		},
	}
	handler.Handle(command)
}

func (command *commandUpdate) Context() *handler.Context {
	return command.Ctx
}

func (command *commandUpdate) Keys() []string {
	return keysUpdate
}

func (command *commandUpdate) ServiceClientType() string {
	return serviceClientType
}

func (command *commandUpdate) HandleFlags(resource *handler.Resource) error {
	c := command.Ctx.CLIContext

	err := command.Ctx.CheckFlagsSet([]string{"name"})
	if err != nil {
		return err
	}

	opts := containers.UpdateOpts{
		ContainerRead:  c.String("container-read"),
		ContainerWrite: c.String("container-write"),
	}
	if c.IsSet("metadata") {
		metadata, err := command.Ctx.CheckKVFlag("metadata")
		if err != nil {
			return err
		}
		opts.Metadata = metadata
	}
	resource.Params = &paramsUpdate{
		container: c.String("name"),
		opts:      opts,
	}
	return nil
}

func (command *commandUpdate) Execute(resource *handler.Resource) {
	params := resource.Params.(*paramsUpdate)
	containerName := params.container
	opts := params.opts
	rawResponse := containers.Update(command.Ctx.ServiceClient, containerName, opts)
	if rawResponse.Err != nil {
		resource.Err = rawResponse.Err
		return
	}
	resource.Result = fmt.Sprintf("Successfully updated container [%s]\n", containerName)
}
<commit_msg>check container exists before updating<commit_after>package containercommands

import (
	"fmt"

	"github.com/jrperritt/rack/handler"
	"github.com/jrperritt/rack/internal/github.com/codegangsta/cli"
	"github.com/jrperritt/rack/internal/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers"
	"github.com/jrperritt/rack/util"
)

var update = cli.Command{
	Name:        "update",
	Usage:       util.Usage(commandPrefix, "update", "--name <containerName>"),
	Description: "Updates a container",
	Action:      actionUpdate,
	Flags:       util.CommandFlags(flagsUpdate, keysUpdate),
	BashComplete: func(c *cli.Context) {
		util.CompleteFlags(util.CommandFlags(flagsUpdate, keysUpdate))
	},
}

func flagsUpdate() []cli.Flag {
	return []cli.Flag{
		cli.StringFlag{
			Name:  "name",
			Usage: "[required] The name of the container",
		},
		cli.StringFlag{
			Name:  "metadata",
			Usage: "[optional] Comma-separated key-value pairs for the container. Example: key1=val1,key2=val2",
		},
		cli.StringFlag{
			Name:  "container-read",
			Usage: "[optional] Comma-separated list of users for whom to grant read access to the container",
		},
		cli.StringFlag{
			Name:  "container-write",
			Usage: "[optional] Comma-separated list of users for whom to grant write access to the container",
		},
	}
}

var keysUpdate = []string{}

type paramsUpdate struct {
	container string
	opts      containers.UpdateOpts
}

type commandUpdate handler.Command

func actionUpdate(c *cli.Context) {
	command := &commandUpdate{
		Ctx: &handler.Context{
			CLIContext: c,
		},
	}
	handler.Handle(command)
}

func (command *commandUpdate) Context() *handler.Context {
	return command.Ctx
}

func (command *commandUpdate) Keys() []string {
	return keysUpdate
}

func (command *commandUpdate) ServiceClientType() string {
	return serviceClientType
}

func (command *commandUpdate) HandleFlags(resource *handler.Resource) error {
	c := command.Ctx.CLIContext

	err := command.Ctx.CheckFlagsSet([]string{"name"})
	if err != nil {
		return err
	}

	opts := containers.UpdateOpts{
		ContainerRead:  c.String("container-read"),
		ContainerWrite: c.String("container-write"),
	}
	if c.IsSet("metadata") {
		metadata, err := command.Ctx.CheckKVFlag("metadata")
		if err != nil {
			return err
		}
		opts.Metadata = metadata
	}
	resource.Params = &paramsUpdate{
		container: c.String("name"),
		opts:      opts,
	}
	return nil
}

func (command *commandUpdate) Execute(resource *handler.Resource) {
	params := resource.Params.(*paramsUpdate)
	containerName := params.container

	containerRaw := containers.Get(command.Ctx.ServiceClient, containerName)
	if containerRaw.Err != nil {
		resource.Err = containerRaw.Err
		return
	}

	opts := params.opts
	rawResponse := containers.Update(command.Ctx.ServiceClient, containerName, opts)
	if rawResponse.Err != nil {
		resource.Err = rawResponse.Err
		return
	}
	resource.Result = fmt.Sprintf("Successfully updated container [%s]\n", containerName)
}
<|endoftext|>


<commit_before>//First iteration of temperature chaincode.

package main

import (
	"errors"
	"fmt"
	//"strconv"
	//"strings"
	"encoding/json"

	//"github.com/hyperledger/fabric/accesscontrol/impl"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// policyChaincode
type policyChaincode struct {
}
type Policy struct {
	Insert bool
	Groups []string
}

//This function will be executed by the chaincode when it is first deployed.
//I don't think we need any kind of initialization yet. Therefore we take 0 arguments and return nil, nil if that is the case.
func (t *policyChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	adminCert := args[0]
	fmt.Println("This is the adminCert: " + adminCert)
	if len(adminCert) == 0 {
		fmt.Println("This is the adminCert: " + adminCert)
		return nil, errors.New("Invalid admin certificate, it was empty.")
	}
	stub.PutState("admin", []byte(adminCert))
	stub.PutState(string(adminCert), []byte(`{"Insert":true, "Groups":["temp"]}`))

	return nil, nil
}

//Called when someone is trying to perform a transaction to change the state.
//When adding a policy to allow queries for temperature data, append ("temperature", true) to the policy JSON.
func (t *policyChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	//get adminCert
	callerCert := args[0]
	adminCertRaw, err := stub.GetState("admin")
	if err != nil {
		return nil, errors.New("GetState('admin') returned an error, Invoke call aborted.")
	}
	adminCert := string(adminCertRaw)
	if callerCert != adminCert {
		return nil, errors.New("Caller is not admin. Aborting invoke call.")
	}
	if err != nil {
		return nil, errors.New("Failed checking admin certificate.")
	}
	switch function {
		//This case is executed when the recieved function is removePolicy
  case "removePolicy":
		//The removePolicy function only takes one argument, certificate of the user as a string in arg[1].
  	if len(args) != 2 {
      return nil, errors.New("Wrong number of arguments for function " + function + ", expected 1 but recieved " + string(len(args)) + ".")
    }
		fmt.Println("Deleting policy for user: " + args[1] + ".")
		//Delete the policy for user in argument
    stub.PutState(args[2], nil)
  case "addPolicy":
		if len(args) != 3 {
			return nil, errors.New("Wrong number of arguments for function " + function + ", expected 1 but recieved " + string(len(args)) + ".")
		}
		//addPolicy takes the certificate of the user as a string in arg[1] and the policy as string encoded JSON in arg[2].
		fmt.Println("This is what arg[0] looks like: " + args[1])
		fmt.Println("Inserting new policy")
    err = stub.PutState(args[1], []byte(args[2]))
    if err != nil {
      return nil, errors.New("Error occurred when trying to PutState(" + args[1] + ", " + args[2] + ").")
    }
  default:
    return nil, errors.New("Function: " + function + " was not found.")
	}
	return nil, nil
}

// Query callback representing the query of a chaincode
func (t *policyChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
  //Check arguments
	callerCert := args[0]

	//The JSON decoding is probably broken, what the fuck is an empty interface and how do I iterate over a string array with one?
	policyRaw, err := stub.GetState(string(callerCert))
	if err != nil {
		return nil, errors.New("GetState('callerCert') returned an error, query call aborted.")
	}
	var policy Policy
	jsonErr := json.Unmarshal([]byte(policyRaw), &policy)
	if jsonErr != nil {
		return nil, jsonErr
		fmt.Println("error decoding json")
	}
	fmt.Println("The string: " + string(policyRaw))
	fmt.Println("DAFUQ: " )

  switch function {
  case "insert":
		if policy.Insert == true {
			return []byte{1}, nil
		}
		return []byte{0}, nil

	case "fetch":
		group := args[1]
		for i := 0; i < len(policy.Groups); i++ {
			if policy.Groups[i] == group {
				return []byte{1}, nil
			}
		}

		return []byte{0}, nil

	case "policy":
		return policyRaw, nil

  default:
    return nil, errors.New("Function: " + function + " was not found.")
  }

    return nil, nil
}

func (t *policyChaincode) isCaller(stub shim.ChaincodeStubInterface, certificate []byte) (bool, error) {
	fmt.Printf("Check caller...")

	// In order to enforce access control, we require that the
	// metadata contains the signature under the signing key corresponding
	// to the verification key inside certificate of
	// the payload of the transaction (namely, function name and args) and
	// the transaction binding (to avoid copying attacks)

	// Verify \sigma=Sign(certificate.sk, tx.Payload||tx.Binding) against certificate.vk
	// \sigma is in the metadata

	sigma, err := stub.GetCallerMetadata()
	if err != nil {
		return false, errors.New("Failed getting metadata, can't verify caller.")
	}
	payload, err := stub.GetPayload()
	if err != nil {
		return false, errors.New("Failed getting payload, can't verify caller.")
	}
	binding, err := stub.GetBinding()
	if err != nil {
		return false, errors.New("Failed getting binding, can't verify caller.")
	}

	fmt.Printf("passed certificate [% x]", certificate)
	fmt.Printf("passed sigma [% x]", sigma)
	fmt.Printf("passed payload [% x]", payload)
	fmt.Printf("passed binding [% x]", binding)

	ok, err := stub.VerifySignature(
		certificate,
		sigma,
		append(payload, binding...),
	)
	if err != nil {
		fmt.Printf("Failed checking signature [%s], can't verify caller.", err)
		return ok, err
	}
	if !ok {
		fmt.Printf("Invalid signature, can't verify caller.")
	}

	fmt.Printf("Check caller...Verified!")

	return ok, err
}

func main() {
	err := shim.Start(new(policyChaincode))
	if err != nil {
		fmt.Printf("Error starting Temperature chaincode: %s", err)
	}
}
<commit_msg>changes to chaincode<commit_after>//First iteration of temperature chaincode.

package main

import (
	"errors"
	"fmt"
	//"strconv"
	//"stri ngs"
	"encoding/json"

	//"github.com/hyperledger/fabric/accesscontrol/impl"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// policyChaincode
type policyChaincode struct {
}
type Policy struct {
	Insert bool
	Groups []string
}

//This function will be executed by the chaincode when it is first deployed.
//I don't think we need any kind of initialization yet. Therefore we take 0 arguments and return nil, nil if that is the case.
func (t *policyChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	adminCert := args[0]
	fmt.Println("This is the adminCert: " + adminCert)
	if len(adminCert) == 0 {
		fmt.Println("This is the adminCert: " + adminCert)
		return nil, errors.New("Invalid admin certificate, it was empty.")
	}
	stub.PutState("admin", []byte(adminCert))
	stub.PutState(string(adminCert), []byte(`{"Insert":true, "Groups":["temp"]}`))

	return nil, nil
}

//Called when someone is trying to perform a transaction to change the state.
//When adding a policy to allow queries for temperature data, append ("temperature", true) to the policy JSON.
func (t *policyChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	//get adminCert
	callerCert := args[0]
	adminCertRaw, err := stub.GetState("admin")
	if err != nil {
		return nil, errors.New("GetState('admin') returned an error, Invoke call aborted.")
	}
	adminCert := string(adminCertRaw)
	if callerCert != adminCert {
		return nil, errors.New("Caller is not admin. Aborting invoke call.")
	}
	if err != nil {
		return nil, errors.New("Failed checking admin certificate.")
	}
	switch function {
		//This case is executed when the recieved function is removePolicy
  case "removePolicy":
		//The removePolicy function only takes one argument, certificate of the user as a string in arg[1].
  	if len(args) != 2 {
      return nil, errors.New("Wrong number of arguments for function " + function + ", expected 1 but recieved " + string(len(args)) + ".")
    }
		fmt.Println("Deleting policy for user: " + args[1] + ".")
		//Delete the policy for user in argument
    stub.PutState(args[2], nil)
  case "addPolicy":
		if len(args) != 3 {
			return nil, errors.New("Wrong number of arguments for function " + function + ", expected 1 but recieved " + string(len(args)) + ".")
		}
		//addPolicy takes the certificate of the user as a string in arg[1] and the policy as string encoded JSON in arg[2].
		fmt.Println("This is what arg[0] looks like: " + args[1])
		fmt.Println("Inserting new policy")
    err = stub.PutState(args[1], []byte(args[2]))
    if err != nil {
      return nil, errors.New("Error occurred when trying to PutState(" + args[1] + ", " + args[2] + ").")
    }
  default:
    return nil, errors.New("Function: " + function + " was not found.")
	}
	return nil, nil
}

// Query callback representing the query of a chaincode
func (t *policyChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
  //Check arguments
	callerCert := args[0]

	//The JSON decoding is probably broken, what the fuck is an empty interface and how do I iterate over a string array with one?
	policyRaw, err := stub.GetState(string(callerCert))
	if err != nil {
		return nil, errors.New("GetState('callerCert') returned an error, query call aborted.")
	}
	var policy Policy
	jsonErr := json.Unmarshal([]byte(policyRaw), &policy)
	if jsonErr != nil {
		return nil, jsonErr
		fmt.Println("error decoding json")
	}
	fmt.Println("The string: " + string(policyRaw))
	fmt.Println("DAFUQ: " )

  switch function {
  case "insert":
		if policy.Insert == true {
			return []byte{1}, nil
		}
		return []byte{0}, nil

	case "fetch":
		group := args[1]
		for i := 0; i < len(policy.Groups); i++ {
			if policy.Groups[i] == group {
				return []byte{1}, nil
			}
		}

		return []byte{0}, nil

	case "policy":
		return policyRaw, nil

  default:
    return nil, errors.New("Function: " + function + " was not found.")
  }

    return nil, nil
}

func (t *policyChaincode) isCaller(stub shim.ChaincodeStubInterface, certificate []byte) (bool, error) {
	fmt.Printf("Check caller...")

	// In order to enforce access control, we require that the
	// metadata contains the signature under the signing key corresponding
	// to the verification key inside certificate of
	// the payload of the transaction (namely, function name and args) and
	// the transaction binding (to avoid copying attacks)

	// Verify \sigma=Sign(certificate.sk, tx.Payload||tx.Binding) against certificate.vk
	// \sigma is in the metadata

	sigma, err := stub.GetCallerMetadata()
	if err != nil {
		return false, errors.New("Failed getting metadata, can't verify caller.")
	}
	payload, err := stub.GetPayload()
	if err != nil {
		return false, errors.New("Failed getting payload, can't verify caller.")
	}
	binding, err := stub.GetBinding()
	if err != nil {
		return false, errors.New("Failed getting binding, can't verify caller.")
	}

	fmt.Printf("passed certificate [% x]", certificate)
	fmt.Printf("passed sigma [% x]", sigma)
	fmt.Printf("passed payload [% x]", payload)
	fmt.Printf("passed binding [% x]", binding)

	ok, err := stub.VerifySignature(
		certificate,
		sigma,
		append(payload, binding...),
	)
	if err != nil {
		fmt.Printf("Failed checking signature [%s], can't verify caller.", err)
		return ok, err
	}
	if !ok {
		fmt.Printf("Invalid signature, can't verify caller.")
	}

	fmt.Printf("Check caller...Verified!")

	return ok, err
}

func main() {
	err := shim.Start(new(policyChaincode))
	if err != nil {
		fmt.Printf("Error starting Temperature chaincode: %s", err)
	}
}
<|endoftext|>


<commit_before>package reporter

import (
  "bytes"
  "fmt"
  "os"
  fsnotify "gopkg.in/fsnotify.v1"
)

type LogWatcher struct {
  // Path to the log file that will be watched.
  logFile string
  // Filesystem notifications client.
  fsWatcher *fsnotify.Watcher
  // Sink for the lines written to the log file.
  logLines chan []byte
  // Tells the log watch loop when to stop.
  commands chan int
  // Sink for errors encountered by the log file watching loop.
  errors chan error
  // Filesystem handle for the log file.
  log *os.File
  // The number of bytes already read from the log file.
  readOffset int64
  // The buffer used to read from the file.
  lineBuffer []byte
}

// Init sets up the filesystem watcher.
func (l *LogWatcher) Init(logFile string) error {
  l.logFile = logFile
  var err error
  l.fsWatcher, err = fsnotify.NewWatcher()
  if err != nil {
    return err
  }
  l.logLines = make(chan []byte, 1024)

  l.readOffset = -1
  l.lineBuffer = make([]byte, 4096)[:0]
  l.errors = make(chan error, 5)
  return nil
}

// LogLines returns the channel that produces Hearthstone's logging output.
func (l *LogWatcher) LogLines() <-chan []byte {
  return l.logLines
}

// Errors returns the channel for errors encountered while watching the log.
func (l *LogWatcher) Errors() <-chan error {
  return l.errors
}

// Start spawns a goroutine that listens for log-related filesystem events.
func (l *LogWatcher) Start() error {
  if err := l.handleWrite(); err != nil {
    return err
  }
  if err := l.fsWatcher.Add(l.logFile); err != nil {
    return err
  }
  go l.listenLoop()
  return nil
}

// Stop causes the filesystem listener to break out of its loop.
func (l *LogWatcher) Stop() error {
  if err := l.fsWatcher.Remove(l.logFile); err != nil {
    return err
  }
  l.commands <- 1
  return nil
}

// listenLoop repeatedly listens for filesystem events and acts on them.
func (l *LogWatcher) listenLoop() {
  for {
    select {
    case fsEvent := <- l.fsWatcher.Events:
      if err := l.handleEvent(&fsEvent); err != nil {
        l.errors <- err
      }
    case fsError := <- l.fsWatcher.Errors:
      l.errors <- fsError
    case command := <- l.commands:
      if command == 1 {
        break
      }
    }
  }
}

func (l *LogWatcher) handleEvent(event *fsnotify.Event) error {
  switch event.Op {
  case fsnotify.Write:
    return l.handleWrite()
  }
  l.errors <- fmt.Errorf("Unexpected event: %v\n", event)
  return nil
}

// handleWrite is called when the log file is updated.
func (l *LogWatcher) handleWrite() error {
  var err error
  if l.log == nil {
    l.log, err = os.OpenFile(l.logFile, os.O_RDONLY, 0644)
    if err != nil {
      return err
    }
  }
  fileInfo, err := l.log.Stat()
  if err != nil {
    return err
  }

  logSize := fileInfo.Size()
  if logSize < l.readOffset {
    // The log file was truncated.
    l.readOffset = 0
  } else if l.readOffset == -1 {
    // The watcher is just getting started.
    l.readOffset = logSize
  }

  for l.readOffset < logSize {
    readSize := logSize - l.readOffset
    bufferOffset := len(l.lineBuffer)
    bufferCapacity := cap(l.lineBuffer) - bufferOffset
    if readSize > int64(bufferCapacity) {
      readSize = int64(bufferCapacity)
    }

    readBuffer := l.lineBuffer[bufferOffset : bufferOffset + int(readSize)]
    bytesRead, err := l.log.ReadAt(readBuffer, l.readOffset)
    if err != nil {
      return err
    }
    l.readOffset += int64(bytesRead)
    l.lineBuffer = l.lineBuffer[0 : bufferOffset + bytesRead]

    l.sliceLines(bufferOffset)
  }

  return nil
}

// sliceLines removes complete lines from the read buffer.
// "bufferOffset
func (l *LogWatcher) sliceLines(bufferOffset int) {
  lineStart := 0
  for {
    readBuffer := l.lineBuffer[bufferOffset:]
    relativeIndex := bytes.IndexByte(readBuffer, byte('\n'))
    if relativeIndex == -1 {
      break
    }
    newlineIndex := relativeIndex + bufferOffset
    l.reportLine(l.lineBuffer[lineStart : newlineIndex + 1])

    bufferOffset = newlineIndex + 1
    lineStart = bufferOffset
  }

  if lineStart == 0 {
    return
  }
  bufferOffset = len(l.lineBuffer) - lineStart
  copy(l.lineBuffer[0:bufferOffset], l.lineBuffer[lineStart:])
  l.lineBuffer = l.lineBuffer[0:bufferOffset]
}

// reportLine sends the line information over the channel.
func (l *LogWatcher) reportLine(line []byte) {
  if len(line) == 0 || line[0] != byte('[') {
    // Skip lines that don't start with a [
    return
  }

  // NOTE: We copy the slice because its underlying buffer is the line buffer,
  //       which changes often.
  // TODO(pwnall): Consider cutting slices from large pools.
  lineCopy := make([]byte, len(line))
  copy(lineCopy, line)
  l.logLines <- lineCopy
}
<commit_msg>Avoid showing a potentially scary error message.<commit_after>package reporter

import (
  "bytes"
  "fmt"
  "os"
  fsnotify "gopkg.in/fsnotify.v1"
)

type LogWatcher struct {
  // Path to the log file that will be watched.
  logFile string
  // Filesystem notifications client.
  fsWatcher *fsnotify.Watcher
  // Sink for the lines written to the log file.
  logLines chan []byte
  // Tells the log watch loop when to stop.
  commands chan int
  // Sink for errors encountered by the log file watching loop.
  errors chan error
  // Filesystem handle for the log file.
  log *os.File
  // The number of bytes already read from the log file.
  readOffset int64
  // The buffer used to read from the file.
  lineBuffer []byte
}

// Init sets up the filesystem watcher.
func (l *LogWatcher) Init(logFile string) error {
  l.logFile = logFile
  var err error
  l.fsWatcher, err = fsnotify.NewWatcher()
  if err != nil {
    return err
  }
  l.logLines = make(chan []byte, 1024)

  l.readOffset = -1
  l.lineBuffer = make([]byte, 4096)[:0]
  l.errors = make(chan error, 5)
  return nil
}

// LogLines returns the channel that produces Hearthstone's logging output.
func (l *LogWatcher) LogLines() <-chan []byte {
  return l.logLines
}

// Errors returns the channel for errors encountered while watching the log.
func (l *LogWatcher) Errors() <-chan error {
  return l.errors
}

// Start spawns a goroutine that listens for log-related filesystem events.
func (l *LogWatcher) Start() error {
  if err := l.handleWrite(); err != nil {
    return err
  }
  if err := l.fsWatcher.Add(l.logFile); err != nil {
    return err
  }
  go l.listenLoop()
  return nil
}

// Stop causes the filesystem listener to break out of its loop.
func (l *LogWatcher) Stop() error {
  if err := l.fsWatcher.Remove(l.logFile); err != nil {
    return err
  }
  l.commands <- 1
  return nil
}

// listenLoop repeatedly listens for filesystem events and acts on them.
func (l *LogWatcher) listenLoop() {
  for {
    select {
    case fsEvent := <- l.fsWatcher.Events:
      if err := l.handleEvent(&fsEvent); err != nil {
        l.errors <- err
      }
    case fsError := <- l.fsWatcher.Errors:
      l.errors <- fsError
    case command := <- l.commands:
      if command == 1 {
        break
      }
    }
  }
}

func (l *LogWatcher) handleEvent(event *fsnotify.Event) error {
  switch event.Op {
  case fsnotify.Write:
    return l.handleWrite()
  case fsnotify.Chmod:
    // NOTE: Chmod tends to happen when the game starts and when a match
    //       starts. It might be associated with the file getting truncated.
    //       For now, treating it as a write seems to work.
    return l.handleWrite()
  }
  l.errors <- fmt.Errorf("Unexpected event: %v\n", event)
  return nil
}

// handleWrite is called when the log file is updated.
func (l *LogWatcher) handleWrite() error {
  var err error
  if l.log == nil {
    l.log, err = os.OpenFile(l.logFile, os.O_RDONLY, 0644)
    if err != nil {
      return err
    }
  }
  fileInfo, err := l.log.Stat()
  if err != nil {
    return err
  }

  logSize := fileInfo.Size()
  if logSize < l.readOffset {
    // The log file was truncated.
    l.readOffset = 0
  } else if l.readOffset == -1 {
    // The watcher is just getting started.
    l.readOffset = logSize
  }

  for l.readOffset < logSize {
    readSize := logSize - l.readOffset
    bufferOffset := len(l.lineBuffer)
    bufferCapacity := cap(l.lineBuffer) - bufferOffset
    if readSize > int64(bufferCapacity) {
      readSize = int64(bufferCapacity)
    }

    readBuffer := l.lineBuffer[bufferOffset : bufferOffset + int(readSize)]
    bytesRead, err := l.log.ReadAt(readBuffer, l.readOffset)
    if err != nil {
      return err
    }
    l.readOffset += int64(bytesRead)
    l.lineBuffer = l.lineBuffer[0 : bufferOffset + bytesRead]

    l.sliceLines(bufferOffset)
  }

  return nil
}

// sliceLines removes complete lines from the read buffer.
// "bufferOffset
func (l *LogWatcher) sliceLines(bufferOffset int) {
  lineStart := 0
  for {
    readBuffer := l.lineBuffer[bufferOffset:]
    relativeIndex := bytes.IndexByte(readBuffer, byte('\n'))
    if relativeIndex == -1 {
      break
    }
    newlineIndex := relativeIndex + bufferOffset
    l.reportLine(l.lineBuffer[lineStart : newlineIndex + 1])

    bufferOffset = newlineIndex + 1
    lineStart = bufferOffset
  }

  if lineStart == 0 {
    return
  }
  bufferOffset = len(l.lineBuffer) - lineStart
  copy(l.lineBuffer[0:bufferOffset], l.lineBuffer[lineStart:])
  l.lineBuffer = l.lineBuffer[0:bufferOffset]
}

// reportLine sends the line information over the channel.
func (l *LogWatcher) reportLine(line []byte) {
  if len(line) == 0 || line[0] != byte('[') {
    // Skip lines that don't start with a [
    return
  }

  // NOTE: We copy the slice because its underlying buffer is the line buffer,
  //       which changes often.
  // TODO(pwnall): Consider cutting slices from large pools.
  lineCopy := make([]byte, len(line))
  copy(lineCopy, line)
  l.logLines <- lineCopy
}
<|endoftext|>


<commit_before>// Copyright (c) 2014, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package protected_objects stores, searches and chains protected objects like keys
// and files.

package rotation_support

import (
	"container/list"
	"errors"
	"fmt"
	"time"

	"github.com/jlmucb/cloudproxy/go/support_libraries/protected_objects"
)

func ChangeObjectStatus(l *list.List, name_obj string, epoch int, new_status string) error {
	obj := protected_objects.FindObject(l, name_obj, int32(epoch), nil, nil)
	if obj == nil {
		return errors.New("Can't find object")
	}
	obj.ObjStatus = &new_status
	return nil
}

// Revoke indicated object
func RevokeObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "revoked")
}

// Retire indicated object
func RetireObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "retired")
}

// Activate indicated object
func ActivateObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "active")
}

// Inactivate indicated object
func InactivateObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "inactive")
}

func ForceInclude() {
	fmt.Printf("Include forced")
}

// Make object with new epoch and return it
func AddNewKeyEpoch(l *list.List, name_obj string, obj_type string, existing_status string, new_status string,
		    notBefore string, notAfter string,
                    value []byte) (*protected_objects.ObjectMessage, *protected_objects.ObjectMessage, error) {
	new_epoch := 1
	old_obj := protected_objects.GetLatestEpoch(l, name_obj, []string{existing_status})
	if old_obj != nil {
		new_epoch = int(*old_obj.ObjId.ObjEpoch + 1)
	}
	nb, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", notBefore)
	if err != nil {
		return nil,nil, errors.New("Can't parse notBefore")
	}
	na, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", notAfter)
	if err != nil {
		return nil,nil, errors.New("Can't parse notAfter")
	}
	new_obj, err := protected_objects.CreateObject(name_obj, int32(new_epoch), &obj_type,
			&new_status, &nb, &na, value)
	if err != nil || new_obj == nil {
		return nil,nil, errors.New("Can't create new object")
	}
	err = protected_objects.AddObject(l, *new_obj)
	if err != nil {
		return nil,nil, errors.New("Can't add new object")
	}
	return old_obj, new_obj, nil
}

// Find all the objects protected by existing object.
// For each, make a new protected object with new protector.
// Add all resulting nodes to the node list.
// Return new epoch.
func AddAndRotateNewKeyEpoch(name_obj string,  obj_type string, existing_status string,
		new_status string, notBefore string, notAfter string,
		value []byte, node_list *list.List, obj_list *list.List,
		protected_obj_list *list.List) (int, error) {
	old_obj, new_obj, err := AddNewKeyEpoch(obj_list, name_obj, obj_type, existing_status,
                    new_status, notBefore, notAfter, value)
	if err != nil || new_obj == nil {
		return -1, errors.New("Can't create new epoch")
	}
	err = protected_objects.AddObject(obj_list, *new_obj)
	if err != nil {
		return -1, errors.New("Can't add new key")
	}
	if old_obj == nil {
		return 1, nil
	}
	old_protected:= protected_objects.FindProtectedNodes(node_list, name_obj, *old_obj.ObjId.ObjEpoch)
	if old_protected == nil  || old_protected.Len() <= 0 {
	}
	for e := old_protected.Front(); e != nil; e = e.Next() {
		old := e.Value.(protected_objects.NodeMessage)
		if old.ProtectedObjId.ObjName == nil {
		}
		new_epoch := *old.ProtectedObjId.ObjEpoch + 1
		new_protected_obj, err := protected_objects.MakeProtectedObject(*new_obj, *old.ProtectedObjId.ObjName,
					new_epoch, new_obj.ObjVal)
		if new_protected_obj == nil || err != nil {
		}
		err = protected_objects.AddProtectedObject(protected_obj_list, *new_protected_obj)
		if err != nil {
		}
		new_node := protected_objects.MakeNode(*new_obj.ObjId.ObjName, *new_obj.ObjId.ObjEpoch,
			*new_protected_obj.ProtectedObjId.ObjName, *new_protected_obj.ProtectedObjId.ObjEpoch)
		err = protected_objects.AddNode(node_list, *new_node)
		if err != nil {
		}
		// re-encrypt
	}
	return int(*old_obj.ObjId.ObjEpoch), nil
}

<commit_msg>more rotate support<commit_after>// Copyright (c) 2014, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package protected_objects stores, searches and chains protected objects like keys
// and files.

package rotation_support

import (
	"container/list"
	"errors"
	"fmt"
	"time"

	"github.com/jlmucb/cloudproxy/go/support_libraries/protected_objects"
)

func ChangeObjectStatus(l *list.List, name_obj string, epoch int, new_status string) error {
	obj := protected_objects.FindObject(l, name_obj, int32(epoch), nil, nil)
	if obj == nil {
		return errors.New("Can't find object")
	}
	obj.ObjStatus = &new_status
	return nil
}

// Revoke indicated object
func RevokeObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "revoked")
}

// Retire indicated object
func RetireObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "retired")
}

// Activate indicated object
func ActivateObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "active")
}

// Inactivate indicated object
func InactivateObject(l *list.List, name_obj string, epoch int) (error) {
	return ChangeObjectStatus(l, name_obj, epoch, "inactive")
}

func ForceInclude() {
	fmt.Printf("Include forced")
}

// Make object with new epoch and return it
func AddNewKeyEpoch(l *list.List, name_obj string, obj_type string, existing_status string, new_status string,
		    notBefore string, notAfter string,
                    value []byte) (*protected_objects.ObjectMessage, *protected_objects.ObjectMessage, error) {
	new_epoch := 1
	old_obj := protected_objects.GetLatestEpoch(l, name_obj, []string{existing_status})
	if old_obj != nil {
		new_epoch = int(*old_obj.ObjId.ObjEpoch + 1)
	}
	nb, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", notBefore)
	if err != nil {
		return nil,nil, errors.New("Can't parse notBefore")
	}
	na, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", notAfter)
	if err != nil {
		return nil,nil, errors.New("Can't parse notAfter")
	}
	new_obj, err := protected_objects.CreateObject(name_obj, int32(new_epoch), &obj_type,
			&new_status, &nb, &na, value)
	if err != nil || new_obj == nil {
		return nil,nil, errors.New("Can't create new object")
	}
	err = protected_objects.AddObject(l, *new_obj)
	if err != nil {
		return nil,nil, errors.New("Can't add new object")
	}
	return old_obj, new_obj, nil
}

// Find all the objects protected by existing object.
// For each, make a new protected object with new protector.
// Add all resulting nodes to the node list.
// Return new epoch.
func AddAndRotateNewKeyEpoch(name_obj string,  obj_type string, existing_status string,
		new_status string, notBefore string, notAfter string,
		value []byte, node_list *list.List, obj_list *list.List,
		protected_obj_list *list.List) (int, error) {
	old_obj, new_obj, err := AddNewKeyEpoch(obj_list, name_obj, obj_type, existing_status,
                    new_status, notBefore, notAfter, value)
	if err != nil || new_obj == nil {
		return -1, errors.New("Can't create new epoch")
	}
	err = protected_objects.AddObject(obj_list, *new_obj)
	if err != nil {
		return -1, errors.New("Can't add new key")
	}
	if old_obj == nil {
		return 1, nil
	}
	old_protected:= protected_objects.FindProtectedNodes(node_list, name_obj, *old_obj.ObjId.ObjEpoch)
	if old_protected == nil  || old_protected.Len() <= 0 {
	}
	for e := old_protected.Front(); e != nil; e = e.Next() {
		old := e.Value.(protected_objects.NodeMessage)
		protected_name := *old.ProtectedObjId.ObjName
		protected_epoch := *old.ProtectedObjId.ObjEpoch
		new_protected_obj, err := protected_objects.MakeProtectedObject(*new_obj, protected_name,
					protected_epoch, new_obj.ObjVal)
		if new_protected_obj == nil || err != nil {
			return -1, errors.New("Can't make new protected object")
		}
		err = protected_objects.AddProtectedObject(protected_obj_list, *new_protected_obj)
		if err != nil {
			return -1, errors.New("Can't add new protected node")
		}
		new_node := protected_objects.MakeNode(*new_obj.ObjId.ObjName, *new_obj.ObjId.ObjEpoch,
			protected_name, protected_epoch)
		if new_node == nil {
			return -1, errors.New("Can't make new node")
		}
		err = protected_objects.AddNode(node_list, *new_node)
		if err != nil {
			return -1, errors.New("Can't add new node")
		}
	}
	_ = RetireObject(obj_list, *old_obj.ObjId.ObjName, int(*old_obj.ObjId.ObjEpoch))
	return int(*new_obj.ObjId.ObjEpoch), nil
}
<|endoftext|>


<commit_before>package awspurge

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/elb"
)

type Config struct {
	Regions        []string `toml:"regions" json:"regions"`
	RegionsExclude []string `toml:"regions_exclude" json:"regions_exclude"`
	AccessKey      string   `toml:"access_key" json:"access_key"`
	SecretKey      string   `toml:"secret_key" json:"secret_key"`

	// AWS Client timeout
	Timeout time.Duration `toml:"timeout" json:"timeout"`

	// If enabled it only fetches and lists resources (it doesn't terminate
	// resources)
	List bool `toml:"list" json:"list"`
}

type resources struct {
	instances        []*ec2.Instance
	volumes          []*ec2.Volume
	keyPairs         []*ec2.KeyPairInfo
	placementGroups  []*ec2.PlacementGroup
	addresses        []*ec2.Address
	snapshots        []*ec2.Snapshot
	loadBalancers    []*elb.LoadBalancerDescription
	securityGroups   []*ec2.SecurityGroup
	vpcs             []*ec2.Vpc
	subnets          []*ec2.Subnet
	networkAcls      []*ec2.NetworkAcl
	internetGateways []*ec2.InternetGateway
	routeTables      []*ec2.RouteTable
}

type Purge struct {
	services *multiRegion
	regions  []string // our own defined regions
	list     bool     // only list, do not terminate if enabled

	// resources represents the current available resources per region. It's
	// populated by the Fetch() method.
	resources  map[string]*resources
	resourceMu sync.Mutex // protects resources

	// fetch synchronization
	fetchWg   sync.WaitGroup
	fetchMu   sync.Mutex
	fetchErrs error

	// deleteErrors
	deleteMu   sync.Mutex
	deleteErrs error
}

func New(conf *Config) (*Purge, error) {
	checkCfg := "Please check your configuration"

	if len(conf.Regions) == 0 {
		return nil, errors.New("AWS Regions are not set. " + checkCfg)
	}

	if conf.AccessKey == "" {
		return nil, errors.New("AWS Access Key is not set. " + checkCfg)
	}

	if conf.SecretKey == "" {
		return nil, errors.New("AWS Secret Key is not set. " + checkCfg)
	}

	if conf.Timeout == 0 {
		conf.Timeout = time.Second * 30
	}

	client := &http.Client{
		Transport: &http.Transport{TLSHandshakeTimeout: conf.Timeout},
		Timeout:   conf.Timeout,
	}

	creds := credentials.NewStaticCredentials(conf.AccessKey, conf.SecretKey, "")
	awsCfg := &aws.Config{
		Credentials: creds,
		HTTPClient:  client,
		Logger:      aws.NewDefaultLogger(),
	}

	regions := filterRegions(conf.Regions, conf.RegionsExclude)
	m := newMultiRegion(awsCfg, regions)

	// initialize resources
	res := make(map[string]*resources, 0)
	for _, region := range regions {
		res[region] = &resources{}
	}

	return &Purge{
		services:  m,
		resources: res,
		regions:   regions,
		list:      conf.List,
	}, nil
}

func (p *Purge) Do() error {
	log.Println("Fetching resources")
	if err := p.Fetch(); err != nil {
		log.Printf("Fetch err: %s\n", err)
	}

	log.Println("Printing resources")
	if err := p.Print(); err != nil {
		return err
	}

	if p.list {
		return nil
	}

	log.Println("Terminating resources")
	if err := p.Terminate(); err != nil {
		return err
	}

	return nil
}

// Print prints all fetched resources
func (p *Purge) Print() error {
	for region, resources := range p.resources {
		fmt.Println("REGION:", region)
		fmt.Printf("\t'%d' instances\n", len(resources.instances))
		fmt.Printf("\t'%d' volumes\n", len(resources.volumes))
		fmt.Printf("\t'%d' keyPairs\n", len(resources.keyPairs))
		fmt.Printf("\t'%d' placementGroups\n", len(resources.placementGroups))
		fmt.Printf("\t'%d' addresses\n", len(resources.addresses))
		fmt.Printf("\t'%d' snapshots\n", len(resources.snapshots))
		fmt.Printf("\t'%d' loadbalancers\n", len(resources.loadBalancers))
		fmt.Printf("\t'%d' securitygroups\n", len(resources.securityGroups))
		fmt.Printf("\t'%d' vpcs\n", len(resources.vpcs))
		fmt.Printf("\t'%d' subnets\n", len(resources.subnets))
		fmt.Printf("\t'%d' networkAcls\n", len(resources.networkAcls))
		fmt.Printf("\t'%d' internetGateways\n", len(resources.internetGateways))
		fmt.Printf("\t'%d' routeTables\n", len(resources.routeTables))
	}
	return nil
}

// Fetch fetches all given resources and stores them internally. To print them
// use the Print() method
func (p *Purge) Fetch() error {
	// EC2
	p.FetchInstances()
	p.FetchVolumes()
	p.FetchKeyPairs()
	p.FetchPlacementGroups()
	p.FetchAddresses()
	p.FetchSnapshots()
	p.FetchLoadBalancers()

	// VPC
	p.FetchVpcs()
	p.FetchSubnets()
	p.FetchSecurityGroups()
	p.FetchNetworkAcls()
	p.FetchInternetGateways()
	p.FetchRouteTables()

	p.fetchWg.Wait()
	return p.fetchErrs
}

// Terminate terminates all resources stored internally
func (p *Purge) Terminate() error {
	// EC2
	log.Println("Deleting EC2 resources")
	p.DeleteInstances()
	p.DeleteVolumes()
	p.DeleteKeyPairs()
	p.DeletePlacementGroups()
	p.DeleteAddresses()
	p.DeleteSnapshots()
	p.DeleteLoadBalancers()

	// VPC
	log.Println("Deleting VPC resources")
	p.DeleteSubnets()
	p.DeleteInternetGateways()
	p.DeleteVPCs()
	// p.DeleteRouteTables()
	// p.DeleteNetworkAcls()
	// p.DeleteSecurityGroups()

	return p.deleteErrs
}
<commit_msg>awspurge: try to delete rt's<commit_after>package awspurge

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/elb"
)

type Config struct {
	Regions        []string `toml:"regions" json:"regions"`
	RegionsExclude []string `toml:"regions_exclude" json:"regions_exclude"`
	AccessKey      string   `toml:"access_key" json:"access_key"`
	SecretKey      string   `toml:"secret_key" json:"secret_key"`

	// AWS Client timeout
	Timeout time.Duration `toml:"timeout" json:"timeout"`

	// If enabled it only fetches and lists resources (it doesn't terminate
	// resources)
	List bool `toml:"list" json:"list"`
}

type resources struct {
	instances        []*ec2.Instance
	volumes          []*ec2.Volume
	keyPairs         []*ec2.KeyPairInfo
	placementGroups  []*ec2.PlacementGroup
	addresses        []*ec2.Address
	snapshots        []*ec2.Snapshot
	loadBalancers    []*elb.LoadBalancerDescription
	securityGroups   []*ec2.SecurityGroup
	vpcs             []*ec2.Vpc
	subnets          []*ec2.Subnet
	networkAcls      []*ec2.NetworkAcl
	internetGateways []*ec2.InternetGateway
	routeTables      []*ec2.RouteTable
}

type Purge struct {
	services *multiRegion
	regions  []string // our own defined regions
	list     bool     // only list, do not terminate if enabled

	// resources represents the current available resources per region. It's
	// populated by the Fetch() method.
	resources  map[string]*resources
	resourceMu sync.Mutex // protects resources

	// fetch synchronization
	fetchWg   sync.WaitGroup
	fetchMu   sync.Mutex
	fetchErrs error

	// deleteErrors
	deleteMu   sync.Mutex
	deleteErrs error
}

func New(conf *Config) (*Purge, error) {
	checkCfg := "Please check your configuration"

	if len(conf.Regions) == 0 {
		return nil, errors.New("AWS Regions are not set. " + checkCfg)
	}

	if conf.AccessKey == "" {
		return nil, errors.New("AWS Access Key is not set. " + checkCfg)
	}

	if conf.SecretKey == "" {
		return nil, errors.New("AWS Secret Key is not set. " + checkCfg)
	}

	if conf.Timeout == 0 {
		conf.Timeout = time.Second * 30
	}

	client := &http.Client{
		Transport: &http.Transport{TLSHandshakeTimeout: conf.Timeout},
		Timeout:   conf.Timeout,
	}

	creds := credentials.NewStaticCredentials(conf.AccessKey, conf.SecretKey, "")
	awsCfg := &aws.Config{
		Credentials: creds,
		HTTPClient:  client,
		Logger:      aws.NewDefaultLogger(),
	}

	regions := filterRegions(conf.Regions, conf.RegionsExclude)
	m := newMultiRegion(awsCfg, regions)

	// initialize resources
	res := make(map[string]*resources, 0)
	for _, region := range regions {
		res[region] = &resources{}
	}

	return &Purge{
		services:  m,
		resources: res,
		regions:   regions,
		list:      conf.List,
	}, nil
}

func (p *Purge) Do() error {
	log.Println("Fetching resources")
	if err := p.Fetch(); err != nil {
		log.Printf("Fetch err: %s\n", err)
	}

	log.Println("Printing resources")
	if err := p.Print(); err != nil {
		return err
	}

	if p.list {
		return nil
	}

	log.Println("Terminating resources")
	if err := p.Terminate(); err != nil {
		return err
	}

	return nil
}

// Print prints all fetched resources
func (p *Purge) Print() error {
	for region, resources := range p.resources {
		fmt.Println("REGION:", region)
		fmt.Printf("\t'%d' instances\n", len(resources.instances))
		fmt.Printf("\t'%d' volumes\n", len(resources.volumes))
		fmt.Printf("\t'%d' keyPairs\n", len(resources.keyPairs))
		fmt.Printf("\t'%d' placementGroups\n", len(resources.placementGroups))
		fmt.Printf("\t'%d' addresses\n", len(resources.addresses))
		fmt.Printf("\t'%d' snapshots\n", len(resources.snapshots))
		fmt.Printf("\t'%d' loadbalancers\n", len(resources.loadBalancers))
		fmt.Printf("\t'%d' securitygroups\n", len(resources.securityGroups))
		fmt.Printf("\t'%d' vpcs\n", len(resources.vpcs))
		fmt.Printf("\t'%d' subnets\n", len(resources.subnets))
		fmt.Printf("\t'%d' networkAcls\n", len(resources.networkAcls))
		fmt.Printf("\t'%d' internetGateways\n", len(resources.internetGateways))
		fmt.Printf("\t'%d' routeTables\n", len(resources.routeTables))
	}
	return nil
}

// Fetch fetches all given resources and stores them internally. To print them
// use the Print() method
func (p *Purge) Fetch() error {
	// EC2
	p.FetchInstances()
	p.FetchVolumes()
	p.FetchKeyPairs()
	p.FetchPlacementGroups()
	p.FetchAddresses()
	p.FetchSnapshots()
	p.FetchLoadBalancers()

	// VPC
	p.FetchVpcs()
	p.FetchSubnets()
	p.FetchSecurityGroups()
	p.FetchNetworkAcls()
	p.FetchInternetGateways()
	p.FetchRouteTables()

	p.fetchWg.Wait()
	return p.fetchErrs
}

// Terminate terminates all resources stored internally
func (p *Purge) Terminate() error {
	// EC2
	log.Println("Deleting EC2 resources")
	p.DeleteInstances()
	p.DeleteVolumes()
	p.DeleteKeyPairs()
	p.DeletePlacementGroups()
	p.DeleteAddresses()
	p.DeleteSnapshots()
	p.DeleteLoadBalancers()

	// VPC
	log.Println("Deleting VPC resources")
	p.DeleteSubnets()
	p.DeleteInternetGateways()
	p.DeleteRouteTables()
	p.DeleteVPCs()
	// p.DeleteSecurityGroups()
	// p.DeleteNetworkAcls()

	return p.deleteErrs
}
<|endoftext|>