本文整理匯總了Golang中github.com/golang/glog.V函數的典型用法代碼示例。如果您正苦於以下問題:Golang V函數的具體用法?Golang V怎麽用?Golang V使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了V函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: StandardErrorMessage
// StandardErrorMessage translates common errors into a human readable message, or returns
// false if the error is not one of the recognized types. It may also log extended
// information to glog.
//
// This method is generic to the command in use and may be used by non-Kubectl
// commands.
func StandardErrorMessage(err error) (string, bool) {
if debugErr, ok := err.(debugError); ok {
glog.V(4).Infof(debugErr.DebugError())
}
status, isStatus := err.(kerrors.APIStatus)
switch {
case isStatus:
switch s := status.Status(); {
case s.Reason == "Unauthorized":
return fmt.Sprintf("error: You must be logged in to the server (%s)", s.Message), true
default:
return fmt.Sprintf("Error from server: %s", err.Error()), true
}
case kerrors.IsUnexpectedObjectError(err):
return fmt.Sprintf("Server returned an unexpected response: %s", err.Error()), true
}
switch t := err.(type) {
case *url.Error:
glog.V(4).Infof("Connection error: %s %s: %v", t.Op, t.URL, t.Err)
switch {
case strings.Contains(t.Err.Error(), "connection refused"):
host := t.URL
if server, err := url.Parse(t.URL); err == nil {
host = server.Host
}
return fmt.Sprintf("The connection to the server %s was refused - did you specify the right host or port?", host), true
}
return fmt.Sprintf("Unable to connect to the server: %v", t.Err), true
}
return "", false
}
示例2: filterCandidates
// Forward those file paths received on candidateCh that are text files to textFileCh.
func filterCandidates(
candidateCh chan string, textFileCh chan string,
ftiMgr *FileTypeInfoManager, ctrl GoRtnCntrl) {
defer ctrl.wg.Done()
glog.V(1).Infoln("ENTER filterCandidates")
defer glog.V(1).Infoln("EXIT filterCandidates")
for {
select {
case <-ctrl.stopCh:
return
case fp, ok := <-candidateCh:
if !ok {
return
}
isText := ftiMgr.FindType(fp)
if isText {
select {
case <-ctrl.stopCh:
return
case textFileCh <- fp:
}
}
}
}
}
示例3: newClusterResourceOverride
// newClusterResourceOverride returns an admission controller for containers that
// configurably overrides container resource request/limits
func newClusterResourceOverride(client clientset.Interface, config io.Reader) (admission.Interface, error) {
parsed, err := ReadConfig(config)
if err != nil {
glog.V(5).Infof("%s admission controller loaded with error: (%T) %[2]v", api.PluginName, err)
return nil, err
}
if errs := validation.Validate(parsed); len(errs) > 0 {
return nil, errs.ToAggregate()
}
glog.V(5).Infof("%s admission controller loaded with config: %v", api.PluginName, parsed)
var internal *internalConfig
if parsed != nil {
internal = &internalConfig{
limitCPUToMemoryRatio: inf.NewDec(parsed.LimitCPUToMemoryPercent, 2),
cpuRequestToLimitRatio: inf.NewDec(parsed.CPURequestToLimitPercent, 2),
memoryRequestToLimitRatio: inf.NewDec(parsed.MemoryRequestToLimitPercent, 2),
}
}
limitRanger, err := limitranger.NewLimitRanger(client, wrapLimit)
if err != nil {
return nil, err
}
return &clusterResourceOverridePlugin{
Handler: admission.NewHandler(admission.Create),
config: internal,
LimitRanger: limitRanger,
}, nil
}
示例4: syncLoop
// syncLoop is the main loop for processing changes. It watches for changes from
// four channels (file, etcd, server, and http) and creates a union of them. For
// any new change seen, will run a sync against desired state and running state. If
// no changes are seen to the configuration, will synchronize the last known desired
// state every sync_frequency seconds. Never returns.
func (kl *Kubelet) syncLoop(updates <-chan PodUpdate, handler SyncHandler) {
for {
select {
case u := <-updates:
switch u.Op {
case SET:
glog.V(3).Infof("SET: Containers changed")
kl.pods = u.Pods
kl.pods = filterHostPortConflicts(kl.pods)
case UPDATE:
glog.V(3).Infof("Update: Containers changed")
kl.pods = updateBoundPods(u.Pods, kl.pods)
kl.pods = filterHostPortConflicts(kl.pods)
default:
panic("syncLoop does not support incremental changes")
}
case <-time.After(kl.resyncInterval):
glog.V(4).Infof("Periodic sync")
}
err := handler.SyncPods(kl.pods)
if err != nil {
glog.Errorf("Couldn't sync containers: %v", err)
}
}
}
示例5: listCollection
// listCollection will list the items in the specified namespace
// it returns the following:
// the list of items in the collection (if found)
// a boolean if the operation is supported
// an error if the operation is supported but could not be completed.
func listCollection(
dynamicClient *dynamic.Client,
opCache operationNotSupportedCache,
gvr unversioned.GroupVersionResource,
namespace string,
) (*runtime.UnstructuredList, bool, error) {
glog.V(5).Infof("namespace controller - listCollection - namespace: %s, gvr: %v", namespace, gvr)
key := operationKey{op: operationList, gvr: gvr}
if !opCache.isSupported(key) {
glog.V(5).Infof("namespace controller - listCollection ignored since not supported - namespace: %s, gvr: %v", namespace, gvr)
return nil, false, nil
}
apiResource := unversioned.APIResource{Name: gvr.Resource, Namespaced: true}
unstructuredList, err := dynamicClient.Resource(&apiResource, namespace).List(v1.ListOptions{})
if err == nil {
return unstructuredList, true, nil
}
// this is strange, but we need to special case for both MethodNotSupported and NotFound errors
// TODO: https://github.com/kubernetes/kubernetes/issues/22413
// we have a resource returned in the discovery API that supports no top-level verbs:
// /apis/extensions/v1beta1/namespaces/default/replicationcontrollers
// when working with this resource type, we will get a literal not found error rather than expected method not supported
// remember next time that this resource does not support delete collection...
if errors.IsMethodNotSupported(err) || errors.IsNotFound(err) {
glog.V(5).Infof("namespace controller - listCollection not supported - namespace: %s, gvr: %v", namespace, gvr)
opCache[key] = true
return nil, false, nil
}
return nil, true, err
}
示例6: makeHandler
// makeHandler wraps our ResponseHandlers while timing requests, collecting,
// stats, logging, and handling errors.
func makeHandler(handler ResponseHandler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
start := time.Now()
httpCode, err := handler(w, r, p)
duration := time.Since(start)
var msg string
if err != nil {
msg = err.Error()
} else if httpCode != http.StatusOK {
msg = http.StatusText(httpCode)
}
if len(msg) > 0 {
http.Error(w, msg, httpCode)
stats.RecordEvent(stats.ErroredRequest)
}
if len(msg) > 0 || glog.V(2) {
reqString := r.URL.Path + " " + r.RemoteAddr
if glog.V(3) {
reqString = r.URL.RequestURI() + " " + r.RemoteAddr
}
if len(msg) > 0 {
glog.Errorf("[API - %9s] %s (%d - %s)", duration, reqString, httpCode, msg)
} else {
glog.Infof("[API - %9s] %s (%d)", duration, reqString, httpCode)
}
}
stats.RecordEvent(stats.HandledRequest)
stats.RecordTiming(stats.ResponseTime, duration)
}
}
示例7: Put
func (ts *timeStore) Put(tp TimePoint) error {
if tp.Value == nil {
return fmt.Errorf("cannot store TimePoint with nil data")
}
if (tp.Timestamp == time.Time{}) {
return fmt.Errorf("cannot store TimePoint with zero timestamp")
}
ts.rwLock.Lock()
defer ts.rwLock.Unlock()
if ts.buffer.Len() == 0 {
glog.V(5).Infof("put pushfront: %v, %v", tp.Timestamp, tp.Value)
ts.buffer.PushFront(tp)
return nil
}
for elem := ts.buffer.Front(); elem != nil; elem = elem.Next() {
if tp.Timestamp.After(elem.Value.(TimePoint).Timestamp) {
glog.V(5).Infof("put insert before: %v, %v, %v", elem, tp.Timestamp, tp.Value)
ts.buffer.InsertBefore(tp, elem)
return nil
}
}
glog.V(5).Infof("put pushback: %v, %v", tp.Timestamp, tp.Value)
ts.buffer.PushBack(tp)
return nil
}
示例8: DecryptProto
// Decrypts a proto using an AEAD. Unmarshals the result into dst. The result
// should only be considered written if this function returns true.
func DecryptProto(aead cipher.AEAD, msg string, additionalData []byte, dst proto.Message) bool {
msgBytes, err := base64.RawURLEncoding.DecodeString(msg)
if err != nil {
glog.V(2).Infof("Tried to decrypt proto with invalid base64: %v", err)
return false
}
var msgProto pb.EncryptedMessage
err = proto.Unmarshal(msgBytes, &msgProto)
if err != nil {
glog.V(2).Infof("Tried to decrypt proto with invalid pb.EncryptedMessage: %v", err)
return false
}
// Decrypt in-place.
plaintext := msgProto.Ciphertext
plaintext, err = aead.Open(plaintext[:0], msgProto.Nonce, msgProto.Ciphertext, additionalData)
if err != nil {
glog.V(2).Infof("Failed to decrypt data: %v", err)
return false
}
err = proto.Unmarshal(plaintext, dst)
if err != nil {
glog.V(2).Infof("Failed to decrypt proto: %v", err)
return false
}
return true
}
示例9: shouldWriteCerts
// shouldWriteCerts determines if the router should ask the cert manager to write out certificates
// it will return true if a route is edge or reencrypt and it has all the required (host/key) certificates
// defined. If the route does not have the certificates defined it will log an info message if the
// router is configured with a default certificate and assume the route is meant to be a wildcard. Otherwise
// it will log a warning. The route will still be written but users may receive browser errors
// for a host/cert mismatch
func (r *templateRouter) shouldWriteCerts(cfg *ServiceAliasConfig) bool {
if cfg.Certificates == nil {
return false
}
if cfg.TLSTermination == routeapi.TLSTerminationEdge || cfg.TLSTermination == routeapi.TLSTerminationReencrypt {
if hasRequiredEdgeCerts(cfg) {
return true
}
if cfg.TLSTermination == routeapi.TLSTerminationReencrypt && hasReencryptDestinationCACert(cfg) {
glog.V(4).Info("a reencrypt route with host %s does not have an edge certificate, using default router certificate", cfg.Host)
return true
}
msg := fmt.Sprintf("a %s terminated route with host %s does not have the required certificates. The route will still be created but no certificates will be written",
cfg.TLSTermination, cfg.Host)
// if a default cert is configured we'll assume it is meant to be a wildcard and only log info
// otherwise we'll consider this a warning
if len(r.defaultCertificate) > 0 {
glog.V(4).Info(msg)
} else {
glog.Warning(msg)
}
return false
}
return false
}
示例10: LoadBalancer
func (os *OpenStack) LoadBalancer() (cloudprovider.LoadBalancer, bool) {
glog.V(4).Info("openstack.LoadBalancer() called")
// TODO: Search for and support Rackspace loadbalancer API, and others.
network, err := openstack.NewNetworkV2(os.provider, gophercloud.EndpointOpts{
Region: os.region,
})
if err != nil {
glog.Warningf("Failed to find neutron endpoint: %v", err)
return nil, false
}
compute, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{
Region: os.region,
})
if err != nil {
glog.Warningf("Failed to find compute endpoint: %v", err)
return nil, false
}
glog.V(1).Info("Claiming to support LoadBalancer")
if os.lbOpts.LBVersion == "v2" {
return &LbaasV2{LoadBalancer{network, compute, os.lbOpts}}, true
} else {
return &LbaasV1{LoadBalancer{network, compute, os.lbOpts}}, true
}
}
示例11: AttachDisk
// Attaches given cinder volume to the compute running kubelet
func (os *OpenStack) AttachDisk(instanceID string, diskName string) (string, error) {
disk, err := os.getVolume(diskName)
if err != nil {
return "", err
}
cClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{
Region: os.region,
})
if err != nil || cClient == nil {
glog.Errorf("Unable to initialize nova client for region: %s", os.region)
return "", err
}
if len(disk.Attachments) > 0 && disk.Attachments[0]["server_id"] != nil {
if instanceID == disk.Attachments[0]["server_id"] {
glog.V(4).Infof("Disk: %q is already attached to compute: %q", diskName, instanceID)
return disk.ID, nil
} else {
errMsg := fmt.Sprintf("Disk %q is attached to a different compute: %q, should be detached before proceeding", diskName, disk.Attachments[0]["server_id"])
glog.Errorf(errMsg)
return "", errors.New(errMsg)
}
}
// add read only flag here if possible spothanis
_, err = volumeattach.Create(cClient, instanceID, &volumeattach.CreateOpts{
VolumeID: disk.ID,
}).Extract()
if err != nil {
glog.Errorf("Failed to attach %s volume to %s compute", diskName, instanceID)
return "", err
}
glog.V(2).Infof("Successfully attached %s volume to %s compute", diskName, instanceID)
return disk.ID, nil
}
示例12: List
func (i *Instances) List(name_filter string) ([]string, error) {
glog.V(4).Infof("openstack List(%v) called", name_filter)
opts := servers.ListOpts{
Name: name_filter,
Status: "ACTIVE",
}
pager := servers.List(i.compute, opts)
ret := make([]string, 0)
err := pager.EachPage(func(page pagination.Page) (bool, error) {
sList, err := servers.ExtractServers(page)
if err != nil {
return false, err
}
for _, server := range sList {
ret = append(ret, server.Name)
}
return true, nil
})
if err != nil {
return nil, err
}
glog.V(3).Infof("Found %v instances matching %v: %v",
len(ret), name_filter, ret)
return ret, nil
}
示例13: decodeLoop
// Since HTTPTransporter.Recv() is already buffered, so we don't need a 'recvLoop' here.
func (m *MesosMessenger) decodeLoop() {
for {
select {
case <-m.stop:
return
default:
}
msg, err := m.tr.Recv()
if err != nil {
if err == discardOnStopError {
log.V(1).Info("exiting decodeLoop, transport shutting down")
return
} else {
panic(fmt.Sprintf("unexpected transport error: %v", err))
}
}
log.V(2).Infof("Receiving message %v from %v\n", msg.Name, msg.UPID)
msg.ProtoMessage = reflect.New(m.installedMessages[msg.Name]).Interface().(proto.Message)
if err := proto.Unmarshal(msg.Bytes, msg.ProtoMessage); err != nil {
log.Errorf("Failed to unmarshal message %v: %v\n", msg, err)
continue
}
// TODO(yifan): Catch panic.
m.installedHandlers[msg.Name](msg.UPID, msg.ProtoMessage)
}
}
示例14: Start
// Start launches a master. It will error if possible, but some background processes may still
// be running and the process should exit after it finishes.
func (m *Master) Start() error {
// Allow privileged containers
// TODO: make this configurable and not the default https://github.com/openshift/origin/issues/662
capabilities.Initialize(capabilities.Capabilities{
AllowPrivileged: true,
PrivilegedSources: capabilities.PrivilegedSources{
HostNetworkSources: []string{kubelettypes.ApiserverSource, kubelettypes.FileSource},
HostPIDSources: []string{kubelettypes.ApiserverSource, kubelettypes.FileSource},
HostIPCSources: []string{kubelettypes.ApiserverSource, kubelettypes.FileSource},
},
})
openshiftConfig, err := origin.BuildMasterConfig(*m.config)
if err != nil {
return err
}
kubeMasterConfig, err := BuildKubernetesMasterConfig(openshiftConfig)
if err != nil {
return err
}
switch {
case m.api:
glog.Infof("Starting master on %s (%s)", m.config.ServingInfo.BindAddress, version.Get().String())
glog.Infof("Public master address is %s", m.config.AssetConfig.MasterPublicURL)
if len(m.config.DisabledFeatures) > 0 {
glog.V(4).Infof("Disabled features: %s", strings.Join(m.config.DisabledFeatures, ", "))
}
glog.Infof("Using images from %q", openshiftConfig.ImageFor("<component>"))
if err := StartAPI(openshiftConfig, kubeMasterConfig); err != nil {
return err
}
case m.controllers:
glog.Infof("Starting controllers on %s (%s)", m.config.ServingInfo.BindAddress, version.Get().String())
if len(m.config.DisabledFeatures) > 0 {
glog.V(4).Infof("Disabled features: %s", strings.Join(m.config.DisabledFeatures, ", "))
}
glog.Infof("Using images from %q", openshiftConfig.ImageFor("<component>"))
if err := startHealth(openshiftConfig); err != nil {
return err
}
}
if m.controllers {
// run controllers asynchronously (not required to be "ready")
go func() {
if err := startControllers(openshiftConfig, kubeMasterConfig); err != nil {
glog.Fatal(err)
}
openshiftConfig.Informers.Start(utilwait.NeverStop)
}()
}
return nil
}
示例15: extractFromDir
// Get as many pod configs as we can from a directory. Return an error iff something
// prevented us from reading anything at all. Do not return an error if only some files
// were problematic.
func (s *sourceFile) extractFromDir(name string) ([]*api.Pod, error) {
dirents, err := filepath.Glob(filepath.Join(name, "[^.]*"))
if err != nil {
return nil, fmt.Errorf("glob failed: %v", err)
}
pods := make([]*api.Pod, 0)
if len(dirents) == 0 {
return pods, nil
}
sort.Strings(dirents)
for _, path := range dirents {
statInfo, err := os.Stat(path)
if err != nil {
glog.V(1).Infof("Can't get metadata for %q: %v", path, err)
continue
}
switch {
case statInfo.Mode().IsDir():
glog.V(1).Infof("Not recursing into config path %q", path)
case statInfo.Mode().IsRegular():
pod, err := s.extractFromFile(path)
if err != nil {
glog.V(1).Infof("Can't process config file %q: %v", path, err)
} else {
pods = append(pods, pod)
}
default:
glog.V(1).Infof("Config path %q is not a directory or file: %v", path, statInfo.Mode())
}
}
return pods, nil
}